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