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