]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live-manager.ts
Add live doc in production.yaml
[github/Chocobozzz/PeerTube.git] / server / lib / live-manager.ts
CommitLineData
c6c0fa6c
C
1
2import { AsyncQueue, queue } from 'async'
3import * as chokidar from 'chokidar'
4import { FfmpegCommand } from 'fluent-ffmpeg'
fb719404 5import { ensureDir, stat } from 'fs-extra'
a5cf76af 6import { basename } from 'path'
c6c0fa6c
C
7import { computeResolutionsToTranscode, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
8import { logger } from '@server/helpers/logger'
9import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
fb719404
C
10import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
11import { UserModel } from '@server/models/account/user'
a5cf76af 12import { VideoModel } from '@server/models/video/video'
c6c0fa6c
C
13import { VideoFileModel } from '@server/models/video/video-file'
14import { VideoLiveModel } from '@server/models/video/video-live'
15import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
b5b68755 16import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
c6c0fa6c 17import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
a5cf76af 18import { federateVideoIfNeeded } from './activitypub/videos'
c6c0fa6c 19import { buildSha256Segment } from './hls'
a5cf76af
C
20import { JobQueue } from './job-queue'
21import { PeerTubeSocket } from './peertube-socket'
fb719404 22import { isAbleToUploadVideo } from './user'
c6c0fa6c
C
23import { getHLSDirectory } from './video-paths'
24
fb719404 25import memoizee = require('memoizee')
c6c0fa6c
C
26const NodeRtmpServer = require('node-media-server/node_rtmp_server')
27const context = require('node-media-server/node_core_ctx')
28const nodeMediaServerLogger = require('node-media-server/node_core_logger')
29
30// Disable node media server logs
31nodeMediaServerLogger.setLogType(0)
32
33const config = {
34 rtmp: {
35 port: CONFIG.LIVE.RTMP.PORT,
36 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
37 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
38 ping: VIDEO_LIVE.RTMP.PING,
39 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
40 },
41 transcoding: {
42 ffmpeg: 'ffmpeg'
43 }
44}
45
46type SegmentSha256QueueParam = {
47 operation: 'update' | 'delete'
48 videoUUID: string
49 segmentPath: string
50}
51
52class LiveManager {
53
54 private static instance: LiveManager
55
56 private readonly transSessions = new Map<string, FfmpegCommand>()
a5cf76af 57 private readonly videoSessions = new Map<number, string>()
c6c0fa6c 58 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
fb719404
C
59 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
60
61 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
62 return isAbleToUploadVideo(userId, 1000)
63 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
c6c0fa6c
C
64
65 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
66 private rtmpServer: any
67
68 private constructor () {
69 }
70
71 init () {
a5cf76af
C
72 const events = this.getContext().nodeEvent
73 events.on('postPublish', (sessionId: string, streamPath: string) => {
c6c0fa6c
C
74 logger.debug('RTMP received stream', { id: sessionId, streamPath })
75
76 const splittedPath = streamPath.split('/')
77 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
78 logger.warn('Live path is incorrect.', { streamPath })
79 return this.abortSession(sessionId)
80 }
81
82 this.handleSession(sessionId, streamPath, splittedPath[2])
83 .catch(err => logger.error('Cannot handle sessions.', { err }))
84 })
85
a5cf76af 86 events.on('donePublish', sessionId => {
284ef529 87 logger.info('Live session ended.', { sessionId })
c6c0fa6c
C
88 })
89
90 this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => {
91 const promise = options.operation === 'update'
92 ? this.addSegmentSha(options)
93 : Promise.resolve(this.removeSegmentSha(options))
94
95 promise.then(() => cb())
96 .catch(err => {
97 logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err })
98 cb()
99 })
100 })
101
102 registerConfigChangedHandler(() => {
103 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
104 this.run()
105 return
106 }
107
108 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
109 this.stop()
110 }
111 })
112 }
113
114 run () {
115 logger.info('Running RTMP server.')
116
117 this.rtmpServer = new NodeRtmpServer(config)
118 this.rtmpServer.run()
119 }
120
121 stop () {
122 logger.info('Stopping RTMP server.')
123
124 this.rtmpServer.stop()
125 this.rtmpServer = undefined
126 }
127
128 getSegmentsSha256 (videoUUID: string) {
129 return this.segmentsSha256.get(videoUUID)
130 }
131
a5cf76af
C
132 stopSessionOf (videoId: number) {
133 const sessionId = this.videoSessions.get(videoId)
134 if (!sessionId) return
135
136 this.abortSession(sessionId)
137
fb719404 138 this.onEndTransmuxing(videoId, true)
a5cf76af
C
139 .catch(err => logger.error('Cannot end transmuxing of video %d.', videoId, { err }))
140 }
141
c6c0fa6c
C
142 private getContext () {
143 return context
144 }
145
146 private abortSession (id: string) {
147 const session = this.getContext().sessions.get(id)
284ef529
C
148 if (session) {
149 session.stop()
150 this.getContext().sessions.delete(id)
151 }
c6c0fa6c
C
152
153 const transSession = this.transSessions.get(id)
284ef529
C
154 if (transSession) {
155 transSession.kill('SIGINT')
156 this.transSessions.delete(id)
157 }
c6c0fa6c
C
158 }
159
160 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
161 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
162 if (!videoLive) {
163 logger.warn('Unknown live video with stream key %s.', streamKey)
164 return this.abortSession(sessionId)
165 }
166
167 const video = videoLive.Video
a5cf76af
C
168 if (video.isBlacklisted()) {
169 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
170 return this.abortSession(sessionId)
171 }
172
173 this.videoSessions.set(video.id, sessionId)
174
c6c0fa6c
C
175 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
176
177 const session = this.getContext().sessions.get(sessionId)
178 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
179 ? computeResolutionsToTranscode(session.videoHeight, 'live')
180 : []
181
182 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
183
184 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
185 videoId: video.id,
186 playlistUrl,
187 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
188 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
189 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
190
191 type: VideoStreamingPlaylistType.HLS
192 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
193
c6c0fa6c
C
194 return this.runMuxing({
195 sessionId,
196 videoLive,
197 playlist: videoStreamingPlaylist,
198 streamPath,
199 originalResolution: session.videoHeight,
200 resolutionsEnabled
201 })
202 }
203
204 private async runMuxing (options: {
205 sessionId: string
206 videoLive: MVideoLiveVideo
207 playlist: MStreamingPlaylist
208 streamPath: string
209 resolutionsEnabled: number[]
210 originalResolution: number
211 }) {
212 const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options
fb719404 213 const startStreamDateTime = new Date().getTime()
c6c0fa6c
C
214 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
215
fb719404
C
216 const user = await UserModel.loadByLiveId(videoLive.id)
217 if (!this.livesPerUser.has(user.id)) {
218 this.livesPerUser.set(user.id, [])
219 }
220
221 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
222 const livesOfUser = this.livesPerUser.get(user.id)
223 livesOfUser.push(currentUserLive)
224
c6c0fa6c
C
225 for (let i = 0; i < allResolutions.length; i++) {
226 const resolution = allResolutions[i]
227
228 VideoFileModel.upsert({
229 resolution,
230 size: -1,
231 extname: '.ts',
232 infoHash: null,
233 fps: -1,
234 videoStreamingPlaylistId: playlist.id
235 }).catch(err => {
236 logger.error('Cannot create file for live streaming.', { err })
237 })
238 }
239
240 const outPath = getHLSDirectory(videoLive.Video)
241 await ensureDir(outPath)
242
fb719404
C
243 const deleteSegments = videoLive.saveReplay === false
244
c6c0fa6c
C
245 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
246 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
fb719404
C
247 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, deleteSegments)
248 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
c6c0fa6c
C
249
250 logger.info('Running live muxing/transcoding.')
c6c0fa6c
C
251 this.transSessions.set(sessionId, ffmpegExec)
252
a5cf76af
C
253 const videoUUID = videoLive.Video.uuid
254 const tsWatcher = chokidar.watch(outPath + '/*.ts')
255
fb719404
C
256 const updateSegment = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
257
258 const addHandler = segmentPath => {
259 updateSegment(segmentPath)
260
261 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
262 this.stopSessionOf(videoLive.videoId)
263 }
264
265 if (videoLive.saveReplay === true) {
266 stat(segmentPath)
267 .then(segmentStat => {
268 currentUserLive.size += segmentStat.size
269 })
270 .then(() => this.isQuotaConstraintValid(user, videoLive))
271 .then(quotaValid => {
272 if (quotaValid !== true) {
273 this.stopSessionOf(videoLive.videoId)
274 }
275 })
276 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
277 }
a5cf76af
C
278 }
279
280 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
281
fb719404
C
282 tsWatcher.on('add', p => addHandler(p))
283 tsWatcher.on('change', p => updateSegment(p))
a5cf76af
C
284 tsWatcher.on('unlink', p => deleteHandler(p))
285
286 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
287 masterWatcher.on('add', async () => {
288 try {
289 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
290
291 video.state = VideoState.PUBLISHED
292 await video.save()
293 videoLive.Video = video
294
295 await federateVideoIfNeeded(video, false)
296
297 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
298 } catch (err) {
299 logger.error('Cannot federate video %d.', videoLive.videoId, { err })
300 } finally {
301 masterWatcher.close()
302 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
303 }
304 })
305
c6c0fa6c 306 const onFFmpegEnded = () => {
a5cf76af 307 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', streamPath)
c6c0fa6c 308
284ef529
C
309 this.transSessions.delete(sessionId)
310
a5cf76af
C
311 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
312 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
313
314 this.onEndTransmuxing(videoLive.Video.id)
c6c0fa6c
C
315 .catch(err => logger.error('Error in closed transmuxing.', { err }))
316 }
317
318 ffmpegExec.on('error', (err, stdout, stderr) => {
319 onFFmpegEnded()
320
321 // Don't care that we killed the ffmpeg process
284ef529 322 if (err?.message?.includes('SIGINT')) return
c6c0fa6c
C
323
324 logger.error('Live transcoding error.', { err, stdout, stderr })
325 })
326
327 ffmpegExec.on('end', () => onFFmpegEnded())
c6c0fa6c
C
328 }
329
fb719404
C
330 getLiveQuotaUsedByUser (userId: number) {
331 const currentLives = this.livesPerUser.get(userId)
332 if (!currentLives) return 0
333
334 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
335 }
336
337 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
a5cf76af
C
338 try {
339 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
340 if (!fullVideo) return
c6c0fa6c 341
a5cf76af
C
342 JobQueue.Instance.createJob({
343 type: 'video-live-ending',
344 payload: {
345 videoId: fullVideo.id
346 }
fb719404 347 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
c6c0fa6c 348
a5cf76af
C
349 // FIXME: use end
350 fullVideo.state = VideoState.WAITING_FOR_LIVE
351 await fullVideo.save()
c6c0fa6c 352
a5cf76af 353 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
c6c0fa6c 354
a5cf76af
C
355 await federateVideoIfNeeded(fullVideo, false)
356 } catch (err) {
357 logger.error('Cannot save/federate new video state of live streaming.', { err })
358 }
c6c0fa6c
C
359 }
360
361 private async addSegmentSha (options: SegmentSha256QueueParam) {
362 const segmentName = basename(options.segmentPath)
363 logger.debug('Updating live sha segment %s.', options.segmentPath)
364
365 const shaResult = await buildSha256Segment(options.segmentPath)
366
367 if (!this.segmentsSha256.has(options.videoUUID)) {
368 this.segmentsSha256.set(options.videoUUID, new Map())
369 }
370
371 const filesMap = this.segmentsSha256.get(options.videoUUID)
372 filesMap.set(segmentName, shaResult)
373 }
374
375 private removeSegmentSha (options: SegmentSha256QueueParam) {
376 const segmentName = basename(options.segmentPath)
377
378 logger.debug('Removing live sha segment %s.', options.segmentPath)
379
380 const filesMap = this.segmentsSha256.get(options.videoUUID)
381 if (!filesMap) {
382 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
383 return
384 }
385
386 if (!filesMap.has(segmentName)) {
387 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
388 return
389 }
390
391 filesMap.delete(segmentName)
392 }
393
fb719404
C
394 private isDurationConstraintValid (streamingStartTime: number) {
395 const maxDuration = CONFIG.LIVE.MAX_DURATION
396 // No limit
397 if (maxDuration === null) return true
398
399 const now = new Date().getTime()
400 const max = streamingStartTime + maxDuration
401
402 return now <= max
403 }
404
405 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
406 if (live.saveReplay !== true) return true
407
408 return this.isAbleToUploadVideoWithCache(user.id)
409 }
410
c6c0fa6c
C
411 static get Instance () {
412 return this.instance || (this.instance = new this())
413 }
414}
415
416// ---------------------------------------------------------------------------
417
418export {
419 LiveManager
420}