2 import { readFile } from 'fs-extra'
3 import { createServer, Server } from 'net'
4 import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
6 computeLowerResolutionsToTranscode,
10 getVideoStreamDimensionsInfo,
12 } from '@server/helpers/ffmpeg'
13 import { logger, loggerTagsFactory } from '@server/helpers/logger'
14 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
15 import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
16 import { UserModel } from '@server/models/user/user'
17 import { VideoModel } from '@server/models/video/video'
18 import { VideoLiveModel } from '@server/models/video/video-live'
19 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
20 import { MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models'
21 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
22 import { federateVideoIfNeeded } from '../activitypub/videos'
23 import { JobQueue } from '../job-queue'
24 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../paths'
25 import { PeerTubeSocket } from '../peertube-socket'
26 import { LiveQuotaStore } from './live-quota-store'
27 import { LiveSegmentShaStore } from './live-segment-sha-store'
28 import { cleanupLive } from './live-utils'
29 import { MuxingSession } from './shared'
31 const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
32 const context = require('node-media-server/src/node_core_ctx')
33 const nodeMediaServerLogger = require('node-media-server/src/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
48 const lTags = loggerTagsFactory('live')
52 private static instance: LiveManager
54 private readonly muxingSessions = new Map<string, MuxingSession>()
55 private readonly videoSessions = new Map<number, string>()
57 private rtmpServer: Server
58 private rtmpsServer: ServerTLS
60 private running = false
62 private constructor () {
66 const events = this.getContext().nodeEvent
67 events.on('postPublish', (sessionId: string, streamPath: string) => {
68 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
70 const splittedPath = streamPath.split('/')
71 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
72 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
73 return this.abortSession(sessionId)
76 const session = this.getContext().sessions.get(sessionId)
78 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
79 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
82 events.on('donePublish', sessionId => {
83 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
86 registerConfigChangedHandler(() => {
87 if (!this.running && CONFIG.LIVE.ENABLED === true) {
88 this.run().catch(err => logger.error('Cannot run live server.', { err }))
92 if (this.running && CONFIG.LIVE.ENABLED === false) {
97 // Cleanup broken lives, that were terminated by a server restart for example
98 this.handleBrokenLives()
99 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
105 if (CONFIG.LIVE.RTMP.ENABLED) {
106 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
108 this.rtmpServer = createServer(socket => {
109 const session = new NodeRtmpSession(config, socket)
111 session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
115 this.rtmpServer.on('error', err => {
116 logger.error('Cannot run RTMP server.', { err, ...lTags() })
119 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
122 if (CONFIG.LIVE.RTMPS.ENABLED) {
123 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
125 const [ key, cert ] = await Promise.all([
126 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
127 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
129 const serverOptions = { key, cert }
131 this.rtmpsServer = createServerTLS(serverOptions, socket => {
132 const session = new NodeRtmpSession(config, socket)
134 session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
138 this.rtmpsServer.on('error', err => {
139 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
142 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT)
149 if (this.rtmpServer) {
150 logger.info('Stopping RTMP server.', lTags())
152 this.rtmpServer.close()
153 this.rtmpServer = undefined
156 if (this.rtmpsServer) {
157 logger.info('Stopping RTMPS server.', lTags())
159 this.rtmpsServer.close()
160 this.rtmpsServer = undefined
163 // Sessions is an object
164 this.getContext().sessions.forEach((session: any) => {
165 if (session instanceof NodeRtmpSession) {
172 return !!this.rtmpServer
175 stopSessionOf (videoId: number) {
176 const sessionId = this.videoSessions.get(videoId)
177 if (!sessionId) return
179 this.videoSessions.delete(videoId)
180 this.abortSession(sessionId)
183 private getContext () {
187 private abortSession (sessionId: string) {
188 const session = this.getContext().sessions.get(sessionId)
191 this.getContext().sessions.delete(sessionId)
194 const muxingSession = this.muxingSessions.get(sessionId)
196 // Muxing session will fire and event so we correctly cleanup the session
197 muxingSession.abort()
199 this.muxingSessions.delete(sessionId)
203 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
204 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
206 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
207 return this.abortSession(sessionId)
210 const video = videoLive.Video
211 if (video.isBlacklisted()) {
212 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
213 return this.abortSession(sessionId)
216 // Cleanup old potential live files (could happen with a permanent live)
217 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
219 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
220 if (oldStreamingPlaylist) {
221 await cleanupLive(video, oldStreamingPlaylist)
224 this.videoSessions.set(video.id, sessionId)
226 const now = Date.now()
227 const probe = await ffprobePromise(inputUrl)
229 const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
230 getVideoStreamDimensionsInfo(inputUrl, probe),
231 getVideoStreamFPS(inputUrl, probe),
232 getVideoStreamBitrate(inputUrl, probe)
236 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
237 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
240 const allResolutions = this.buildAllResolutionsToTranscode(resolution)
243 'Will mux/transcode live video of original resolution %d.', resolution,
244 { allResolutions, ...lTags(sessionId, video.uuid) }
247 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
249 return this.runMuxingSession({
261 private async runMuxingSession (options: {
263 videoLive: MVideoLiveVideo
264 streamingPlaylist: MStreamingPlaylistVideo
269 allResolutions: number[]
271 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options
272 const videoUUID = videoLive.Video.uuid
273 const localLTags = lTags(sessionId, videoUUID)
275 const user = await UserModel.loadByLiveId(videoLive.id)
276 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
278 const muxingSession = new MuxingSession({
279 context: this.getContext(),
291 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
293 muxingSession.on('bad-socket-health', ({ videoId }) => {
295 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
296 ' Stopping session of video %s.', videoUUID,
300 this.stopSessionOf(videoId)
303 muxingSession.on('duration-exceeded', ({ videoId }) => {
304 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
306 this.stopSessionOf(videoId)
309 muxingSession.on('quota-exceeded', ({ videoId }) => {
310 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
312 this.stopSessionOf(videoId)
315 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
316 muxingSession.on('ffmpeg-end', ({ videoId }) => {
317 this.onMuxingFFmpegEnd(videoId)
320 muxingSession.on('after-cleanup', ({ videoId }) => {
321 this.muxingSessions.delete(sessionId)
323 muxingSession.destroy()
325 return this.onAfterMuxingCleanup(videoId)
326 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
329 this.muxingSessions.set(sessionId, muxingSession)
331 muxingSession.runMuxing()
333 logger.error('Cannot run muxing.', { err, ...localLTags })
334 this.abortSession(sessionId)
338 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
339 const videoId = live.videoId
342 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
344 logger.info('Will publish and federate live %s.', video.url, localLTags)
346 video.state = VideoState.PUBLISHED
347 video.publishedAt = new Date()
353 federateVideoIfNeeded(video, false)
354 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }))
356 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
357 }, getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
359 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
363 private onMuxingFFmpegEnd (videoId: number) {
364 this.videoSessions.delete(videoId)
367 private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) {
369 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
370 if (!fullVideo) return
372 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
374 if (!live.permanentLive) {
375 JobQueue.Instance.createJob({
376 type: 'video-live-ending',
378 videoId: fullVideo.id
380 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
382 fullVideo.state = VideoState.LIVE_ENDED
384 fullVideo.state = VideoState.WAITING_FOR_LIVE
387 await fullVideo.save()
389 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
391 await federateVideoIfNeeded(fullVideo, false)
393 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
397 private async handleBrokenLives () {
398 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
400 for (const uuid of videoUUIDs) {
401 await this.onAfterMuxingCleanup(uuid, true)
405 private buildAllResolutionsToTranscode (originResolution: number) {
406 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
407 ? computeLowerResolutionsToTranscode(originResolution, 'live')
410 return resolutionsEnabled.concat([ originResolution ])
413 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
414 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
416 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
417 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
419 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
420 playlist.type = VideoStreamingPlaylistType.HLS
422 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
424 return playlist.save()
427 static get Instance () {
428 return this.instance || (this.instance = new this())
432 // ---------------------------------------------------------------------------