2 import * as chokidar from 'chokidar'
3 import { FfmpegCommand } from 'fluent-ffmpeg'
4 import { copy, ensureDir, stat } from 'fs-extra'
5 import { basename, join } from 'path'
6 import { isTestInstance } from '@server/helpers/core-utils'
7 import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils'
8 import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
9 import { logger } from '@server/helpers/logger'
10 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
11 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants'
12 import { UserModel } from '@server/models/account/user'
13 import { VideoModel } from '@server/models/video/video'
14 import { VideoFileModel } from '@server/models/video/video-file'
15 import { VideoLiveModel } from '@server/models/video/video-live'
16 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
17 import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
18 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
19 import { federateVideoIfNeeded } from './activitypub/videos'
20 import { buildSha256Segment } from './hls'
21 import { JobQueue } from './job-queue'
22 import { cleanupLive } from './job-queue/handlers/video-live-ending'
23 import { PeerTubeSocket } from './peertube-socket'
24 import { isAbleToUploadVideo } from './user'
25 import { getHLSDirectory } from './video-paths'
26 import { availableEncoders } from './video-transcoding-profiles'
28 import memoizee = require('memoizee')
30 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
31 const context = require('node-media-server/node_core_ctx')
32 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
34 // Disable node media server logs
35 nodeMediaServerLogger.setLogType(0)
39 port: CONFIG.LIVE.RTMP.PORT,
40 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
41 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
42 ping: VIDEO_LIVE.RTMP.PING,
43 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
52 private static instance: LiveManager
54 private readonly transSessions = new Map<string, FfmpegCommand>()
55 private readonly videoSessions = new Map<number, string>()
56 // Values are Date().getTime()
57 private readonly watchersPerVideo = new Map<number, number[]>()
58 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
59 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
61 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
62 return isAbleToUploadVideo(userId, 1000)
63 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
65 private rtmpServer: any
67 private constructor () {
71 const events = this.getContext().nodeEvent
72 events.on('postPublish', (sessionId: string, streamPath: string) => {
73 logger.debug('RTMP received stream', { id: sessionId, streamPath })
75 const splittedPath = streamPath.split('/')
76 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
77 logger.warn('Live path is incorrect.', { streamPath })
78 return this.abortSession(sessionId)
81 this.handleSession(sessionId, streamPath, splittedPath[2])
82 .catch(err => logger.error('Cannot handle sessions.', { err }))
85 events.on('donePublish', sessionId => {
86 logger.info('Live session ended.', { sessionId })
89 registerConfigChangedHandler(() => {
90 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
95 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
100 // Cleanup broken lives, that were terminated by a server restart for example
101 this.handleBrokenLives()
102 .catch(err => logger.error('Cannot handle broken lives.', { err }))
104 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
108 logger.info('Running RTMP server on port %d', config.rtmp.port)
110 this.rtmpServer = new NodeRtmpServer(config)
111 this.rtmpServer.run()
115 logger.info('Stopping RTMP server.')
117 this.rtmpServer.stop()
118 this.rtmpServer = undefined
122 return !!this.rtmpServer
125 getSegmentsSha256 (videoUUID: string) {
126 return this.segmentsSha256.get(videoUUID)
129 stopSessionOf (videoId: number) {
130 const sessionId = this.videoSessions.get(videoId)
131 if (!sessionId) return
133 this.videoSessions.delete(videoId)
134 this.abortSession(sessionId)
137 getLiveQuotaUsedByUser (userId: number) {
138 const currentLives = this.livesPerUser.get(userId)
139 if (!currentLives) return 0
141 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
144 addViewTo (videoId: number) {
145 if (this.videoSessions.has(videoId) === false) return
147 let watchers = this.watchersPerVideo.get(videoId)
151 this.watchersPerVideo.set(videoId, watchers)
154 watchers.push(new Date().getTime())
157 cleanupShaSegments (videoUUID: string) {
158 this.segmentsSha256.delete(videoUUID)
161 private getContext () {
165 private abortSession (id: string) {
166 const session = this.getContext().sessions.get(id)
169 this.getContext().sessions.delete(id)
172 const transSession = this.transSessions.get(id)
174 transSession.kill('SIGINT')
175 this.transSessions.delete(id)
179 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
180 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
182 logger.warn('Unknown live video with stream key %s.', streamKey)
183 return this.abortSession(sessionId)
186 const video = videoLive.Video
187 if (video.isBlacklisted()) {
188 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
189 return this.abortSession(sessionId)
192 // Cleanup old potential live files (could happen with a permanent live)
193 this.cleanupShaSegments(video.uuid)
195 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
196 if (oldStreamingPlaylist) {
197 await cleanupLive(video, oldStreamingPlaylist)
200 this.videoSessions.set(video.id, sessionId)
202 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
204 const session = this.getContext().sessions.get(sessionId)
205 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
207 const [ resolutionResult, fps ] = await Promise.all([
208 getVideoFileResolution(rtmpUrl),
209 getVideoFileFPS(rtmpUrl)
212 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
213 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
216 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
218 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
220 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
223 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
224 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
225 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
227 type: VideoStreamingPlaylistType.HLS
228 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
230 return this.runMuxing({
233 playlist: videoStreamingPlaylist,
240 private async runMuxing (options: {
242 videoLive: MVideoLiveVideo
243 playlist: MStreamingPlaylist
246 allResolutions: number[]
248 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
249 const startStreamDateTime = new Date().getTime()
251 const user = await UserModel.loadByLiveId(videoLive.id)
252 if (!this.livesPerUser.has(user.id)) {
253 this.livesPerUser.set(user.id, [])
256 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
257 const livesOfUser = this.livesPerUser.get(user.id)
258 livesOfUser.push(currentUserLive)
260 for (let i = 0; i < allResolutions.length; i++) {
261 const resolution = allResolutions[i]
263 VideoFileModel.upsert({
269 videoStreamingPlaylistId: playlist.id
271 logger.error('Cannot create file for live streaming.', { err })
275 const outPath = getHLSDirectory(videoLive.Video)
276 await ensureDir(outPath)
278 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
280 if (videoLive.saveReplay === true) {
281 await ensureDir(replayDirectory)
284 const videoUUID = videoLive.Video.uuid
286 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
287 ? await getLiveTranscodingCommand({
290 resolutions: allResolutions,
295 : getLiveMuxingCommand(rtmpUrl, outPath)
297 logger.info('Running live muxing/transcoding for %s.', videoUUID)
298 this.transSessions.set(sessionId, ffmpegExec)
300 const tsWatcher = chokidar.watch(outPath + '/*.ts')
302 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
303 const playlistIdMatcher = /^([\d+])-/
305 const processSegments = (segmentsToProcess: string[]) => {
306 // Add sha hash of previous segments, because ffmpeg should have finished generating them
307 for (const previousSegment of segmentsToProcess) {
308 this.addSegmentSha(videoUUID, previousSegment)
309 .catch(err => logger.error('Cannot add sha segment of video %s -> %s.', videoUUID, previousSegment, { err }))
311 if (videoLive.saveReplay) {
312 const segmentName = basename(previousSegment)
314 copy(previousSegment, join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY, segmentName))
315 .catch(err => logger.error('Cannot copy segment %s to repay directory.', previousSegment, { err }))
320 const addHandler = segmentPath => {
321 logger.debug('Live add handler of %s.', segmentPath)
323 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
325 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
326 processSegments(segmentsToProcess)
328 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
330 // Duration constraint check
331 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
332 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
334 this.stopSessionOf(videoLive.videoId)
337 // Check user quota if the user enabled replay saving
338 if (videoLive.saveReplay === true) {
340 .then(segmentStat => {
341 currentUserLive.size += segmentStat.size
343 .then(() => this.isQuotaConstraintValid(user, videoLive))
344 .then(quotaValid => {
345 if (quotaValid !== true) {
346 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
348 this.stopSessionOf(videoLive.videoId)
351 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
355 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
357 tsWatcher.on('add', p => addHandler(p))
358 tsWatcher.on('unlink', p => deleteHandler(p))
360 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
361 masterWatcher.on('add', async () => {
363 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
365 video.state = VideoState.PUBLISHED
367 videoLive.Video = video
370 federateVideoIfNeeded(video, false)
371 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
373 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
374 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
377 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
379 masterWatcher.close()
380 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
384 const onFFmpegEnded = () => {
385 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
387 this.transSessions.delete(sessionId)
389 this.watchersPerVideo.delete(videoLive.videoId)
390 this.videoSessions.delete(videoLive.videoId)
392 const newLivesPerUser = this.livesPerUser.get(user.id)
393 .filter(o => o.liveId !== videoLive.id)
394 this.livesPerUser.set(user.id, newLivesPerUser)
397 // Wait latest segments generation, and close watchers
399 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
401 // Process remaining segments hash
402 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
403 processSegments(segmentsToProcessPerPlaylist[key])
406 .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err }))
408 this.onEndTransmuxing(videoLive.Video.id)
409 .catch(err => logger.error('Error in closed transmuxing.', { err }))
413 ffmpegExec.on('error', (err, stdout, stderr) => {
416 // Don't care that we killed the ffmpeg process
417 if (err?.message?.includes('Exiting normally')) return
419 logger.error('Live transcoding error.', { err, stdout, stderr })
421 this.abortSession(sessionId)
424 ffmpegExec.on('end', () => onFFmpegEnded())
429 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
431 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
432 if (!fullVideo) return
434 const live = await VideoLiveModel.loadByVideoId(videoId)
436 if (!live.permanentLive) {
437 JobQueue.Instance.createJob({
438 type: 'video-live-ending',
440 videoId: fullVideo.id
442 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
444 fullVideo.state = VideoState.LIVE_ENDED
446 fullVideo.state = VideoState.WAITING_FOR_LIVE
449 await fullVideo.save()
451 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
453 await federateVideoIfNeeded(fullVideo, false)
455 logger.error('Cannot save/federate new video state of live streaming.', { err })
459 private async addSegmentSha (videoUUID: string, segmentPath: string) {
460 const segmentName = basename(segmentPath)
461 logger.debug('Adding live sha segment %s.', segmentPath)
463 const shaResult = await buildSha256Segment(segmentPath)
465 if (!this.segmentsSha256.has(videoUUID)) {
466 this.segmentsSha256.set(videoUUID, new Map())
469 const filesMap = this.segmentsSha256.get(videoUUID)
470 filesMap.set(segmentName, shaResult)
473 private removeSegmentSha (videoUUID: string, segmentPath: string) {
474 const segmentName = basename(segmentPath)
476 logger.debug('Removing live sha segment %s.', segmentPath)
478 const filesMap = this.segmentsSha256.get(videoUUID)
480 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
484 if (!filesMap.has(segmentName)) {
485 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
489 filesMap.delete(segmentName)
492 private isDurationConstraintValid (streamingStartTime: number) {
493 const maxDuration = CONFIG.LIVE.MAX_DURATION
495 if (maxDuration === null) return true
497 const now = new Date().getTime()
498 const max = streamingStartTime + maxDuration
503 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
504 if (live.saveReplay !== true) return true
506 return this.isAbleToUploadVideoWithCache(user.id)
509 private async updateLiveViews () {
510 if (!this.isRunning()) return
512 if (!isTestInstance()) logger.info('Updating live video views.')
514 for (const videoId of this.watchersPerVideo.keys()) {
515 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
517 const watchers = this.watchersPerVideo.get(videoId)
519 const numWatchers = watchers.length
521 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
522 video.views = numWatchers
525 await federateVideoIfNeeded(video, false)
527 // Only keep not expired watchers
528 const newWatchers = watchers.filter(w => w > notBefore)
529 this.watchersPerVideo.set(videoId, newWatchers)
531 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
535 private async handleBrokenLives () {
536 const videoIds = await VideoModel.listPublishedLiveIds()
538 for (const id of videoIds) {
539 await this.onEndTransmuxing(id, true)
543 static get Instance () {
544 return this.instance || (this.instance = new this())
548 // ---------------------------------------------------------------------------