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