2 import { AsyncQueue, queue } from 'async'
3 import * as chokidar from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { ensureDir, stat } from 'fs-extra'
6 import { basename } from 'path'
7 import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution, getVideoStreamCodec, getVideoStreamSize, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
8 import { logger } from '@server/helpers/logger'
9 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
10 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
11 import { UserModel } from '@server/models/account/user'
12 import { VideoModel } from '@server/models/video/video'
13 import { VideoFileModel } from '@server/models/video/video-file'
14 import { VideoLiveModel } from '@server/models/video/video-live'
15 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
16 import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
17 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
18 import { federateVideoIfNeeded } from './activitypub/videos'
19 import { buildSha256Segment } from './hls'
20 import { JobQueue } from './job-queue'
21 import { PeerTubeSocket } from './peertube-socket'
22 import { isAbleToUploadVideo } from './user'
23 import { getHLSDirectory } from './video-paths'
25 import memoizee = require('memoizee')
26 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
27 const context = require('node-media-server/node_core_ctx')
28 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
30 // Disable node media server logs
31 nodeMediaServerLogger.setLogType(0)
35 port: CONFIG.LIVE.RTMP.PORT,
36 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
37 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
38 ping: VIDEO_LIVE.RTMP.PING,
39 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
46 type SegmentSha256QueueParam = {
47 operation: 'update' | 'delete'
54 private static instance: LiveManager
56 private readonly transSessions = new Map<string, FfmpegCommand>()
57 private readonly videoSessions = new Map<number, string>()
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 segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
66 private rtmpServer: any
68 private constructor () {
72 const events = this.getContext().nodeEvent
73 events.on('postPublish', (sessionId: string, streamPath: string) => {
74 logger.debug('RTMP received stream', { id: sessionId, streamPath })
76 const splittedPath = streamPath.split('/')
77 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
78 logger.warn('Live path is incorrect.', { streamPath })
79 return this.abortSession(sessionId)
82 this.handleSession(sessionId, streamPath, splittedPath[2])
83 .catch(err => logger.error('Cannot handle sessions.', { err }))
86 events.on('donePublish', sessionId => {
87 logger.info('Live session ended.', { sessionId })
90 this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => {
91 const promise = options.operation === 'update'
92 ? this.addSegmentSha(options)
93 : Promise.resolve(this.removeSegmentSha(options))
95 promise.then(() => cb())
97 logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err })
102 registerConfigChangedHandler(() => {
103 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
108 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
115 logger.info('Running RTMP server.')
117 this.rtmpServer = new NodeRtmpServer(config)
118 this.rtmpServer.run()
122 logger.info('Stopping RTMP server.')
124 this.rtmpServer.stop()
125 this.rtmpServer = undefined
128 getSegmentsSha256 (videoUUID: string) {
129 return this.segmentsSha256.get(videoUUID)
132 stopSessionOf (videoId: number) {
133 const sessionId = this.videoSessions.get(videoId)
134 if (!sessionId) return
136 this.videoSessions.delete(videoId)
137 this.abortSession(sessionId)
140 getLiveQuotaUsedByUser (userId: number) {
141 const currentLives = this.livesPerUser.get(userId)
142 if (!currentLives) return 0
144 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
147 private getContext () {
151 private abortSession (id: string) {
152 const session = this.getContext().sessions.get(id)
155 this.getContext().sessions.delete(id)
158 const transSession = this.transSessions.get(id)
160 transSession.kill('SIGINT')
161 this.transSessions.delete(id)
165 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
166 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
168 logger.warn('Unknown live video with stream key %s.', streamKey)
169 return this.abortSession(sessionId)
172 const video = videoLive.Video
173 if (video.isBlacklisted()) {
174 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
175 return this.abortSession(sessionId)
178 this.videoSessions.set(video.id, sessionId)
180 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
182 const session = this.getContext().sessions.get(sessionId)
183 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
185 const [ resolutionResult, fps ] = await Promise.all([
186 getVideoFileResolution(rtmpUrl),
187 getVideoFileFPS(rtmpUrl)
190 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
191 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
194 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
196 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
199 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
200 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
201 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
203 type: VideoStreamingPlaylistType.HLS
204 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
206 return this.runMuxing({
209 playlist: videoStreamingPlaylist,
210 originalResolution: session.videoHeight,
217 private async runMuxing (options: {
219 videoLive: MVideoLiveVideo
220 playlist: MStreamingPlaylist
223 resolutionsEnabled: number[]
224 originalResolution: number
226 const { sessionId, videoLive, playlist, resolutionsEnabled, originalResolution, fps, rtmpUrl } = options
227 const startStreamDateTime = new Date().getTime()
228 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
230 const user = await UserModel.loadByLiveId(videoLive.id)
231 if (!this.livesPerUser.has(user.id)) {
232 this.livesPerUser.set(user.id, [])
235 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
236 const livesOfUser = this.livesPerUser.get(user.id)
237 livesOfUser.push(currentUserLive)
239 for (let i = 0; i < allResolutions.length; i++) {
240 const resolution = allResolutions[i]
242 VideoFileModel.upsert({
248 videoStreamingPlaylistId: playlist.id
250 logger.error('Cannot create file for live streaming.', { err })
254 const outPath = getHLSDirectory(videoLive.Video)
255 await ensureDir(outPath)
257 const videoUUID = videoLive.Video.uuid
258 const deleteSegments = videoLive.saveReplay === false
260 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
261 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
262 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
264 logger.info('Running live muxing/transcoding for %s.', videoUUID)
265 this.transSessions.set(sessionId, ffmpegExec)
267 const tsWatcher = chokidar.watch(outPath + '/*.ts')
269 const updateSegment = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
271 const addHandler = segmentPath => {
272 updateSegment(segmentPath)
274 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
275 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
277 this.stopSessionOf(videoLive.videoId)
280 // Check user quota if the user enabled replay saving
281 if (videoLive.saveReplay === true) {
283 .then(segmentStat => {
284 currentUserLive.size += segmentStat.size
286 .then(() => this.isQuotaConstraintValid(user, videoLive))
287 .then(quotaValid => {
288 if (quotaValid !== true) {
289 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
291 this.stopSessionOf(videoLive.videoId)
294 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
298 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
300 tsWatcher.on('add', p => addHandler(p))
301 tsWatcher.on('change', p => updateSegment(p))
302 tsWatcher.on('unlink', p => deleteHandler(p))
304 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
305 masterWatcher.on('add', async () => {
307 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
309 video.state = VideoState.PUBLISHED
311 videoLive.Video = video
313 await federateVideoIfNeeded(video, false)
315 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
317 logger.error('Cannot federate video %d.', videoLive.videoId, { err })
319 masterWatcher.close()
320 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
324 const onFFmpegEnded = () => {
325 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
327 this.transSessions.delete(sessionId)
329 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
330 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
332 this.onEndTransmuxing(videoLive.Video.id)
333 .catch(err => logger.error('Error in closed transmuxing.', { err }))
336 ffmpegExec.on('error', (err, stdout, stderr) => {
339 // Don't care that we killed the ffmpeg process
340 if (err?.message?.includes('Exiting normally')) return
342 logger.error('Live transcoding error.', { err, stdout, stderr })
344 this.abortSession(sessionId)
347 ffmpegExec.on('end', () => onFFmpegEnded())
350 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
352 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
353 if (!fullVideo) return
355 JobQueue.Instance.createJob({
356 type: 'video-live-ending',
358 videoId: fullVideo.id
360 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
362 fullVideo.state = VideoState.LIVE_ENDED
363 await fullVideo.save()
365 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
367 await federateVideoIfNeeded(fullVideo, false)
369 logger.error('Cannot save/federate new video state of live streaming.', { err })
373 private async addSegmentSha (options: SegmentSha256QueueParam) {
374 const segmentName = basename(options.segmentPath)
375 logger.debug('Updating live sha segment %s.', options.segmentPath)
377 const shaResult = await buildSha256Segment(options.segmentPath)
379 if (!this.segmentsSha256.has(options.videoUUID)) {
380 this.segmentsSha256.set(options.videoUUID, new Map())
383 const filesMap = this.segmentsSha256.get(options.videoUUID)
384 filesMap.set(segmentName, shaResult)
387 private removeSegmentSha (options: SegmentSha256QueueParam) {
388 const segmentName = basename(options.segmentPath)
390 logger.debug('Removing live sha segment %s.', options.segmentPath)
392 const filesMap = this.segmentsSha256.get(options.videoUUID)
394 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
398 if (!filesMap.has(segmentName)) {
399 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
403 filesMap.delete(segmentName)
406 private isDurationConstraintValid (streamingStartTime: number) {
407 const maxDuration = CONFIG.LIVE.MAX_DURATION
409 if (maxDuration === null) return true
411 const now = new Date().getTime()
412 const max = streamingStartTime + maxDuration
417 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
418 if (live.saveReplay !== true) return true
420 return this.isAbleToUploadVideoWithCache(user.id)
423 static get Instance () {
424 return this.instance || (this.instance = new this())
428 // ---------------------------------------------------------------------------