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'
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')
28 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
29 const context = require('node-media-server/node_core_ctx')
30 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
32 // Disable node media server logs
33 nodeMediaServerLogger.setLogType(0)
37 port: CONFIG.LIVE.RTMP.PORT,
38 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
39 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
40 ping: VIDEO_LIVE.RTMP.PING,
41 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
50 private static instance: LiveManager
52 private readonly transSessions = new Map<string, FfmpegCommand>()
53 private readonly videoSessions = new Map<number, string>()
54 // Values are Date().getTime()
55 private readonly watchersPerVideo = new Map<number, number[]>()
56 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
57 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
59 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
60 return isAbleToUploadVideo(userId, 1000)
61 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
63 private rtmpServer: any
65 private constructor () {
69 const events = this.getContext().nodeEvent
70 events.on('postPublish', (sessionId: string, streamPath: string) => {
71 logger.debug('RTMP received stream', { id: sessionId, streamPath })
73 const splittedPath = streamPath.split('/')
74 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
75 logger.warn('Live path is incorrect.', { streamPath })
76 return this.abortSession(sessionId)
79 this.handleSession(sessionId, streamPath, splittedPath[2])
80 .catch(err => logger.error('Cannot handle sessions.', { err }))
83 events.on('donePublish', sessionId => {
84 logger.info('Live session ended.', { sessionId })
87 registerConfigChangedHandler(() => {
88 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
93 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
98 // Cleanup broken lives, that were terminated by a server restart for example
99 this.handleBrokenLives()
100 .catch(err => logger.error('Cannot handle broken lives.', { err }))
102 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
106 logger.info('Running RTMP server on port %d', config.rtmp.port)
108 this.rtmpServer = new NodeRtmpServer(config)
109 this.rtmpServer.run()
113 logger.info('Stopping RTMP server.')
115 this.rtmpServer.stop()
116 this.rtmpServer = undefined
120 return !!this.rtmpServer
123 getSegmentsSha256 (videoUUID: string) {
124 return this.segmentsSha256.get(videoUUID)
127 stopSessionOf (videoId: number) {
128 const sessionId = this.videoSessions.get(videoId)
129 if (!sessionId) return
131 this.videoSessions.delete(videoId)
132 this.abortSession(sessionId)
135 getLiveQuotaUsedByUser (userId: number) {
136 const currentLives = this.livesPerUser.get(userId)
137 if (!currentLives) return 0
139 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
142 addViewTo (videoId: number) {
143 if (this.videoSessions.has(videoId) === false) return
145 let watchers = this.watchersPerVideo.get(videoId)
149 this.watchersPerVideo.set(videoId, watchers)
152 watchers.push(new Date().getTime())
155 private getContext () {
159 private abortSession (id: string) {
160 const session = this.getContext().sessions.get(id)
163 this.getContext().sessions.delete(id)
166 const transSession = this.transSessions.get(id)
168 transSession.kill('SIGINT')
169 this.transSessions.delete(id)
173 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
174 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
176 logger.warn('Unknown live video with stream key %s.', streamKey)
177 return this.abortSession(sessionId)
180 const video = videoLive.Video
181 if (video.isBlacklisted()) {
182 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
183 return this.abortSession(sessionId)
186 this.videoSessions.set(video.id, sessionId)
188 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
190 const session = this.getContext().sessions.get(sessionId)
191 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
193 const [ resolutionResult, fps ] = await Promise.all([
194 getVideoFileResolution(rtmpUrl),
195 getVideoFileFPS(rtmpUrl)
198 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
199 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
202 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
204 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
206 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
209 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
210 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
211 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
213 type: VideoStreamingPlaylistType.HLS
214 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
216 return this.runMuxing({
219 playlist: videoStreamingPlaylist,
226 private async runMuxing (options: {
228 videoLive: MVideoLiveVideo
229 playlist: MStreamingPlaylist
232 allResolutions: number[]
234 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
235 const startStreamDateTime = new Date().getTime()
237 const user = await UserModel.loadByLiveId(videoLive.id)
238 if (!this.livesPerUser.has(user.id)) {
239 this.livesPerUser.set(user.id, [])
242 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
243 const livesOfUser = this.livesPerUser.get(user.id)
244 livesOfUser.push(currentUserLive)
246 for (let i = 0; i < allResolutions.length; i++) {
247 const resolution = allResolutions[i]
249 VideoFileModel.upsert({
255 videoStreamingPlaylistId: playlist.id
257 logger.error('Cannot create file for live streaming.', { err })
261 const outPath = getHLSDirectory(videoLive.Video)
262 await ensureDir(outPath)
264 const videoUUID = videoLive.Video.uuid
265 const deleteSegments = videoLive.saveReplay === false
267 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
268 ? await getLiveTranscodingCommand({
278 : getLiveMuxingCommand(rtmpUrl, outPath, deleteSegments)
280 logger.info('Running live muxing/transcoding for %s.', videoUUID)
281 this.transSessions.set(sessionId, ffmpegExec)
283 const tsWatcher = chokidar.watch(outPath + '/*.ts')
285 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
286 const playlistIdMatcher = /^([\d+])-/
288 const processHashSegments = (segmentsToProcess: string[]) => {
289 // Add sha hash of previous segments, because ffmpeg should have finished generating them
290 for (const previousSegment of segmentsToProcess) {
291 this.addSegmentSha(videoUUID, previousSegment)
292 .catch(err => logger.error('Cannot add sha segment of video %s -> %s.', videoUUID, previousSegment, { err }))
296 const addHandler = segmentPath => {
297 logger.debug('Live add handler of %s.', segmentPath)
299 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
301 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
302 processHashSegments(segmentsToProcess)
304 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
306 // Duration constraint check
307 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
308 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
310 this.stopSessionOf(videoLive.videoId)
313 // Check user quota if the user enabled replay saving
314 if (videoLive.saveReplay === true) {
316 .then(segmentStat => {
317 currentUserLive.size += segmentStat.size
319 .then(() => this.isQuotaConstraintValid(user, videoLive))
320 .then(quotaValid => {
321 if (quotaValid !== true) {
322 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
324 this.stopSessionOf(videoLive.videoId)
327 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
331 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
333 tsWatcher.on('add', p => addHandler(p))
334 tsWatcher.on('unlink', p => deleteHandler(p))
336 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
337 masterWatcher.on('add', async () => {
339 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
341 video.state = VideoState.PUBLISHED
343 videoLive.Video = video
346 federateVideoIfNeeded(video, false)
347 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
349 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
350 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
353 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
355 masterWatcher.close()
356 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
360 const onFFmpegEnded = () => {
361 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
363 this.transSessions.delete(sessionId)
364 this.watchersPerVideo.delete(videoLive.videoId)
367 // Wait latest segments generation, and close watchers
369 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
371 // Process remaining segments hash
372 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
373 processHashSegments(segmentsToProcessPerPlaylist[key])
376 .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err }))
378 this.onEndTransmuxing(videoLive.Video.id)
379 .catch(err => logger.error('Error in closed transmuxing.', { err }))
383 ffmpegExec.on('error', (err, stdout, stderr) => {
386 // Don't care that we killed the ffmpeg process
387 if (err?.message?.includes('Exiting normally')) return
389 logger.error('Live transcoding error.', { err, stdout, stderr })
391 this.abortSession(sessionId)
394 ffmpegExec.on('end', () => onFFmpegEnded())
399 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
401 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
402 if (!fullVideo) return
404 JobQueue.Instance.createJob({
405 type: 'video-live-ending',
407 videoId: fullVideo.id
409 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
411 fullVideo.state = VideoState.LIVE_ENDED
412 await fullVideo.save()
414 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
416 await federateVideoIfNeeded(fullVideo, false)
418 logger.error('Cannot save/federate new video state of live streaming.', { err })
422 private async addSegmentSha (videoUUID: string, segmentPath: string) {
423 const segmentName = basename(segmentPath)
424 logger.debug('Adding live sha segment %s.', segmentPath)
426 const shaResult = await buildSha256Segment(segmentPath)
428 if (!this.segmentsSha256.has(videoUUID)) {
429 this.segmentsSha256.set(videoUUID, new Map())
432 const filesMap = this.segmentsSha256.get(videoUUID)
433 filesMap.set(segmentName, shaResult)
436 private removeSegmentSha (videoUUID: string, segmentPath: string) {
437 const segmentName = basename(segmentPath)
439 logger.debug('Removing live sha segment %s.', segmentPath)
441 const filesMap = this.segmentsSha256.get(videoUUID)
443 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
447 if (!filesMap.has(segmentName)) {
448 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
452 filesMap.delete(segmentName)
455 private isDurationConstraintValid (streamingStartTime: number) {
456 const maxDuration = CONFIG.LIVE.MAX_DURATION
458 if (maxDuration === null) return true
460 const now = new Date().getTime()
461 const max = streamingStartTime + maxDuration
466 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
467 if (live.saveReplay !== true) return true
469 return this.isAbleToUploadVideoWithCache(user.id)
472 private async updateLiveViews () {
473 if (!this.isRunning()) return
475 if (!isTestInstance()) logger.info('Updating live video views.')
477 for (const videoId of this.watchersPerVideo.keys()) {
478 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
480 const watchers = this.watchersPerVideo.get(videoId)
482 const numWatchers = watchers.length
484 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
485 video.views = numWatchers
488 await federateVideoIfNeeded(video, false)
490 // Only keep not expired watchers
491 const newWatchers = watchers.filter(w => w > notBefore)
492 this.watchersPerVideo.set(videoId, newWatchers)
494 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
498 private async handleBrokenLives () {
499 const videoIds = await VideoModel.listPublishedLiveIds()
501 for (const id of videoIds) {
502 await this.onEndTransmuxing(id, true)
506 static get Instance () {
507 return this.instance || (this.instance = new this())
511 // ---------------------------------------------------------------------------