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 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 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
204 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
207 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
208 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
209 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
211 type: VideoStreamingPlaylistType.HLS
212 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
214 return this.runMuxing({
217 playlist: videoStreamingPlaylist,
218 originalResolution: session.videoHeight,
225 private async runMuxing (options: {
227 videoLive: MVideoLiveVideo
228 playlist: MStreamingPlaylist
231 resolutionsEnabled: number[]
232 originalResolution: number
234 const { sessionId, videoLive, playlist, resolutionsEnabled, originalResolution, fps, rtmpUrl } = options
235 const startStreamDateTime = new Date().getTime()
236 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
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 videoUUID = videoLive.Video.uuid
266 const deleteSegments = videoLive.saveReplay === false
268 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
269 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
270 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
272 logger.info('Running live muxing/transcoding for %s.', videoUUID)
273 this.transSessions.set(sessionId, ffmpegExec)
275 const tsWatcher = chokidar.watch(outPath + '/*.ts')
277 let segmentsToProcess: string[] = []
279 const addHandler = segmentPath => {
280 // Add sha hash of previous segments, because ffmpeg should have finished generating them
281 for (const previousSegment of segmentsToProcess) {
282 this.addSegmentSha(videoUUID, previousSegment)
283 .catch(err => logger.error('Cannot add sha segment of video %s -> %s.', videoUUID, previousSegment, { err }))
286 segmentsToProcess = [ segmentPath ]
288 // Duration constraint check
289 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
290 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
292 this.stopSessionOf(videoLive.videoId)
295 // Check user quota if the user enabled replay saving
296 if (videoLive.saveReplay === true) {
298 .then(segmentStat => {
299 currentUserLive.size += segmentStat.size
301 .then(() => this.isQuotaConstraintValid(user, videoLive))
302 .then(quotaValid => {
303 if (quotaValid !== true) {
304 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
306 this.stopSessionOf(videoLive.videoId)
309 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
313 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
315 tsWatcher.on('add', p => addHandler(p))
316 tsWatcher.on('unlink', p => deleteHandler(p))
318 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
319 masterWatcher.on('add', async () => {
321 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
323 video.state = VideoState.PUBLISHED
325 videoLive.Video = video
327 await federateVideoIfNeeded(video, false)
329 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
331 logger.error('Cannot federate video %d.', videoLive.videoId, { err })
333 masterWatcher.close()
334 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
338 const onFFmpegEnded = () => {
339 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
341 this.transSessions.delete(sessionId)
342 this.watchersPerVideo.delete(videoLive.videoId)
344 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
345 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
347 this.onEndTransmuxing(videoLive.Video.id)
348 .catch(err => logger.error('Error in closed transmuxing.', { err }))
351 ffmpegExec.on('error', (err, stdout, stderr) => {
354 // Don't care that we killed the ffmpeg process
355 if (err?.message?.includes('Exiting normally')) return
357 logger.error('Live transcoding error.', { err, stdout, stderr })
359 this.abortSession(sessionId)
362 ffmpegExec.on('end', () => onFFmpegEnded())
365 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
367 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
368 if (!fullVideo) return
370 JobQueue.Instance.createJob({
371 type: 'video-live-ending',
373 videoId: fullVideo.id
375 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
377 fullVideo.state = VideoState.LIVE_ENDED
378 await fullVideo.save()
380 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
382 await federateVideoIfNeeded(fullVideo, false)
384 logger.error('Cannot save/federate new video state of live streaming.', { err })
388 private async addSegmentSha (videoUUID: string, segmentPath: string) {
389 const segmentName = basename(segmentPath)
390 logger.debug('Adding live sha segment %s.', segmentPath)
392 const shaResult = await buildSha256Segment(segmentPath)
394 if (!this.segmentsSha256.has(videoUUID)) {
395 this.segmentsSha256.set(videoUUID, new Map())
398 const filesMap = this.segmentsSha256.get(videoUUID)
399 filesMap.set(segmentName, shaResult)
402 private removeSegmentSha (videoUUID: string, segmentPath: string) {
403 const segmentName = basename(segmentPath)
405 logger.debug('Removing live sha segment %s.', segmentPath)
407 const filesMap = this.segmentsSha256.get(videoUUID)
409 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
413 if (!filesMap.has(segmentName)) {
414 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
418 filesMap.delete(segmentName)
421 private isDurationConstraintValid (streamingStartTime: number) {
422 const maxDuration = CONFIG.LIVE.MAX_DURATION
424 if (maxDuration === null) return true
426 const now = new Date().getTime()
427 const max = streamingStartTime + maxDuration
432 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
433 if (live.saveReplay !== true) return true
435 return this.isAbleToUploadVideoWithCache(user.id)
438 private async updateLiveViews () {
439 if (!this.isRunning()) return
441 if (!isTestInstance()) logger.info('Updating live video views.')
443 for (const videoId of this.watchersPerVideo.keys()) {
444 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
446 const watchers = this.watchersPerVideo.get(videoId)
448 const numWatchers = watchers.length
450 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
451 video.views = numWatchers
454 await federateVideoIfNeeded(video, false)
456 // Only keep not expired watchers
457 const newWatchers = watchers.filter(w => w > notBefore)
458 this.watchersPerVideo.set(videoId, newWatchers)
460 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
464 static get Instance () {
465 return this.instance || (this.instance = new this())
469 // ---------------------------------------------------------------------------