2 import { readdir, readFile } from 'fs-extra'
3 import { createServer, Server } from 'net'
4 import { join } from 'path'
5 import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
7 computeLowerResolutionsToTranscode,
10 getVideoStreamBitrate,
11 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 { wait } from '@shared/core-utils'
24 import { LiveVideoError, VideoState, 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 { LiveQuotaStore } from './live-quota-store'
30 import { cleanupPermanentLive } from './live-utils'
31 import { MuxingSession } from './shared'
33 const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
34 const context = require('node-media-server/src/node_core_ctx')
35 const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
37 // Disable node media server logs
38 nodeMediaServerLogger.setLogType(0)
42 port: CONFIG.LIVE.RTMP.PORT,
43 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
44 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
45 ping: VIDEO_LIVE.RTMP.PING,
46 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
50 const lTags = loggerTagsFactory('live')
54 private static instance: LiveManager
56 private readonly muxingSessions = new Map<string, MuxingSession>()
57 private readonly videoSessions = new Map<number, string>()
59 private rtmpServer: Server
60 private rtmpsServer: ServerTLS
62 private running = false
64 private constructor () {
68 const events = this.getContext().nodeEvent
69 events.on('postPublish', (sessionId: string, streamPath: string) => {
70 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
72 const splittedPath = streamPath.split('/')
73 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
74 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
75 return this.abortSession(sessionId)
78 const session = this.getContext().sessions.get(sessionId)
80 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
81 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
84 events.on('donePublish', sessionId => {
85 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
88 registerConfigChangedHandler(() => {
89 if (!this.running && CONFIG.LIVE.ENABLED === true) {
90 this.run().catch(err => logger.error('Cannot run live server.', { err }))
94 if (this.running && CONFIG.LIVE.ENABLED === false) {
99 // Cleanup broken lives, that were terminated by a server restart for example
100 this.handleBrokenLives()
101 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
107 if (CONFIG.LIVE.RTMP.ENABLED) {
108 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
110 this.rtmpServer = createServer(socket => {
111 const session = new NodeRtmpSession(config, socket)
113 session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
117 this.rtmpServer.on('error', err => {
118 logger.error('Cannot run RTMP server.', { err, ...lTags() })
121 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
124 if (CONFIG.LIVE.RTMPS.ENABLED) {
125 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
127 const [ key, cert ] = await Promise.all([
128 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
129 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
131 const serverOptions = { key, cert }
133 this.rtmpsServer = createServerTLS(serverOptions, socket => {
134 const session = new NodeRtmpSession(config, socket)
136 session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
140 this.rtmpsServer.on('error', err => {
141 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
144 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
151 if (this.rtmpServer) {
152 logger.info('Stopping RTMP server.', lTags())
154 this.rtmpServer.close()
155 this.rtmpServer = undefined
158 if (this.rtmpsServer) {
159 logger.info('Stopping RTMPS server.', lTags())
161 this.rtmpsServer.close()
162 this.rtmpsServer = undefined
165 // Sessions is an object
166 this.getContext().sessions.forEach((session: any) => {
167 if (session instanceof NodeRtmpSession) {
174 return !!this.rtmpServer
177 stopSessionOf (videoId: number, error: LiveVideoError | null) {
178 const sessionId = this.videoSessions.get(videoId)
179 if (!sessionId) return
181 this.saveEndingSession(videoId, error)
182 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
184 this.videoSessions.delete(videoId)
185 this.abortSession(sessionId)
188 private getContext () {
192 private abortSession (sessionId: string) {
193 const session = this.getContext().sessions.get(sessionId)
196 this.getContext().sessions.delete(sessionId)
199 const muxingSession = this.muxingSessions.get(sessionId)
201 // Muxing session will fire and event so we correctly cleanup the session
202 muxingSession.abort()
204 this.muxingSessions.delete(sessionId)
208 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
209 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
211 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
212 return this.abortSession(sessionId)
215 const video = videoLive.Video
216 if (video.isBlacklisted()) {
217 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
218 return this.abortSession(sessionId)
221 // Cleanup old potential live (could happen with a permanent live)
222 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
223 if (oldStreamingPlaylist) {
224 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
226 await cleanupPermanentLive(video, oldStreamingPlaylist)
229 this.videoSessions.set(video.id, sessionId)
231 const now = Date.now()
232 const probe = await ffprobePromise(inputUrl)
234 const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
235 getVideoStreamDimensionsInfo(inputUrl, probe),
236 getVideoStreamFPS(inputUrl, probe),
237 getVideoStreamBitrate(inputUrl, probe)
241 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
242 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
245 const allResolutions = this.buildAllResolutionsToTranscode(resolution)
248 'Will mux/transcode live video of original resolution %d.', resolution,
249 { allResolutions, ...lTags(sessionId, video.uuid) }
252 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
254 return this.runMuxingSession({
266 private async runMuxingSession (options: {
268 videoLive: MVideoLiveVideo
269 streamingPlaylist: MStreamingPlaylistVideo
274 allResolutions: number[]
276 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options
277 const videoUUID = videoLive.Video.uuid
278 const localLTags = lTags(sessionId, videoUUID)
280 const liveSession = await this.saveStartingSession(videoLive)
282 const user = await UserModel.loadByLiveId(videoLive.id)
283 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
285 const muxingSession = new MuxingSession({
286 context: this.getContext(),
298 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
300 muxingSession.on('bad-socket-health', ({ videoId }) => {
302 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
303 ' Stopping session of video %s.', videoUUID,
307 this.stopSessionOf(videoId, LiveVideoError.BAD_SOCKET_HEALTH)
310 muxingSession.on('duration-exceeded', ({ videoId }) => {
311 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
313 this.stopSessionOf(videoId, LiveVideoError.DURATION_EXCEEDED)
316 muxingSession.on('quota-exceeded', ({ videoId }) => {
317 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
319 this.stopSessionOf(videoId, LiveVideoError.QUOTA_EXCEEDED)
322 muxingSession.on('ffmpeg-error', ({ videoId }) => {
323 this.stopSessionOf(videoId, LiveVideoError.FFMPEG_ERROR)
326 muxingSession.on('ffmpeg-end', ({ videoId }) => {
327 this.onMuxingFFmpegEnd(videoId, sessionId)
330 muxingSession.on('after-cleanup', ({ videoId }) => {
331 this.muxingSessions.delete(sessionId)
333 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
335 muxingSession.destroy()
337 return this.onAfterMuxingCleanup({ videoId, liveSession })
338 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
341 this.muxingSessions.set(sessionId, muxingSession)
343 muxingSession.runMuxing()
345 logger.error('Cannot run muxing.', { err, ...localLTags })
346 this.abortSession(sessionId)
350 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
351 const videoId = live.videoId
354 const video = await VideoModel.loadFull(videoId)
356 logger.info('Will publish and federate live %s.', video.url, localLTags)
358 video.state = VideoState.PUBLISHED
359 video.publishedAt = new Date()
364 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
367 await federateVideoIfNeeded(video, false)
369 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
372 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
374 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
378 private onMuxingFFmpegEnd (videoId: number, sessionId: string) {
379 this.videoSessions.delete(videoId)
381 this.saveEndingSession(videoId, null)
382 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
385 private async onAfterMuxingCleanup (options: {
386 videoId: number | string
387 liveSession?: MVideoLiveSession
388 cleanupNow?: boolean // Default false
390 const { videoId, liveSession: liveSessionArg, cleanupNow = false } = options
393 const fullVideo = await VideoModel.loadFull(videoId)
394 if (!fullVideo) return
396 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
398 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
400 // On server restart during a live
401 if (!liveSession.endDate) {
402 liveSession.endDate = new Date()
403 await liveSession.save()
406 JobQueue.Instance.createJob({
407 type: 'video-live-ending',
409 videoId: fullVideo.id,
411 replayDirectory: live.saveReplay
412 ? await this.findReplayDirectory(fullVideo)
415 liveSessionId: liveSession.id,
416 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
418 publishedAt: fullVideo.publishedAt.toISOString()
420 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
422 fullVideo.state = live.permanentLive
423 ? VideoState.WAITING_FOR_LIVE
424 : VideoState.LIVE_ENDED
426 await fullVideo.save()
428 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
430 await federateVideoIfNeeded(fullVideo, false)
432 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') })
436 private async handleBrokenLives () {
437 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
439 for (const uuid of videoUUIDs) {
440 await this.onAfterMuxingCleanup({ videoId: uuid, cleanupNow: true })
444 private async findReplayDirectory (video: MVideo) {
445 const directory = getLiveReplayBaseDirectory(video)
446 const files = await readdir(directory)
448 if (files.length === 0) return undefined
450 return join(directory, files.sort().reverse()[0])
453 private buildAllResolutionsToTranscode (originResolution: number) {
454 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
455 ? computeLowerResolutionsToTranscode(originResolution, 'live')
458 return resolutionsEnabled.concat([ originResolution ])
461 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
462 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
464 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
465 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
467 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
468 playlist.type = VideoStreamingPlaylistType.HLS
470 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
472 return playlist.save()
475 private saveStartingSession (videoLive: MVideoLiveVideo) {
476 const liveSession = new VideoLiveSessionModel({
477 startDate: new Date(),
478 liveVideoId: videoLive.videoId
481 return liveSession.save()
484 private async saveEndingSession (videoId: number, error: LiveVideoError | null) {
485 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoId)
486 liveSession.endDate = new Date()
487 liveSession.error = error
489 return liveSession.save()
492 static get Instance () {
493 return this.instance || (this.instance = new this())
497 // ---------------------------------------------------------------------------