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 { PeerTubeSocket } from './peertube-socket'
23 import { isAbleToUploadVideo } from './user'
24 import { getHLSDirectory } from './video-paths'
25 import { availableEncoders } from './video-transcoding-profiles'
27 import memoizee = require('memoizee')
29 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
30 const context = require('node-media-server/node_core_ctx')
31 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
33 // Disable node media server logs
34 nodeMediaServerLogger.setLogType(0)
38 port: CONFIG.LIVE.RTMP.PORT,
39 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
40 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
41 ping: VIDEO_LIVE.RTMP.PING,
42 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
51 private static instance: LiveManager
53 private readonly transSessions = new Map<string, FfmpegCommand>()
54 private readonly videoSessions = new Map<number, string>()
55 // Values are Date().getTime()
56 private readonly watchersPerVideo = new Map<number, number[]>()
57 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
58 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
60 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
61 return isAbleToUploadVideo(userId, 1000)
62 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
64 private rtmpServer: any
66 private constructor () {
70 const events = this.getContext().nodeEvent
71 events.on('postPublish', (sessionId: string, streamPath: string) => {
72 logger.debug('RTMP received stream', { id: sessionId, streamPath })
74 const splittedPath = streamPath.split('/')
75 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
76 logger.warn('Live path is incorrect.', { streamPath })
77 return this.abortSession(sessionId)
80 this.handleSession(sessionId, streamPath, splittedPath[2])
81 .catch(err => logger.error('Cannot handle sessions.', { err }))
84 events.on('donePublish', sessionId => {
85 logger.info('Live session ended.', { sessionId })
88 registerConfigChangedHandler(() => {
89 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
94 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
99 // Cleanup broken lives, that were terminated by a server restart for example
100 this.handleBrokenLives()
101 .catch(err => logger.error('Cannot handle broken lives.', { err }))
103 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
107 logger.info('Running RTMP server on port %d', config.rtmp.port)
109 this.rtmpServer = new NodeRtmpServer(config)
110 this.rtmpServer.run()
114 logger.info('Stopping RTMP server.')
116 this.rtmpServer.stop()
117 this.rtmpServer = undefined
121 return !!this.rtmpServer
124 getSegmentsSha256 (videoUUID: string) {
125 return this.segmentsSha256.get(videoUUID)
128 stopSessionOf (videoId: number) {
129 const sessionId = this.videoSessions.get(videoId)
130 if (!sessionId) return
132 this.videoSessions.delete(videoId)
133 this.abortSession(sessionId)
136 getLiveQuotaUsedByUser (userId: number) {
137 const currentLives = this.livesPerUser.get(userId)
138 if (!currentLives) return 0
140 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
143 addViewTo (videoId: number) {
144 if (this.videoSessions.has(videoId) === false) return
146 let watchers = this.watchersPerVideo.get(videoId)
150 this.watchersPerVideo.set(videoId, watchers)
153 watchers.push(new Date().getTime())
156 private getContext () {
160 private abortSession (id: string) {
161 const session = this.getContext().sessions.get(id)
164 this.getContext().sessions.delete(id)
167 const transSession = this.transSessions.get(id)
169 transSession.kill('SIGINT')
170 this.transSessions.delete(id)
174 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
175 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
177 logger.warn('Unknown live video with stream key %s.', streamKey)
178 return this.abortSession(sessionId)
181 const video = videoLive.Video
182 if (video.isBlacklisted()) {
183 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
184 return this.abortSession(sessionId)
187 this.videoSessions.set(video.id, sessionId)
189 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
191 const session = this.getContext().sessions.get(sessionId)
192 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
194 const [ resolutionResult, fps ] = await Promise.all([
195 getVideoFileResolution(rtmpUrl),
196 getVideoFileFPS(rtmpUrl)
199 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
200 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
203 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
205 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
207 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
210 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
211 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
212 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
214 type: VideoStreamingPlaylistType.HLS
215 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
217 return this.runMuxing({
220 playlist: videoStreamingPlaylist,
227 private async runMuxing (options: {
229 videoLive: MVideoLiveVideo
230 playlist: MStreamingPlaylist
233 allResolutions: number[]
235 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
236 const startStreamDateTime = new Date().getTime()
238 const user = await UserModel.loadByLiveId(videoLive.id)
239 if (!this.livesPerUser.has(user.id)) {
240 this.livesPerUser.set(user.id, [])
243 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
244 const livesOfUser = this.livesPerUser.get(user.id)
245 livesOfUser.push(currentUserLive)
247 for (let i = 0; i < allResolutions.length; i++) {
248 const resolution = allResolutions[i]
250 VideoFileModel.upsert({
256 videoStreamingPlaylistId: playlist.id
258 logger.error('Cannot create file for live streaming.', { err })
262 const outPath = getHLSDirectory(videoLive.Video)
263 await ensureDir(outPath)
265 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
267 if (videoLive.saveReplay === true) {
268 await ensureDir(replayDirectory)
271 const videoUUID = videoLive.Video.uuid
273 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
274 ? await getLiveTranscodingCommand({
277 resolutions: allResolutions,
282 : getLiveMuxingCommand(rtmpUrl, outPath)
284 logger.info('Running live muxing/transcoding for %s.', videoUUID)
285 this.transSessions.set(sessionId, ffmpegExec)
287 const tsWatcher = chokidar.watch(outPath + '/*.ts')
289 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
290 const playlistIdMatcher = /^([\d+])-/
292 const processSegments = (segmentsToProcess: string[]) => {
293 // Add sha hash of previous segments, because ffmpeg should have finished generating them
294 for (const previousSegment of segmentsToProcess) {
295 this.addSegmentSha(videoUUID, previousSegment)
296 .catch(err => logger.error('Cannot add sha segment of video %s -> %s.', videoUUID, previousSegment, { err }))
298 if (videoLive.saveReplay) {
299 const segmentName = basename(previousSegment)
301 copy(previousSegment, join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY, segmentName))
302 .catch(err => logger.error('Cannot copy segment %s to repay directory.', previousSegment, { err }))
307 const addHandler = segmentPath => {
308 logger.debug('Live add handler of %s.', segmentPath)
310 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
312 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
313 processSegments(segmentsToProcess)
315 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
317 // Duration constraint check
318 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
319 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
321 this.stopSessionOf(videoLive.videoId)
324 // Check user quota if the user enabled replay saving
325 if (videoLive.saveReplay === true) {
327 .then(segmentStat => {
328 currentUserLive.size += segmentStat.size
330 .then(() => this.isQuotaConstraintValid(user, videoLive))
331 .then(quotaValid => {
332 if (quotaValid !== true) {
333 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
335 this.stopSessionOf(videoLive.videoId)
338 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
342 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
344 tsWatcher.on('add', p => addHandler(p))
345 tsWatcher.on('unlink', p => deleteHandler(p))
347 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
348 masterWatcher.on('add', async () => {
350 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
352 video.state = VideoState.PUBLISHED
354 videoLive.Video = video
357 federateVideoIfNeeded(video, false)
358 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
360 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
361 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
364 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
366 masterWatcher.close()
367 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
371 const onFFmpegEnded = () => {
372 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
374 this.transSessions.delete(sessionId)
375 this.watchersPerVideo.delete(videoLive.videoId)
378 // Wait latest segments generation, and close watchers
380 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
382 // Process remaining segments hash
383 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
384 processSegments(segmentsToProcessPerPlaylist[key])
387 .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err }))
389 this.onEndTransmuxing(videoLive.Video.id)
390 .catch(err => logger.error('Error in closed transmuxing.', { err }))
394 ffmpegExec.on('error', (err, stdout, stderr) => {
397 // Don't care that we killed the ffmpeg process
398 if (err?.message?.includes('Exiting normally')) return
400 logger.error('Live transcoding error.', { err, stdout, stderr })
402 this.abortSession(sessionId)
405 ffmpegExec.on('end', () => onFFmpegEnded())
410 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
412 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
413 if (!fullVideo) return
415 JobQueue.Instance.createJob({
416 type: 'video-live-ending',
418 videoId: fullVideo.id
420 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
422 fullVideo.state = VideoState.LIVE_ENDED
423 await fullVideo.save()
425 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
427 await federateVideoIfNeeded(fullVideo, false)
429 logger.error('Cannot save/federate new video state of live streaming.', { err })
433 private async addSegmentSha (videoUUID: string, segmentPath: string) {
434 const segmentName = basename(segmentPath)
435 logger.debug('Adding live sha segment %s.', segmentPath)
437 const shaResult = await buildSha256Segment(segmentPath)
439 if (!this.segmentsSha256.has(videoUUID)) {
440 this.segmentsSha256.set(videoUUID, new Map())
443 const filesMap = this.segmentsSha256.get(videoUUID)
444 filesMap.set(segmentName, shaResult)
447 private removeSegmentSha (videoUUID: string, segmentPath: string) {
448 const segmentName = basename(segmentPath)
450 logger.debug('Removing live sha segment %s.', segmentPath)
452 const filesMap = this.segmentsSha256.get(videoUUID)
454 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
458 if (!filesMap.has(segmentName)) {
459 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
463 filesMap.delete(segmentName)
466 private isDurationConstraintValid (streamingStartTime: number) {
467 const maxDuration = CONFIG.LIVE.MAX_DURATION
469 if (maxDuration === null) return true
471 const now = new Date().getTime()
472 const max = streamingStartTime + maxDuration
477 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
478 if (live.saveReplay !== true) return true
480 return this.isAbleToUploadVideoWithCache(user.id)
483 private async updateLiveViews () {
484 if (!this.isRunning()) return
486 if (!isTestInstance()) logger.info('Updating live video views.')
488 for (const videoId of this.watchersPerVideo.keys()) {
489 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
491 const watchers = this.watchersPerVideo.get(videoId)
493 const numWatchers = watchers.length
495 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
496 video.views = numWatchers
499 await federateVideoIfNeeded(video, false)
501 // Only keep not expired watchers
502 const newWatchers = watchers.filter(w => w > notBefore)
503 this.watchersPerVideo.set(videoId, newWatchers)
505 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
509 private async handleBrokenLives () {
510 const videoIds = await VideoModel.listPublishedLiveIds()
512 for (const id of videoIds) {
513 await this.onEndTransmuxing(id, true)
517 static get Instance () {
518 return this.instance || (this.instance = new this())
522 // ---------------------------------------------------------------------------