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'
5 import { logger, loggerTagsFactory } from '@server/helpers/logger'
6 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
7 import { VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
8 import { sequelizeTypescript } from '@server/initializers/database'
9 import { RunnerJobModel } from '@server/models/runner/runner-job'
10 import { UserModel } from '@server/models/user/user'
11 import { VideoModel } from '@server/models/video/video'
12 import { VideoLiveModel } from '@server/models/video/video-live'
13 import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting'
14 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
15 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
16 import { MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models'
17 import { pick, wait } from '@shared/core-utils'
18 import { ffprobePromise, getVideoStreamBitrate, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
19 import { LiveVideoError, VideoState } from '@shared/models'
20 import { federateVideoIfNeeded } from '../activitypub/videos'
21 import { JobQueue } from '../job-queue'
22 import { getLiveReplayBaseDirectory } from '../paths'
23 import { PeerTubeSocket } from '../peertube-socket'
24 import { Hooks } from '../plugins/hooks'
25 import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions'
26 import { LiveQuotaStore } from './live-quota-store'
27 import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } 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<string, 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)
76 const inputLocalUrl = session.inputOriginLocalUrl + streamPath
77 const inputPublicUrl = session.inputOriginPublicUrl + streamPath
79 this.handleSession({ sessionId, inputPublicUrl, inputLocalUrl, streamKey: splittedPath[2] })
80 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
83 events.on('donePublish', sessionId => {
84 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
86 // Force session aborting, so we kill ffmpeg even if it still has data to process (slow CPU)
87 setTimeout(() => this.abortSession(sessionId), 2000)
90 registerConfigChangedHandler(() => {
91 if (!this.running && CONFIG.LIVE.ENABLED === true) {
92 this.run().catch(err => logger.error('Cannot run live server.', { err }))
96 if (this.running && CONFIG.LIVE.ENABLED === false) {
101 // Cleanup broken lives, that were terminated by a server restart for example
102 this.handleBrokenLives()
103 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
109 if (CONFIG.LIVE.RTMP.ENABLED) {
110 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
112 this.rtmpServer = createServer(socket => {
113 const session = new NodeRtmpSession(config, socket)
115 session.inputOriginLocalUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
116 session.inputOriginPublicUrl = WEBSERVER.RTMP_URL
120 this.rtmpServer.on('error', err => {
121 logger.error('Cannot run RTMP server.', { err, ...lTags() })
124 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
127 if (CONFIG.LIVE.RTMPS.ENABLED) {
128 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
130 const [ key, cert ] = await Promise.all([
131 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
132 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
134 const serverOptions = { key, cert }
136 this.rtmpsServer = createServerTLS(serverOptions, socket => {
137 const session = new NodeRtmpSession(config, socket)
139 session.inputOriginLocalUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
140 session.inputOriginPublicUrl = WEBSERVER.RTMPS_URL
144 this.rtmpsServer.on('error', err => {
145 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
148 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
155 if (this.rtmpServer) {
156 logger.info('Stopping RTMP server.', lTags())
158 this.rtmpServer.close()
159 this.rtmpServer = undefined
162 if (this.rtmpsServer) {
163 logger.info('Stopping RTMPS server.', lTags())
165 this.rtmpsServer.close()
166 this.rtmpsServer = undefined
169 // Sessions is an object
170 this.getContext().sessions.forEach((session: any) => {
171 if (session instanceof NodeRtmpSession) {
178 return !!this.rtmpServer
181 hasSession (sessionId: string) {
182 return this.getContext().sessions.has(sessionId)
185 stopSessionOf (videoUUID: string, error: LiveVideoError | null) {
186 const sessionId = this.videoSessions.get(videoUUID)
188 logger.debug('No live session to stop for video %s', videoUUID, lTags(sessionId, videoUUID))
192 logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })
194 this.saveEndingSession(videoUUID, error)
195 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))
197 this.videoSessions.delete(videoUUID)
198 this.abortSession(sessionId)
201 private getContext () {
205 private abortSession (sessionId: string) {
206 const session = this.getContext().sessions.get(sessionId)
209 this.getContext().sessions.delete(sessionId)
212 const muxingSession = this.muxingSessions.get(sessionId)
214 // Muxing session will fire and event so we correctly cleanup the session
215 muxingSession.abort()
217 this.muxingSessions.delete(sessionId)
221 private async handleSession (options: {
223 inputLocalUrl: string
224 inputPublicUrl: string
227 const { inputLocalUrl, inputPublicUrl, sessionId, streamKey } = options
229 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
231 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
232 return this.abortSession(sessionId)
235 const video = videoLive.Video
236 if (video.isBlacklisted()) {
237 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
238 return this.abortSession(sessionId)
241 if (this.videoSessions.has(video.uuid)) {
242 logger.warn('Video %s has already a live session. Refusing stream %s.', video.uuid, streamKey, lTags(sessionId, video.uuid))
243 return this.abortSession(sessionId)
246 // Cleanup old potential live (could happen with a permanent live)
247 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
248 if (oldStreamingPlaylist) {
249 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
251 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
254 this.videoSessions.set(video.uuid, sessionId)
256 const now = Date.now()
257 const probe = await ffprobePromise(inputLocalUrl)
259 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
260 getVideoStreamDimensionsInfo(inputLocalUrl, probe),
261 getVideoStreamFPS(inputLocalUrl, probe),
262 getVideoStreamBitrate(inputLocalUrl, probe),
263 hasAudioStream(inputLocalUrl, probe)
267 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
268 inputLocalUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
271 const allResolutions = await Hooks.wrapObject(
272 this.buildAllResolutionsToTranscode(resolution, hasAudio),
273 'filter:transcoding.auto.resolutions-to-transcode.result',
278 'Handling live video of original resolution %d.', resolution,
279 { allResolutions, ...lTags(sessionId, video.uuid) }
282 return this.runMuxingSession({
296 private async runMuxingSession (options: {
298 videoLive: MVideoLiveVideoWithSetting
300 inputLocalUrl: string
301 inputPublicUrl: string
306 allResolutions: number[]
309 const { sessionId, videoLive } = options
310 const videoUUID = videoLive.Video.uuid
311 const localLTags = lTags(sessionId, videoUUID)
313 const liveSession = await this.saveStartingSession(videoLive)
315 const user = await UserModel.loadByLiveId(videoLive.id)
316 LiveQuotaStore.Instance.addNewLive(user.id, sessionId)
318 const muxingSession = new MuxingSession({
319 context: this.getContext(),
324 ...pick(options, [ 'inputLocalUrl', 'inputPublicUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
327 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
329 muxingSession.on('bad-socket-health', ({ videoUUID }) => {
331 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
332 ' Stopping session of video %s.', videoUUID,
336 this.stopSessionOf(videoUUID, LiveVideoError.BAD_SOCKET_HEALTH)
339 muxingSession.on('duration-exceeded', ({ videoUUID }) => {
340 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
342 this.stopSessionOf(videoUUID, LiveVideoError.DURATION_EXCEEDED)
345 muxingSession.on('quota-exceeded', ({ videoUUID }) => {
346 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
348 this.stopSessionOf(videoUUID, LiveVideoError.QUOTA_EXCEEDED)
351 muxingSession.on('transcoding-error', ({ videoUUID }) => {
352 this.stopSessionOf(videoUUID, LiveVideoError.FFMPEG_ERROR)
355 muxingSession.on('transcoding-end', ({ videoUUID }) => {
356 this.onMuxingFFmpegEnd(videoUUID, sessionId)
359 muxingSession.on('after-cleanup', ({ videoUUID }) => {
360 this.muxingSessions.delete(sessionId)
362 LiveQuotaStore.Instance.removeLive(user.id, sessionId)
364 muxingSession.destroy()
366 return this.onAfterMuxingCleanup({ videoUUID, liveSession })
367 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
370 this.muxingSessions.set(sessionId, muxingSession)
372 muxingSession.runMuxing()
374 logger.error('Cannot run muxing.', { err, ...localLTags })
375 this.abortSession(sessionId)
379 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
380 const videoId = live.videoId
383 const video = await VideoModel.loadFull(videoId)
385 logger.info('Will publish and federate live %s.', video.url, localLTags)
387 video.state = VideoState.PUBLISHED
388 video.publishedAt = new Date()
393 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
396 await federateVideoIfNeeded(video, false)
398 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
401 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
403 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
407 private onMuxingFFmpegEnd (videoUUID: string, sessionId: string) {
408 // Session already cleaned up
409 if (!this.videoSessions.has(videoUUID)) return
411 this.videoSessions.delete(videoUUID)
413 this.saveEndingSession(videoUUID, null)
414 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
417 private async onAfterMuxingCleanup (options: {
419 liveSession?: MVideoLiveSession
420 cleanupNow?: boolean // Default false
422 const { videoUUID, liveSession: liveSessionArg, cleanupNow = false } = options
424 logger.debug('Live of video %s has been cleaned up. Moving to its next state.', videoUUID, lTags(videoUUID))
427 const fullVideo = await VideoModel.loadFull(videoUUID)
428 if (!fullVideo) return
430 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
432 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
434 // On server restart during a live
435 if (!liveSession.endDate) {
436 liveSession.endDate = new Date()
437 await liveSession.save()
440 JobQueue.Instance.createJobAsync({
441 type: 'video-live-ending',
443 videoId: fullVideo.id,
445 replayDirectory: live.saveReplay
446 ? await this.findReplayDirectory(fullVideo)
449 liveSessionId: liveSession.id,
450 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
452 publishedAt: fullVideo.publishedAt.toISOString()
457 : VIDEO_LIVE.CLEANUP_DELAY
460 fullVideo.state = live.permanentLive
461 ? VideoState.WAITING_FOR_LIVE
462 : VideoState.LIVE_ENDED
464 await fullVideo.save()
466 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
468 await federateVideoIfNeeded(fullVideo, false)
470 logger.error('Cannot save/federate new video state of live streaming of video %s.', videoUUID, { err, ...lTags(videoUUID) })
474 private async handleBrokenLives () {
475 await RunnerJobModel.cancelAllJobs({ type: 'live-rtmp-hls-transcoding' })
477 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
479 for (const uuid of videoUUIDs) {
480 await this.onAfterMuxingCleanup({ videoUUID: uuid, cleanupNow: true })
484 private async findReplayDirectory (video: MVideo) {
485 const directory = getLiveReplayBaseDirectory(video)
486 const files = await readdir(directory)
488 if (files.length === 0) return undefined
490 return join(directory, files.sort().reverse()[0])
493 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
494 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
496 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
497 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
500 if (resolutionsEnabled.length === 0) {
501 return [ originResolution ]
504 return resolutionsEnabled
507 private async saveStartingSession (videoLive: MVideoLiveVideoWithSetting) {
508 const replaySettings = videoLive.saveReplay
509 ? new VideoLiveReplaySettingModel({
510 privacy: videoLive.ReplaySetting.privacy
514 return sequelizeTypescript.transaction(async t => {
515 if (videoLive.saveReplay) {
516 await replaySettings.save({ transaction: t })
519 return VideoLiveSessionModel.create({
520 startDate: new Date(),
521 liveVideoId: videoLive.videoId,
522 saveReplay: videoLive.saveReplay,
523 replaySettingId: videoLive.saveReplay ? replaySettings.id : null,
524 endingProcessed: false
525 }, { transaction: t })
529 private async saveEndingSession (videoUUID: string, error: LiveVideoError | null) {
530 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoUUID)
531 if (!liveSession) return
533 liveSession.endDate = new Date()
534 liveSession.error = error
536 return liveSession.save()
539 static get Instance () {
540 return this.instance || (this.instance = new this())
544 // ---------------------------------------------------------------------------