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 { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
21 import { MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models'
22 import { wait } from '@shared/core-utils'
23 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
24 import { federateVideoIfNeeded } from '../activitypub/videos'
25 import { JobQueue } from '../job-queue'
26 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveReplayBaseDirectory } from '../paths'
27 import { PeerTubeSocket } from '../peertube-socket'
28 import { LiveQuotaStore } from './live-quota-store'
29 import { LiveSegmentShaStore } from './live-segment-sha-store'
30 import { cleanupLive } 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)
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)
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) {
178 const sessionId = this.videoSessions.get(videoId)
179 if (!sessionId) return
181 this.videoSessions.delete(videoId)
182 this.abortSession(sessionId)
185 private getContext () {
189 private abortSession (sessionId: string) {
190 const session = this.getContext().sessions.get(sessionId)
193 this.getContext().sessions.delete(sessionId)
196 const muxingSession = this.muxingSessions.get(sessionId)
198 // Muxing session will fire and event so we correctly cleanup the session
199 muxingSession.abort()
201 this.muxingSessions.delete(sessionId)
205 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
206 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
208 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
209 return this.abortSession(sessionId)
212 const video = videoLive.Video
213 if (video.isBlacklisted()) {
214 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
215 return this.abortSession(sessionId)
218 // Cleanup old potential live files (could happen with a permanent live)
219 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
221 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
222 if (oldStreamingPlaylist) {
223 await cleanupLive(video, oldStreamingPlaylist)
226 this.videoSessions.set(video.id, sessionId)
228 const now = Date.now()
229 const probe = await ffprobePromise(inputUrl)
231 const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
232 getVideoStreamDimensionsInfo(inputUrl, probe),
233 getVideoStreamFPS(inputUrl, probe),
234 getVideoStreamBitrate(inputUrl, probe)
238 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
239 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
242 const allResolutions = this.buildAllResolutionsToTranscode(resolution)
245 'Will mux/transcode live video of original resolution %d.', resolution,
246 { allResolutions, ...lTags(sessionId, video.uuid) }
249 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
251 return this.runMuxingSession({
263 private async runMuxingSession (options: {
265 videoLive: MVideoLiveVideo
266 streamingPlaylist: MStreamingPlaylistVideo
271 allResolutions: number[]
273 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options
274 const videoUUID = videoLive.Video.uuid
275 const localLTags = lTags(sessionId, videoUUID)
277 const user = await UserModel.loadByLiveId(videoLive.id)
278 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
280 const muxingSession = new MuxingSession({
281 context: this.getContext(),
293 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
295 muxingSession.on('bad-socket-health', ({ videoId }) => {
297 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
298 ' Stopping session of video %s.', videoUUID,
302 this.stopSessionOf(videoId)
305 muxingSession.on('duration-exceeded', ({ videoId }) => {
306 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
308 this.stopSessionOf(videoId)
311 muxingSession.on('quota-exceeded', ({ videoId }) => {
312 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
314 this.stopSessionOf(videoId)
317 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
318 muxingSession.on('ffmpeg-end', ({ videoId }) => {
319 this.onMuxingFFmpegEnd(videoId)
322 muxingSession.on('after-cleanup', ({ videoId }) => {
323 this.muxingSessions.delete(sessionId)
325 muxingSession.destroy()
327 return this.onAfterMuxingCleanup({ videoId })
328 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
331 this.muxingSessions.set(sessionId, muxingSession)
333 muxingSession.runMuxing()
335 logger.error('Cannot run muxing.', { err, ...localLTags })
336 this.abortSession(sessionId)
340 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
341 const videoId = live.videoId
344 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
346 logger.info('Will publish and federate live %s.', video.url, localLTags)
348 video.state = VideoState.PUBLISHED
349 video.publishedAt = new Date()
354 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
357 await federateVideoIfNeeded(video, false)
359 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
362 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
364 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
368 private onMuxingFFmpegEnd (videoId: number) {
369 this.videoSessions.delete(videoId)
372 private async onAfterMuxingCleanup (options: {
373 videoId: number | string
374 cleanupNow?: boolean // Default false
376 const { videoId, cleanupNow = false } = options
379 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
380 if (!fullVideo) return
382 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
384 JobQueue.Instance.createJob({
385 type: 'video-live-ending',
387 videoId: fullVideo.id,
388 replayDirectory: live.saveReplay
389 ? await this.findReplayDirectory(fullVideo)
391 publishedAt: fullVideo.publishedAt.toISOString()
393 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
395 fullVideo.state = live.permanentLive
396 ? VideoState.WAITING_FOR_LIVE
397 : VideoState.LIVE_ENDED
399 await fullVideo.save()
401 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
403 await federateVideoIfNeeded(fullVideo, false)
405 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') })
409 private async handleBrokenLives () {
410 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
412 for (const uuid of videoUUIDs) {
413 await this.onAfterMuxingCleanup({ videoId: uuid, cleanupNow: true })
417 private async findReplayDirectory (video: MVideo) {
418 const directory = getLiveReplayBaseDirectory(video)
419 const files = await readdir(directory)
421 if (files.length === 0) return undefined
423 return join(directory, files.sort().reverse()[0])
426 private buildAllResolutionsToTranscode (originResolution: number) {
427 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
428 ? computeLowerResolutionsToTranscode(originResolution, 'live')
431 return resolutionsEnabled.concat([ originResolution ])
434 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
435 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
437 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
438 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
440 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
441 playlist.type = VideoStreamingPlaylistType.HLS
443 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
445 return playlist.save()
448 static get Instance () {
449 return this.instance || (this.instance = new this())
453 // ---------------------------------------------------------------------------