2 import { readFile } from 'fs-extra'
3 import { createServer, Server } from 'net'
4 import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
6 computeResolutionsToTranscode,
10 getVideoFileResolution
11 } from '@server/helpers/ffprobe-utils'
12 import { logger, loggerTagsFactory } from '@server/helpers/logger'
13 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
14 import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
15 import { UserModel } from '@server/models/user/user'
16 import { VideoModel } from '@server/models/video/video'
17 import { VideoLiveModel } from '@server/models/video/video-live'
18 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
19 import { MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models'
20 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
21 import { federateVideoIfNeeded } from '../activitypub/videos'
22 import { JobQueue } from '../job-queue'
23 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../paths'
24 import { PeerTubeSocket } from '../peertube-socket'
25 import { LiveQuotaStore } from './live-quota-store'
26 import { LiveSegmentShaStore } from './live-segment-sha-store'
27 import { cleanupLive } from './live-utils'
28 import { MuxingSession } from './shared'
30 const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
31 const context = require('node-media-server/src/node_core_ctx')
32 const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
34 // Disable node media server logs
35 nodeMediaServerLogger.setLogType(0)
39 port: CONFIG.LIVE.RTMP.PORT,
40 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
41 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
42 ping: VIDEO_LIVE.RTMP.PING,
43 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
47 const lTags = loggerTagsFactory('live')
51 private static instance: LiveManager
53 private readonly muxingSessions = new Map<string, MuxingSession>()
54 private readonly videoSessions = new Map<number, string>()
56 private rtmpServer: Server
57 private rtmpsServer: ServerTLS
59 private running = false
61 private constructor () {
65 const events = this.getContext().nodeEvent
66 events.on('postPublish', (sessionId: string, streamPath: string) => {
67 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
69 const splittedPath = streamPath.split('/')
70 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
71 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
72 return this.abortSession(sessionId)
75 const session = this.getContext().sessions.get(sessionId)
77 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
78 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
81 events.on('donePublish', sessionId => {
82 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
85 registerConfigChangedHandler(() => {
86 if (!this.running && CONFIG.LIVE.ENABLED === true) {
87 this.run().catch(err => logger.error('Cannot run live server.', { err }))
91 if (this.running && CONFIG.LIVE.ENABLED === false) {
96 // Cleanup broken lives, that were terminated by a server restart for example
97 this.handleBrokenLives()
98 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
104 if (CONFIG.LIVE.RTMP.ENABLED) {
105 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
107 this.rtmpServer = createServer(socket => {
108 const session = new NodeRtmpSession(config, socket)
110 session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
114 this.rtmpServer.on('error', err => {
115 logger.error('Cannot run RTMP server.', { err, ...lTags() })
118 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
121 if (CONFIG.LIVE.RTMPS.ENABLED) {
122 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
124 const [ key, cert ] = await Promise.all([
125 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
126 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
128 const serverOptions = { key, cert }
130 this.rtmpsServer = createServerTLS(serverOptions, socket => {
131 const session = new NodeRtmpSession(config, socket)
133 session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
137 this.rtmpsServer.on('error', err => {
138 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
141 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT)
148 if (this.rtmpServer) {
149 logger.info('Stopping RTMP server.', lTags())
151 this.rtmpServer.close()
152 this.rtmpServer = undefined
155 if (this.rtmpsServer) {
156 logger.info('Stopping RTMPS server.', lTags())
158 this.rtmpsServer.close()
159 this.rtmpsServer = undefined
162 // Sessions is an object
163 this.getContext().sessions.forEach((session: any) => {
164 if (session instanceof NodeRtmpSession) {
171 return !!this.rtmpServer
174 stopSessionOf (videoId: number) {
175 const sessionId = this.videoSessions.get(videoId)
176 if (!sessionId) return
178 this.videoSessions.delete(videoId)
179 this.abortSession(sessionId)
182 private getContext () {
186 private abortSession (sessionId: string) {
187 const session = this.getContext().sessions.get(sessionId)
190 this.getContext().sessions.delete(sessionId)
193 const muxingSession = this.muxingSessions.get(sessionId)
195 // Muxing session will fire and event so we correctly cleanup the session
196 muxingSession.abort()
198 this.muxingSessions.delete(sessionId)
202 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
203 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
205 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
206 return this.abortSession(sessionId)
209 const video = videoLive.Video
210 if (video.isBlacklisted()) {
211 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
212 return this.abortSession(sessionId)
215 // Cleanup old potential live files (could happen with a permanent live)
216 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
218 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
219 if (oldStreamingPlaylist) {
220 await cleanupLive(video, oldStreamingPlaylist)
223 this.videoSessions.set(video.id, sessionId)
225 const now = Date.now()
226 const probe = await ffprobePromise(inputUrl)
228 const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
229 getVideoFileResolution(inputUrl, probe),
230 getVideoFileFPS(inputUrl, probe),
231 getVideoFileBitrate(inputUrl, probe)
235 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
236 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
239 const allResolutions = this.buildAllResolutionsToTranscode(resolution)
242 'Will mux/transcode live video of original resolution %d.', resolution,
243 { allResolutions, ...lTags(sessionId, video.uuid) }
246 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
248 return this.runMuxingSession({
260 private async runMuxingSession (options: {
262 videoLive: MVideoLiveVideo
263 streamingPlaylist: MStreamingPlaylistVideo
268 allResolutions: number[]
270 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options
271 const videoUUID = videoLive.Video.uuid
272 const localLTags = lTags(sessionId, videoUUID)
274 const user = await UserModel.loadByLiveId(videoLive.id)
275 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
277 const muxingSession = new MuxingSession({
278 context: this.getContext(),
290 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
292 muxingSession.on('bad-socket-health', ({ videoId }) => {
294 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
295 ' Stopping session of video %s.', videoUUID,
299 this.stopSessionOf(videoId)
302 muxingSession.on('duration-exceeded', ({ videoId }) => {
303 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
305 this.stopSessionOf(videoId)
308 muxingSession.on('quota-exceeded', ({ videoId }) => {
309 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
311 this.stopSessionOf(videoId)
314 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
315 muxingSession.on('ffmpeg-end', ({ videoId }) => {
316 this.onMuxingFFmpegEnd(videoId)
319 muxingSession.on('after-cleanup', ({ videoId }) => {
320 this.muxingSessions.delete(sessionId)
322 muxingSession.destroy()
324 return this.onAfterMuxingCleanup(videoId)
325 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
328 this.muxingSessions.set(sessionId, muxingSession)
330 muxingSession.runMuxing()
332 logger.error('Cannot run muxing.', { err, ...localLTags })
333 this.abortSession(sessionId)
337 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
338 const videoId = live.videoId
341 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
343 logger.info('Will publish and federate live %s.', video.url, localLTags)
345 video.state = VideoState.PUBLISHED
351 federateVideoIfNeeded(video, false)
352 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }))
354 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
355 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
357 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
361 private onMuxingFFmpegEnd (videoId: number) {
362 this.videoSessions.delete(videoId)
365 private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) {
367 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
368 if (!fullVideo) return
370 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
372 if (!live.permanentLive) {
373 JobQueue.Instance.createJob({
374 type: 'video-live-ending',
376 videoId: fullVideo.id
378 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
380 fullVideo.state = VideoState.LIVE_ENDED
382 fullVideo.state = VideoState.WAITING_FOR_LIVE
385 await fullVideo.save()
387 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
389 await federateVideoIfNeeded(fullVideo, false)
391 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
395 private async handleBrokenLives () {
396 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
398 for (const uuid of videoUUIDs) {
399 await this.onAfterMuxingCleanup(uuid, true)
403 private buildAllResolutionsToTranscode (originResolution: number) {
404 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
405 ? computeResolutionsToTranscode(originResolution, 'live')
408 return resolutionsEnabled.concat([ originResolution ])
411 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
412 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
414 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
415 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
417 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
418 playlist.type = VideoStreamingPlaylistType.HLS
420 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
422 return playlist.save()
425 static get Instance () {
426 return this.instance || (this.instance = new this())
430 // ---------------------------------------------------------------------------