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 { createServer, Server } from 'net'
7 import { basename, join } from 'path'
8 import { isTestInstance } from '@server/helpers/core-utils'
9 import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils'
10 import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
11 import { logger, loggerTagsFactory } from '@server/helpers/logger'
12 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
13 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants'
14 import { UserModel } from '@server/models/user/user'
15 import { VideoModel } from '@server/models/video/video'
16 import { VideoFileModel } from '@server/models/video/video-file'
17 import { VideoLiveModel } from '@server/models/video/video-live'
18 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
19 import { MStreamingPlaylist, MStreamingPlaylistVideo, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
20 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
21 import { federateVideoIfNeeded } from './activitypub/videos'
22 import { buildSha256Segment } from './hls'
23 import { JobQueue } from './job-queue'
24 import { cleanupLive } from './job-queue/handlers/video-live-ending'
25 import { PeerTubeSocket } from './peertube-socket'
26 import { VideoTranscodingProfilesManager } from './transcoding/video-transcoding-profiles'
27 import { isAbleToUploadVideo } from './user'
28 import { getHLSDirectory } from './video-paths'
30 import memoizee = require('memoizee')
31 const NodeRtmpSession = require('node-media-server/node_rtmp_session')
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
51 const lTags = loggerTagsFactory('live')
55 private static instance: LiveManager
57 private readonly transSessions = new Map<string, FfmpegCommand>()
58 private readonly videoSessions = new Map<number, string>()
59 // Values are Date().getTime()
60 private readonly watchersPerVideo = new Map<number, number[]>()
61 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
62 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
64 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
65 return isAbleToUploadVideo(userId, 1000)
66 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
68 private readonly hasClientSocketsInBadHealthWithCache = memoizee((sessionId: string) => {
69 return this.hasClientSocketsInBadHealth(sessionId)
70 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
72 private rtmpServer: Server
74 private constructor () {
78 const events = this.getContext().nodeEvent
79 events.on('postPublish', (sessionId: string, streamPath: string) => {
80 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
82 const splittedPath = streamPath.split('/')
83 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
84 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
85 return this.abortSession(sessionId)
88 this.handleSession(sessionId, streamPath, splittedPath[2])
89 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
92 events.on('donePublish', sessionId => {
93 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
96 registerConfigChangedHandler(() => {
97 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
102 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
107 // Cleanup broken lives, that were terminated by a server restart for example
108 this.handleBrokenLives()
109 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
111 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
115 logger.info('Running RTMP server on port %d', config.rtmp.port, lTags())
117 this.rtmpServer = createServer(socket => {
118 const session = new NodeRtmpSession(config, socket)
123 this.rtmpServer.on('error', err => {
124 logger.error('Cannot run RTMP server.', { err, ...lTags() })
127 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
131 logger.info('Stopping RTMP server.', lTags())
133 this.rtmpServer.close()
134 this.rtmpServer = undefined
136 // Sessions is an object
137 this.getContext().sessions.forEach((session: any) => {
138 if (session instanceof NodeRtmpSession) {
145 return !!this.rtmpServer
148 getSegmentsSha256 (videoUUID: string) {
149 return this.segmentsSha256.get(videoUUID)
152 stopSessionOf (videoId: number) {
153 const sessionId = this.videoSessions.get(videoId)
154 if (!sessionId) return
156 this.videoSessions.delete(videoId)
157 this.abortSession(sessionId)
160 getLiveQuotaUsedByUser (userId: number) {
161 const currentLives = this.livesPerUser.get(userId)
162 if (!currentLives) return 0
164 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
167 addViewTo (videoId: number) {
168 if (this.videoSessions.has(videoId) === false) return
170 let watchers = this.watchersPerVideo.get(videoId)
174 this.watchersPerVideo.set(videoId, watchers)
177 watchers.push(new Date().getTime())
180 cleanupShaSegments (videoUUID: string) {
181 this.segmentsSha256.delete(videoUUID)
184 addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
185 const segmentName = basename(segmentPath)
186 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, this.buildConcatenatedName(segmentName))
188 return readFile(segmentPath)
189 .then(data => appendFile(dest, data))
190 .catch(err => logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...lTags() }))
193 buildConcatenatedName (segmentOrPlaylistPath: string) {
194 const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/)
196 return 'concat-' + num[1] + '.ts'
199 private processSegments (hlsVideoPath: string, videoUUID: string, videoLive: MVideoLive, segmentPaths: string[]) {
200 Bluebird.mapSeries(segmentPaths, async previousSegment => {
201 // Add sha hash of previous segments, because ffmpeg should have finished generating them
202 await this.addSegmentSha(videoUUID, previousSegment)
204 if (videoLive.saveReplay) {
205 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
207 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...lTags(videoUUID) }))
210 private getContext () {
214 private abortSession (id: string) {
215 const session = this.getContext().sessions.get(id)
218 this.getContext().sessions.delete(id)
221 const transSession = this.transSessions.get(id)
223 transSession.kill('SIGINT')
224 this.transSessions.delete(id)
228 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
229 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
231 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
232 return this.abortSession(sessionId)
235 const video = videoLive.Video
236 if (video.isBlacklisted()) {
237 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
238 return this.abortSession(sessionId)
241 // Cleanup old potential live files (could happen with a permanent live)
242 this.cleanupShaSegments(video.uuid)
244 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
245 if (oldStreamingPlaylist) {
246 await cleanupLive(video, oldStreamingPlaylist)
249 this.videoSessions.set(video.id, sessionId)
251 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
253 const session = this.getContext().sessions.get(sessionId)
254 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
256 const [ resolutionResult, fps ] = await Promise.all([
257 getVideoFileResolution(rtmpUrl),
258 getVideoFileFPS(rtmpUrl)
261 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
262 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
265 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
268 'Will mux/transcode live video of original resolution %d.', session.videoHeight,
269 { allResolutions, ...lTags(sessionId, video.uuid) }
272 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
275 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
276 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
277 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
279 type: VideoStreamingPlaylistType.HLS
280 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
282 return this.runMuxing({
285 playlist: Object.assign(videoStreamingPlaylist, { Video: video }),
292 private async runMuxing (options: {
294 videoLive: MVideoLiveVideo
295 playlist: MStreamingPlaylistVideo
298 allResolutions: number[]
300 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
301 const startStreamDateTime = new Date().getTime()
303 const user = await UserModel.loadByLiveId(videoLive.id)
304 if (!this.livesPerUser.has(user.id)) {
305 this.livesPerUser.set(user.id, [])
308 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
309 const livesOfUser = this.livesPerUser.get(user.id)
310 livesOfUser.push(currentUserLive)
312 for (let i = 0; i < allResolutions.length; i++) {
313 const resolution = allResolutions[i]
315 const file = new VideoFileModel({
321 videoStreamingPlaylistId: playlist.id
324 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
325 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...lTags(sessionId, videoLive.Video.uuid) }))
328 const outPath = getHLSDirectory(videoLive.Video)
329 await ensureDir(outPath)
331 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
333 if (videoLive.saveReplay === true) {
334 await ensureDir(replayDirectory)
337 const videoUUID = videoLive.Video.uuid
339 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
340 ? await getLiveTranscodingCommand({
343 resolutions: allResolutions,
345 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
346 profile: CONFIG.LIVE.TRANSCODING.PROFILE
348 : getLiveMuxingCommand(rtmpUrl, outPath)
350 logger.info('Running live muxing/transcoding for %s.', videoUUID, lTags(sessionId, videoUUID))
351 this.transSessions.set(sessionId, ffmpegExec)
353 const tsWatcher = chokidar.watch(outPath + '/*.ts')
355 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
356 const playlistIdMatcher = /^([\d+])-/
358 const addHandler = segmentPath => {
359 logger.debug('Live add handler of %s.', segmentPath, lTags(sessionId, videoUUID))
361 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
363 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
364 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcess)
366 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
368 if (this.hasClientSocketsInBadHealthWithCache(sessionId)) {
370 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
371 ' Stopping session of video %s.', videoUUID,
372 lTags(sessionId, videoUUID)
375 this.stopSessionOf(videoLive.videoId)
379 // Duration constraint check
380 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
381 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, lTags(sessionId, videoUUID))
383 this.stopSessionOf(videoLive.videoId)
387 // Check user quota if the user enabled replay saving
388 if (videoLive.saveReplay === true) {
390 .then(segmentStat => {
391 currentUserLive.size += segmentStat.size
393 .then(() => this.isQuotaConstraintValid(user, videoLive))
394 .then(quotaValid => {
395 if (quotaValid !== true) {
396 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, lTags(sessionId, videoUUID))
398 this.stopSessionOf(videoLive.videoId)
401 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err, ...lTags(sessionId, videoUUID) }))
405 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
407 tsWatcher.on('add', p => addHandler(p))
408 tsWatcher.on('unlink', p => deleteHandler(p))
410 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
411 masterWatcher.on('add', async () => {
413 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
415 video.state = VideoState.PUBLISHED
417 videoLive.Video = video
420 federateVideoIfNeeded(video, false)
421 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...lTags(sessionId, videoUUID) }))
423 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
424 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
427 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err, ...lTags(sessionId, videoUUID) })
429 masterWatcher.close()
430 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...lTags(sessionId, videoUUID) }))
434 const onFFmpegEnded = () => {
435 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl, lTags(sessionId, videoUUID))
437 this.transSessions.delete(sessionId)
439 this.watchersPerVideo.delete(videoLive.videoId)
440 this.videoSessions.delete(videoLive.videoId)
442 const newLivesPerUser = this.livesPerUser.get(user.id)
443 .filter(o => o.liveId !== videoLive.id)
444 this.livesPerUser.set(user.id, newLivesPerUser)
447 // Wait latest segments generation, and close watchers
449 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
451 // Process remaining segments hash
452 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
453 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcessPerPlaylist[key])
458 'Cannot close watchers of %s or process remaining hash segments.', outPath,
459 { err, ...lTags(sessionId, videoUUID) }
463 this.onEndTransmuxing(videoLive.Video.id)
464 .catch(err => logger.error('Error in closed transmuxing.', { err, ...lTags(sessionId, videoUUID) }))
468 ffmpegExec.on('error', (err, stdout, stderr) => {
471 // Don't care that we killed the ffmpeg process
472 if (err?.message?.includes('Exiting normally')) return
474 logger.error('Live transcoding error.', { err, stdout, stderr, ...lTags(sessionId, videoUUID) })
476 this.abortSession(sessionId)
479 ffmpegExec.on('end', () => onFFmpegEnded())
484 private async onEndTransmuxing (videoUUID: string, cleanupNow = false) {
486 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
487 if (!fullVideo) return
489 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
491 if (!live.permanentLive) {
492 JobQueue.Instance.createJob({
493 type: 'video-live-ending',
495 videoId: fullVideo.id
497 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
499 fullVideo.state = VideoState.LIVE_ENDED
501 fullVideo.state = VideoState.WAITING_FOR_LIVE
504 await fullVideo.save()
506 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
508 await federateVideoIfNeeded(fullVideo, false)
510 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
514 private async addSegmentSha (videoUUID: string, segmentPath: string) {
515 const segmentName = basename(segmentPath)
516 logger.debug('Adding live sha segment %s.', segmentPath, lTags(videoUUID))
518 const shaResult = await buildSha256Segment(segmentPath)
520 if (!this.segmentsSha256.has(videoUUID)) {
521 this.segmentsSha256.set(videoUUID, new Map())
524 const filesMap = this.segmentsSha256.get(videoUUID)
525 filesMap.set(segmentName, shaResult)
528 private removeSegmentSha (videoUUID: string, segmentPath: string) {
529 const segmentName = basename(segmentPath)
531 logger.debug('Removing live sha segment %s.', segmentPath, lTags(videoUUID))
533 const filesMap = this.segmentsSha256.get(videoUUID)
535 logger.warn('Unknown files map to remove sha for %s.', videoUUID, lTags(videoUUID))
539 if (!filesMap.has(segmentName)) {
540 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath, lTags(videoUUID))
544 filesMap.delete(segmentName)
547 private isDurationConstraintValid (streamingStartTime: number) {
548 const maxDuration = CONFIG.LIVE.MAX_DURATION
550 if (maxDuration < 0) return true
552 const now = new Date().getTime()
553 const max = streamingStartTime + maxDuration
558 private hasClientSocketsInBadHealth (sessionId: string) {
559 const rtmpSession = this.getContext().sessions.get(sessionId)
562 logger.warn('Cannot get session %s to check players socket health.', sessionId, lTags(sessionId))
566 for (const playerSessionId of rtmpSession.players) {
567 const playerSession = this.getContext().sessions.get(playerSessionId)
569 if (!playerSession) {
570 logger.error('Cannot get player session %s to check socket health.', playerSession, lTags(sessionId))
574 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
582 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
583 if (live.saveReplay !== true) return true
585 return this.isAbleToUploadVideoWithCache(user.id)
588 private async updateLiveViews () {
589 if (!this.isRunning()) return
591 if (!isTestInstance()) logger.info('Updating live video views.', lTags())
593 for (const videoId of this.watchersPerVideo.keys()) {
594 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
596 const watchers = this.watchersPerVideo.get(videoId)
598 const numWatchers = watchers.length
600 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
601 video.views = numWatchers
604 await federateVideoIfNeeded(video, false)
606 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
608 // Only keep not expired watchers
609 const newWatchers = watchers.filter(w => w > notBefore)
610 this.watchersPerVideo.set(videoId, newWatchers)
612 logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags())
616 private async handleBrokenLives () {
617 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
619 for (const uuid of videoUUIDs) {
620 await this.onEndTransmuxing(uuid, true)
624 static get Instance () {
625 return this.instance || (this.instance = new this())
629 // ---------------------------------------------------------------------------