2 import * as chokidar from 'chokidar'
3 import { FfmpegCommand } from 'fluent-ffmpeg'
4 import { ensureDir, stat } from 'fs-extra'
5 import { basename } from 'path'
6 import { isTestInstance } from '@server/helpers/core-utils'
8 computeResolutionsToTranscode,
10 getVideoFileResolution,
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'
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')
36 // Disable node media server logs
37 nodeMediaServerLogger.setLogType(0)
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
54 private static instance: LiveManager
56 private readonly transSessions = new Map<string, FfmpegCommand>()
57 private readonly videoSessions = new Map<number, string>()
58 // Values are Date().getTime()
59 private readonly watchersPerVideo = new Map<number, number[]>()
60 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
61 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
63 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
64 return isAbleToUploadVideo(userId, 1000)
65 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
67 private rtmpServer: any
69 private constructor () {
73 const events = this.getContext().nodeEvent
74 events.on('postPublish', (sessionId: string, streamPath: string) => {
75 logger.debug('RTMP received stream', { id: sessionId, streamPath })
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)
83 this.handleSession(sessionId, streamPath, splittedPath[2])
84 .catch(err => logger.error('Cannot handle sessions.', { err }))
87 events.on('donePublish', sessionId => {
88 logger.info('Live session ended.', { sessionId })
91 registerConfigChangedHandler(() => {
92 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
97 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
102 // Cleanup broken lives, that were terminated by a server restart for example
103 this.handleBrokenLives()
104 .catch(err => logger.error('Cannot handle broken lives.', { err }))
106 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
110 logger.info('Running RTMP server on port %d', config.rtmp.port)
112 this.rtmpServer = new NodeRtmpServer(config)
113 this.rtmpServer.run()
117 logger.info('Stopping RTMP server.')
119 this.rtmpServer.stop()
120 this.rtmpServer = undefined
124 return !!this.rtmpServer
127 getSegmentsSha256 (videoUUID: string) {
128 return this.segmentsSha256.get(videoUUID)
131 stopSessionOf (videoId: number) {
132 const sessionId = this.videoSessions.get(videoId)
133 if (!sessionId) return
135 this.videoSessions.delete(videoId)
136 this.abortSession(sessionId)
139 getLiveQuotaUsedByUser (userId: number) {
140 const currentLives = this.livesPerUser.get(userId)
141 if (!currentLives) return 0
143 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
146 addViewTo (videoId: number) {
147 if (this.videoSessions.has(videoId) === false) return
149 let watchers = this.watchersPerVideo.get(videoId)
153 this.watchersPerVideo.set(videoId, watchers)
156 watchers.push(new Date().getTime())
159 private getContext () {
163 private abortSession (id: string) {
164 const session = this.getContext().sessions.get(id)
167 this.getContext().sessions.delete(id)
170 const transSession = this.transSessions.get(id)
172 transSession.kill('SIGINT')
173 this.transSessions.delete(id)
177 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
178 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
180 logger.warn('Unknown live video with stream key %s.', streamKey)
181 return this.abortSession(sessionId)
184 const video = videoLive.Video
185 if (video.isBlacklisted()) {
186 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
187 return this.abortSession(sessionId)
190 this.videoSessions.set(video.id, sessionId)
192 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
194 const session = this.getContext().sessions.get(sessionId)
195 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
197 const [ resolutionResult, fps ] = await Promise.all([
198 getVideoFileResolution(rtmpUrl),
199 getVideoFileFPS(rtmpUrl)
202 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
203 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
206 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
208 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
210 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
213 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
214 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
215 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
217 type: VideoStreamingPlaylistType.HLS
218 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
220 return this.runMuxing({
223 playlist: videoStreamingPlaylist,
230 private async runMuxing (options: {
232 videoLive: MVideoLiveVideo
233 playlist: MStreamingPlaylist
236 allResolutions: number[]
238 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
239 const startStreamDateTime = new Date().getTime()
241 const user = await UserModel.loadByLiveId(videoLive.id)
242 if (!this.livesPerUser.has(user.id)) {
243 this.livesPerUser.set(user.id, [])
246 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
247 const livesOfUser = this.livesPerUser.get(user.id)
248 livesOfUser.push(currentUserLive)
250 for (let i = 0; i < allResolutions.length; i++) {
251 const resolution = allResolutions[i]
253 VideoFileModel.upsert({
259 videoStreamingPlaylistId: playlist.id
261 logger.error('Cannot create file for live streaming.', { err })
265 const outPath = getHLSDirectory(videoLive.Video)
266 await ensureDir(outPath)
268 const videoUUID = videoLive.Video.uuid
269 const deleteSegments = videoLive.saveReplay === false
271 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
272 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
273 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
275 logger.info('Running live muxing/transcoding for %s.', videoUUID)
276 this.transSessions.set(sessionId, ffmpegExec)
278 const tsWatcher = chokidar.watch(outPath + '/*.ts')
280 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
281 const playlistIdMatcher = /^([\d+])-/
283 const processHashSegments = (segmentsToProcess: string[]) => {
284 // Add sha hash of previous segments, because ffmpeg should have finished generating them
285 for (const previousSegment of segmentsToProcess) {
286 this.addSegmentSha(videoUUID, previousSegment)
287 .catch(err => logger.error('Cannot add sha segment of video %s -> %s.', videoUUID, previousSegment, { err }))
291 const addHandler = segmentPath => {
292 logger.debug('Live add handler of %s.', segmentPath)
294 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
296 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
297 processHashSegments(segmentsToProcess)
299 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
301 // Duration constraint check
302 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
303 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
305 this.stopSessionOf(videoLive.videoId)
308 // Check user quota if the user enabled replay saving
309 if (videoLive.saveReplay === true) {
311 .then(segmentStat => {
312 currentUserLive.size += segmentStat.size
314 .then(() => this.isQuotaConstraintValid(user, videoLive))
315 .then(quotaValid => {
316 if (quotaValid !== true) {
317 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
319 this.stopSessionOf(videoLive.videoId)
322 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
326 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
328 tsWatcher.on('add', p => addHandler(p))
329 tsWatcher.on('unlink', p => deleteHandler(p))
331 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
332 masterWatcher.on('add', async () => {
334 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
336 video.state = VideoState.PUBLISHED
338 videoLive.Video = video
341 federateVideoIfNeeded(video, false)
342 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
344 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
345 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
348 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
350 masterWatcher.close()
351 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
355 const onFFmpegEnded = () => {
356 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
358 this.transSessions.delete(sessionId)
359 this.watchersPerVideo.delete(videoLive.videoId)
362 // Wait latest segments generation, and close watchers
364 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
366 // Process remaining segments hash
367 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
368 processHashSegments(segmentsToProcessPerPlaylist[key])
371 .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err }))
373 this.onEndTransmuxing(videoLive.Video.id)
374 .catch(err => logger.error('Error in closed transmuxing.', { err }))
378 ffmpegExec.on('error', (err, stdout, stderr) => {
381 // Don't care that we killed the ffmpeg process
382 if (err?.message?.includes('Exiting normally')) return
384 logger.error('Live transcoding error.', { err, stdout, stderr })
386 this.abortSession(sessionId)
389 ffmpegExec.on('end', () => onFFmpegEnded())
392 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
394 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
395 if (!fullVideo) return
397 JobQueue.Instance.createJob({
398 type: 'video-live-ending',
400 videoId: fullVideo.id
402 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
404 fullVideo.state = VideoState.LIVE_ENDED
405 await fullVideo.save()
407 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
409 await federateVideoIfNeeded(fullVideo, false)
411 logger.error('Cannot save/federate new video state of live streaming.', { err })
415 private async addSegmentSha (videoUUID: string, segmentPath: string) {
416 const segmentName = basename(segmentPath)
417 logger.debug('Adding live sha segment %s.', segmentPath)
419 const shaResult = await buildSha256Segment(segmentPath)
421 if (!this.segmentsSha256.has(videoUUID)) {
422 this.segmentsSha256.set(videoUUID, new Map())
425 const filesMap = this.segmentsSha256.get(videoUUID)
426 filesMap.set(segmentName, shaResult)
429 private removeSegmentSha (videoUUID: string, segmentPath: string) {
430 const segmentName = basename(segmentPath)
432 logger.debug('Removing live sha segment %s.', segmentPath)
434 const filesMap = this.segmentsSha256.get(videoUUID)
436 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
440 if (!filesMap.has(segmentName)) {
441 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
445 filesMap.delete(segmentName)
448 private isDurationConstraintValid (streamingStartTime: number) {
449 const maxDuration = CONFIG.LIVE.MAX_DURATION
451 if (maxDuration === null) return true
453 const now = new Date().getTime()
454 const max = streamingStartTime + maxDuration
459 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
460 if (live.saveReplay !== true) return true
462 return this.isAbleToUploadVideoWithCache(user.id)
465 private async updateLiveViews () {
466 if (!this.isRunning()) return
468 if (!isTestInstance()) logger.info('Updating live video views.')
470 for (const videoId of this.watchersPerVideo.keys()) {
471 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
473 const watchers = this.watchersPerVideo.get(videoId)
475 const numWatchers = watchers.length
477 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
478 video.views = numWatchers
481 await federateVideoIfNeeded(video, false)
483 // Only keep not expired watchers
484 const newWatchers = watchers.filter(w => w > notBefore)
485 this.watchersPerVideo.set(videoId, newWatchers)
487 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
491 private async handleBrokenLives () {
492 const videoIds = await VideoModel.listPublishedLiveIds()
494 for (const id of videoIds) {
495 await this.onEndTransmuxing(id, true)
499 static get Instance () {
500 return this.instance || (this.instance = new this())
504 // ---------------------------------------------------------------------------