1 import { readdir, readFile } from 'fs-extra'
2 import { createServer, Server } from 'net'
3 import { join } from 'path'
4 import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
6 computeResolutionsToTranscode,
10 getVideoStreamDimensionsInfo,
13 } from '@server/helpers/ffmpeg'
14 import { logger, loggerTagsFactory } from '@server/helpers/logger'
15 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
16 import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
17 import { UserModel } from '@server/models/user/user'
18 import { VideoModel } from '@server/models/video/video'
19 import { VideoLiveModel } from '@server/models/video/video-live'
20 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
21 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
22 import { MStreamingPlaylistVideo, MVideo, MVideoLiveSession, MVideoLiveVideo } from '@server/types/models'
23 import { pick, wait } from '@shared/core-utils'
24 import { LiveVideoError, VideoState, VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
25 import { federateVideoIfNeeded } from '../activitypub/videos'
26 import { JobQueue } from '../job-queue'
27 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveReplayBaseDirectory } from '../paths'
28 import { PeerTubeSocket } from '../peertube-socket'
29 import { Hooks } from '../plugins/hooks'
30 import { LiveQuotaStore } from './live-quota-store'
31 import { cleanupAndDestroyPermanentLive } from './live-utils'
32 import { MuxingSession } from './shared'
34 const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
35 const context = require('node-media-server/src/node_core_ctx')
36 const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
38 // Disable node media server logs
39 nodeMediaServerLogger.setLogType(0)
43 port: CONFIG.LIVE.RTMP.PORT,
44 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
45 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
46 ping: VIDEO_LIVE.RTMP.PING,
47 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
51 const lTags = loggerTagsFactory('live')
55 private static instance: LiveManager
57 private readonly muxingSessions = new Map<string, MuxingSession>()
58 private readonly videoSessions = new Map<number, string>()
60 private rtmpServer: Server
61 private rtmpsServer: ServerTLS
63 private running = false
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, ...lTags(sessionId) })
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, ...lTags(sessionId) })
76 return this.abortSession(sessionId)
79 const session = this.getContext().sessions.get(sessionId)
81 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
82 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
85 events.on('donePublish', sessionId => {
86 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
89 registerConfigChangedHandler(() => {
90 if (!this.running && CONFIG.LIVE.ENABLED === true) {
91 this.run().catch(err => logger.error('Cannot run live server.', { err }))
95 if (this.running && CONFIG.LIVE.ENABLED === false) {
100 // Cleanup broken lives, that were terminated by a server restart for example
101 this.handleBrokenLives()
102 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
108 if (CONFIG.LIVE.RTMP.ENABLED) {
109 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
111 this.rtmpServer = createServer(socket => {
112 const session = new NodeRtmpSession(config, socket)
114 session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
118 this.rtmpServer.on('error', err => {
119 logger.error('Cannot run RTMP server.', { err, ...lTags() })
122 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
125 if (CONFIG.LIVE.RTMPS.ENABLED) {
126 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
128 const [ key, cert ] = await Promise.all([
129 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
130 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
132 const serverOptions = { key, cert }
134 this.rtmpsServer = createServerTLS(serverOptions, socket => {
135 const session = new NodeRtmpSession(config, socket)
137 session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
141 this.rtmpsServer.on('error', err => {
142 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
145 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
152 if (this.rtmpServer) {
153 logger.info('Stopping RTMP server.', lTags())
155 this.rtmpServer.close()
156 this.rtmpServer = undefined
159 if (this.rtmpsServer) {
160 logger.info('Stopping RTMPS server.', lTags())
162 this.rtmpsServer.close()
163 this.rtmpsServer = undefined
166 // Sessions is an object
167 this.getContext().sessions.forEach((session: any) => {
168 if (session instanceof NodeRtmpSession) {
175 return !!this.rtmpServer
178 stopSessionOf (videoId: number, error: LiveVideoError | null) {
179 const sessionId = this.videoSessions.get(videoId)
180 if (!sessionId) return
182 this.saveEndingSession(videoId, error)
183 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
185 this.videoSessions.delete(videoId)
186 this.abortSession(sessionId)
189 private getContext () {
193 private abortSession (sessionId: string) {
194 const session = this.getContext().sessions.get(sessionId)
197 this.getContext().sessions.delete(sessionId)
200 const muxingSession = this.muxingSessions.get(sessionId)
202 // Muxing session will fire and event so we correctly cleanup the session
203 muxingSession.abort()
205 this.muxingSessions.delete(sessionId)
209 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
210 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
212 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
213 return this.abortSession(sessionId)
216 const video = videoLive.Video
217 if (video.isBlacklisted()) {
218 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
219 return this.abortSession(sessionId)
222 // Cleanup old potential live (could happen with a permanent live)
223 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
224 if (oldStreamingPlaylist) {
225 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
227 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
230 this.videoSessions.set(video.id, sessionId)
232 const now = Date.now()
233 const probe = await ffprobePromise(inputUrl)
235 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
236 getVideoStreamDimensionsInfo(inputUrl, probe),
237 getVideoStreamFPS(inputUrl, probe),
238 getVideoStreamBitrate(inputUrl, probe),
239 hasAudioStream(inputUrl, probe)
243 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
244 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
247 const allResolutions = await Hooks.wrapObject(
248 this.buildAllResolutionsToTranscode(resolution, hasAudio),
249 'filter:transcoding.auto.resolutions-to-transcode.result',
254 'Will mux/transcode live video of original resolution %d.', resolution,
255 { allResolutions, ...lTags(sessionId, video.uuid) }
258 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
260 return this.runMuxingSession({
274 private async runMuxingSession (options: {
276 videoLive: MVideoLiveVideo
278 streamingPlaylist: MStreamingPlaylistVideo
283 allResolutions: number[]
286 const { sessionId, videoLive } = options
287 const videoUUID = videoLive.Video.uuid
288 const localLTags = lTags(sessionId, videoUUID)
290 const liveSession = await this.saveStartingSession(videoLive)
292 const user = await UserModel.loadByLiveId(videoLive.id)
293 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
295 const muxingSession = new MuxingSession({
296 context: this.getContext(),
301 ...pick(options, [ 'streamingPlaylist', 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
304 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
306 muxingSession.on('bad-socket-health', ({ videoId }) => {
308 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
309 ' Stopping session of video %s.', videoUUID,
313 this.stopSessionOf(videoId, LiveVideoError.BAD_SOCKET_HEALTH)
316 muxingSession.on('duration-exceeded', ({ videoId }) => {
317 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
319 this.stopSessionOf(videoId, LiveVideoError.DURATION_EXCEEDED)
322 muxingSession.on('quota-exceeded', ({ videoId }) => {
323 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
325 this.stopSessionOf(videoId, LiveVideoError.QUOTA_EXCEEDED)
328 muxingSession.on('ffmpeg-error', ({ videoId }) => {
329 this.stopSessionOf(videoId, LiveVideoError.FFMPEG_ERROR)
332 muxingSession.on('ffmpeg-end', ({ videoId }) => {
333 this.onMuxingFFmpegEnd(videoId, sessionId)
336 muxingSession.on('after-cleanup', ({ videoId }) => {
337 this.muxingSessions.delete(sessionId)
339 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
341 muxingSession.destroy()
343 return this.onAfterMuxingCleanup({ videoId, liveSession })
344 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
347 this.muxingSessions.set(sessionId, muxingSession)
349 muxingSession.runMuxing()
351 logger.error('Cannot run muxing.', { err, ...localLTags })
352 this.abortSession(sessionId)
356 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
357 const videoId = live.videoId
360 const video = await VideoModel.loadFull(videoId)
362 logger.info('Will publish and federate live %s.', video.url, localLTags)
364 video.state = VideoState.PUBLISHED
365 video.publishedAt = new Date()
370 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
373 await federateVideoIfNeeded(video, false)
375 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
378 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
380 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
384 private onMuxingFFmpegEnd (videoId: number, sessionId: string) {
385 this.videoSessions.delete(videoId)
387 this.saveEndingSession(videoId, null)
388 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
391 private async onAfterMuxingCleanup (options: {
392 videoId: number | string
393 liveSession?: MVideoLiveSession
394 cleanupNow?: boolean // Default false
396 const { videoId, liveSession: liveSessionArg, cleanupNow = false } = options
399 const fullVideo = await VideoModel.loadFull(videoId)
400 if (!fullVideo) return
402 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
404 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
406 // On server restart during a live
407 if (!liveSession.endDate) {
408 liveSession.endDate = new Date()
409 await liveSession.save()
412 JobQueue.Instance.createJobAsync({
413 type: 'video-live-ending',
415 videoId: fullVideo.id,
417 replayDirectory: live.saveReplay
418 ? await this.findReplayDirectory(fullVideo)
421 liveSessionId: liveSession.id,
422 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
424 publishedAt: fullVideo.publishedAt.toISOString()
429 : VIDEO_LIVE.CLEANUP_DELAY
432 fullVideo.state = live.permanentLive
433 ? VideoState.WAITING_FOR_LIVE
434 : VideoState.LIVE_ENDED
436 await fullVideo.save()
438 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
440 await federateVideoIfNeeded(fullVideo, false)
442 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') })
446 private async handleBrokenLives () {
447 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
449 for (const uuid of videoUUIDs) {
450 await this.onAfterMuxingCleanup({ videoId: uuid, cleanupNow: true })
454 private async findReplayDirectory (video: MVideo) {
455 const directory = getLiveReplayBaseDirectory(video)
456 const files = await readdir(directory)
458 if (files.length === 0) return undefined
460 return join(directory, files.sort().reverse()[0])
463 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
464 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
466 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
467 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
470 if (resolutionsEnabled.length === 0) {
471 return [ originResolution ]
474 return resolutionsEnabled
477 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
478 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
480 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
481 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
483 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
484 playlist.type = VideoStreamingPlaylistType.HLS
486 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
487 ? VideoStorage.OBJECT_STORAGE
488 : VideoStorage.FILE_SYSTEM
490 if (playlist.storage === VideoStorage.FILE_SYSTEM) {
491 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
494 return playlist.save()
497 private saveStartingSession (videoLive: MVideoLiveVideo) {
498 const liveSession = new VideoLiveSessionModel({
499 startDate: new Date(),
500 liveVideoId: videoLive.videoId,
501 saveReplay: videoLive.saveReplay,
502 endingProcessed: false
505 return liveSession.save()
508 private async saveEndingSession (videoId: number, error: LiveVideoError | null) {
509 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoId)
510 if (!liveSession) return
512 liveSession.endDate = new Date()
513 liveSession.error = error
515 return liveSession.save()
518 static get Instance () {
519 return this.instance || (this.instance = new this())
523 // ---------------------------------------------------------------------------