2 import * as Bluebird from 'bluebird'
3 import * as chokidar from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
6 import { basename, join } from 'path'
7 import { isTestInstance } from '@server/helpers/core-utils'
8 import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils'
9 import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
10 import { logger } from '@server/helpers/logger'
11 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
12 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants'
13 import { UserModel } from '@server/models/account/user'
14 import { VideoModel } from '@server/models/video/video'
15 import { VideoFileModel } from '@server/models/video/video-file'
16 import { VideoLiveModel } from '@server/models/video/video-live'
17 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
18 import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
19 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
20 import { federateVideoIfNeeded } from './activitypub/videos'
21 import { buildSha256Segment } from './hls'
22 import { JobQueue } from './job-queue'
23 import { cleanupLive } from './job-queue/handlers/video-live-ending'
24 import { PeerTubeSocket } from './peertube-socket'
25 import { isAbleToUploadVideo } from './user'
26 import { getHLSDirectory } from './video-paths'
27 import { availableEncoders } from './video-transcoding-profiles'
29 import memoizee = require('memoizee')
31 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
32 const context = require('node-media-server/node_core_ctx')
33 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
35 // Disable node media server logs
36 nodeMediaServerLogger.setLogType(0)
40 port: CONFIG.LIVE.RTMP.PORT,
41 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
42 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
43 ping: VIDEO_LIVE.RTMP.PING,
44 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
53 private static instance: LiveManager
55 private readonly transSessions = new Map<string, FfmpegCommand>()
56 private readonly videoSessions = new Map<number, string>()
57 // Values are Date().getTime()
58 private readonly watchersPerVideo = new Map<number, number[]>()
59 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
60 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
62 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
63 return isAbleToUploadVideo(userId, 1000)
64 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
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 registerConfigChangedHandler(() => {
91 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
96 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
101 // Cleanup broken lives, that were terminated by a server restart for example
102 this.handleBrokenLives()
103 .catch(err => logger.error('Cannot handle broken lives.', { err }))
105 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
109 logger.info('Running RTMP server on port %d', config.rtmp.port)
111 this.rtmpServer = new NodeRtmpServer(config)
112 this.rtmpServer.run()
116 logger.info('Stopping RTMP server.')
118 this.rtmpServer.stop()
119 this.rtmpServer = undefined
123 return !!this.rtmpServer
126 getSegmentsSha256 (videoUUID: string) {
127 return this.segmentsSha256.get(videoUUID)
130 stopSessionOf (videoId: number) {
131 const sessionId = this.videoSessions.get(videoId)
132 if (!sessionId) return
134 this.videoSessions.delete(videoId)
135 this.abortSession(sessionId)
138 getLiveQuotaUsedByUser (userId: number) {
139 const currentLives = this.livesPerUser.get(userId)
140 if (!currentLives) return 0
142 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
145 addViewTo (videoId: number) {
146 if (this.videoSessions.has(videoId) === false) return
148 let watchers = this.watchersPerVideo.get(videoId)
152 this.watchersPerVideo.set(videoId, watchers)
155 watchers.push(new Date().getTime())
158 cleanupShaSegments (videoUUID: string) {
159 this.segmentsSha256.delete(videoUUID)
162 addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
163 const segmentName = basename(segmentPath)
164 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, this.buildConcatenatedName(segmentName))
166 return readFile(segmentPath)
167 .then(data => appendFile(dest, data))
168 .catch(err => logger.error('Cannot copy segment %s to repay directory.', segmentPath, { err }))
171 buildConcatenatedName (segmentOrPlaylistPath: string) {
172 const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/)
174 return 'concat-' + num[1] + '.ts'
177 private processSegments (hlsVideoPath: string, videoUUID: string, videoLive: MVideoLive, segmentPaths: string[]) {
178 Bluebird.mapSeries(segmentPaths, async previousSegment => {
179 // Add sha hash of previous segments, because ffmpeg should have finished generating them
180 await this.addSegmentSha(videoUUID, previousSegment)
182 if (videoLive.saveReplay) {
183 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
185 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err }))
188 private getContext () {
192 private abortSession (id: string) {
193 const session = this.getContext().sessions.get(id)
196 this.getContext().sessions.delete(id)
199 const transSession = this.transSessions.get(id)
201 transSession.kill('SIGINT')
202 this.transSessions.delete(id)
206 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
207 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
209 logger.warn('Unknown live video with stream key %s.', streamKey)
210 return this.abortSession(sessionId)
213 const video = videoLive.Video
214 if (video.isBlacklisted()) {
215 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
216 return this.abortSession(sessionId)
219 // Cleanup old potential live files (could happen with a permanent live)
220 this.cleanupShaSegments(video.uuid)
222 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
223 if (oldStreamingPlaylist) {
224 await cleanupLive(video, oldStreamingPlaylist)
227 this.videoSessions.set(video.id, sessionId)
229 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
231 const session = this.getContext().sessions.get(sessionId)
232 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
234 const [ resolutionResult, fps ] = await Promise.all([
235 getVideoFileResolution(rtmpUrl),
236 getVideoFileFPS(rtmpUrl)
239 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
240 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
243 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
245 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
247 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
250 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
251 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
252 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
254 type: VideoStreamingPlaylistType.HLS
255 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
257 return this.runMuxing({
260 playlist: videoStreamingPlaylist,
267 private async runMuxing (options: {
269 videoLive: MVideoLiveVideo
270 playlist: MStreamingPlaylist
273 allResolutions: number[]
275 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
276 const startStreamDateTime = new Date().getTime()
278 const user = await UserModel.loadByLiveId(videoLive.id)
279 if (!this.livesPerUser.has(user.id)) {
280 this.livesPerUser.set(user.id, [])
283 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
284 const livesOfUser = this.livesPerUser.get(user.id)
285 livesOfUser.push(currentUserLive)
287 for (let i = 0; i < allResolutions.length; i++) {
288 const resolution = allResolutions[i]
290 const file = new VideoFileModel({
296 videoStreamingPlaylistId: playlist.id
299 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
300 .catch(err => logger.error('Cannot create file for live streaming.', { err }))
303 const outPath = getHLSDirectory(videoLive.Video)
304 await ensureDir(outPath)
306 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
308 if (videoLive.saveReplay === true) {
309 await ensureDir(replayDirectory)
312 const videoUUID = videoLive.Video.uuid
314 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
315 ? await getLiveTranscodingCommand({
318 resolutions: allResolutions,
323 : getLiveMuxingCommand(rtmpUrl, outPath)
325 logger.info('Running live muxing/transcoding for %s.', videoUUID)
326 this.transSessions.set(sessionId, ffmpegExec)
328 const tsWatcher = chokidar.watch(outPath + '/*.ts')
330 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
331 const playlistIdMatcher = /^([\d+])-/
333 const addHandler = segmentPath => {
334 logger.debug('Live add handler of %s.', segmentPath)
336 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
338 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
339 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcess)
341 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
343 // Duration constraint check
344 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
345 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
347 this.stopSessionOf(videoLive.videoId)
350 // Check user quota if the user enabled replay saving
351 if (videoLive.saveReplay === true) {
353 .then(segmentStat => {
354 currentUserLive.size += segmentStat.size
356 .then(() => this.isQuotaConstraintValid(user, videoLive))
357 .then(quotaValid => {
358 if (quotaValid !== true) {
359 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
361 this.stopSessionOf(videoLive.videoId)
364 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
368 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
370 tsWatcher.on('add', p => addHandler(p))
371 tsWatcher.on('unlink', p => deleteHandler(p))
373 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
374 masterWatcher.on('add', async () => {
376 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
378 video.state = VideoState.PUBLISHED
380 videoLive.Video = video
383 federateVideoIfNeeded(video, false)
384 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
386 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
387 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
390 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
392 masterWatcher.close()
393 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
397 const onFFmpegEnded = () => {
398 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
400 this.transSessions.delete(sessionId)
402 this.watchersPerVideo.delete(videoLive.videoId)
403 this.videoSessions.delete(videoLive.videoId)
405 const newLivesPerUser = this.livesPerUser.get(user.id)
406 .filter(o => o.liveId !== videoLive.id)
407 this.livesPerUser.set(user.id, newLivesPerUser)
410 // Wait latest segments generation, and close watchers
412 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
414 // Process remaining segments hash
415 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
416 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcessPerPlaylist[key])
419 .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err }))
421 this.onEndTransmuxing(videoLive.Video.id)
422 .catch(err => logger.error('Error in closed transmuxing.', { err }))
426 ffmpegExec.on('error', (err, stdout, stderr) => {
429 // Don't care that we killed the ffmpeg process
430 if (err?.message?.includes('Exiting normally')) return
432 logger.error('Live transcoding error.', { err, stdout, stderr })
434 this.abortSession(sessionId)
437 ffmpegExec.on('end', () => onFFmpegEnded())
442 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
444 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
445 if (!fullVideo) return
447 const live = await VideoLiveModel.loadByVideoId(videoId)
449 if (!live.permanentLive) {
450 JobQueue.Instance.createJob({
451 type: 'video-live-ending',
453 videoId: fullVideo.id
455 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
457 fullVideo.state = VideoState.LIVE_ENDED
459 fullVideo.state = VideoState.WAITING_FOR_LIVE
462 await fullVideo.save()
464 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
466 await federateVideoIfNeeded(fullVideo, false)
468 logger.error('Cannot save/federate new video state of live streaming.', { err })
472 private async addSegmentSha (videoUUID: string, segmentPath: string) {
473 const segmentName = basename(segmentPath)
474 logger.debug('Adding live sha segment %s.', segmentPath)
476 const shaResult = await buildSha256Segment(segmentPath)
478 if (!this.segmentsSha256.has(videoUUID)) {
479 this.segmentsSha256.set(videoUUID, new Map())
482 const filesMap = this.segmentsSha256.get(videoUUID)
483 filesMap.set(segmentName, shaResult)
486 private removeSegmentSha (videoUUID: string, segmentPath: string) {
487 const segmentName = basename(segmentPath)
489 logger.debug('Removing live sha segment %s.', segmentPath)
491 const filesMap = this.segmentsSha256.get(videoUUID)
493 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
497 if (!filesMap.has(segmentName)) {
498 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
502 filesMap.delete(segmentName)
505 private isDurationConstraintValid (streamingStartTime: number) {
506 const maxDuration = CONFIG.LIVE.MAX_DURATION
508 if (maxDuration === null) return true
510 const now = new Date().getTime()
511 const max = streamingStartTime + maxDuration
516 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
517 if (live.saveReplay !== true) return true
519 return this.isAbleToUploadVideoWithCache(user.id)
522 private async updateLiveViews () {
523 if (!this.isRunning()) return
525 if (!isTestInstance()) logger.info('Updating live video views.')
527 for (const videoId of this.watchersPerVideo.keys()) {
528 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
530 const watchers = this.watchersPerVideo.get(videoId)
532 const numWatchers = watchers.length
534 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
535 video.views = numWatchers
538 await federateVideoIfNeeded(video, false)
540 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
542 // Only keep not expired watchers
543 const newWatchers = watchers.filter(w => w > notBefore)
544 this.watchersPerVideo.set(videoId, newWatchers)
546 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
550 private async handleBrokenLives () {
551 const videoIds = await VideoModel.listPublishedLiveIds()
553 for (const id of videoIds) {
554 await this.onEndTransmuxing(id, true)
558 static get Instance () {
559 return this.instance || (this.instance = new this())
563 // ---------------------------------------------------------------------------