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 } from '@server/initializers/constants'
8 import { sequelizeTypescript } from '@server/initializers/database'
9 import { UserModel } from '@server/models/user/user'
10 import { VideoModel } from '@server/models/video/video'
11 import { VideoLiveModel } from '@server/models/video/video-live'
12 import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting'
13 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
14 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
15 import { MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models'
16 import { pick, wait } from '@shared/core-utils'
17 import { ffprobePromise, getVideoStreamBitrate, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
18 import { LiveVideoError, VideoState } from '@shared/models'
19 import { federateVideoIfNeeded } from '../activitypub/videos'
20 import { JobQueue } from '../job-queue'
21 import { getLiveReplayBaseDirectory } from '../paths'
22 import { PeerTubeSocket } from '../peertube-socket'
23 import { Hooks } from '../plugins/hooks'
24 import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions'
25 import { LiveQuotaStore } from './live-quota-store'
26 import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } from './live-utils'
27 import { MuxingSession } from './shared'
28 import { RunnerJobModel } from '@server/models/runner/runner-job'
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)
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, CONFIG.LIVE.RTMP.HOSTNAME)
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, CONFIG.LIVE.RTMPS.HOSTNAME)
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 (videoUUID: string, error: LiveVideoError | null) {
175 const sessionId = this.videoSessions.get(videoUUID)
177 logger.debug('No live session to stop for video %s', videoUUID, lTags(sessionId, videoUUID))
181 logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })
183 this.saveEndingSession(videoUUID, error)
184 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))
186 this.videoSessions.delete(videoUUID)
187 this.abortSession(sessionId)
190 private getContext () {
194 private abortSession (sessionId: string) {
195 const session = this.getContext().sessions.get(sessionId)
198 this.getContext().sessions.delete(sessionId)
201 const muxingSession = this.muxingSessions.get(sessionId)
203 // Muxing session will fire and event so we correctly cleanup the session
204 muxingSession.abort()
206 this.muxingSessions.delete(sessionId)
210 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
211 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
213 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
214 return this.abortSession(sessionId)
217 const video = videoLive.Video
218 if (video.isBlacklisted()) {
219 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
220 return this.abortSession(sessionId)
223 if (this.videoSessions.has(video.uuid)) {
224 logger.warn('Video %s has already a live session. Refusing stream %s.', video.uuid, streamKey, lTags(sessionId, video.uuid))
225 return this.abortSession(sessionId)
228 // Cleanup old potential live (could happen with a permanent live)
229 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
230 if (oldStreamingPlaylist) {
231 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
233 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
236 this.videoSessions.set(video.uuid, sessionId)
238 const now = Date.now()
239 const probe = await ffprobePromise(inputUrl)
241 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
242 getVideoStreamDimensionsInfo(inputUrl, probe),
243 getVideoStreamFPS(inputUrl, probe),
244 getVideoStreamBitrate(inputUrl, probe),
245 hasAudioStream(inputUrl, probe)
249 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
250 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
253 const allResolutions = await Hooks.wrapObject(
254 this.buildAllResolutionsToTranscode(resolution, hasAudio),
255 'filter:transcoding.auto.resolutions-to-transcode.result',
260 'Handling live video of original resolution %d.', resolution,
261 { allResolutions, ...lTags(sessionId, video.uuid) }
264 return this.runMuxingSession({
277 private async runMuxingSession (options: {
279 videoLive: MVideoLiveVideoWithSetting
285 allResolutions: number[]
288 const { sessionId, videoLive } = options
289 const videoUUID = videoLive.Video.uuid
290 const localLTags = lTags(sessionId, videoUUID)
292 const liveSession = await this.saveStartingSession(videoLive)
294 const user = await UserModel.loadByLiveId(videoLive.id)
295 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
297 const muxingSession = new MuxingSession({
298 context: this.getContext(),
303 ...pick(options, [ 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
306 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
308 muxingSession.on('bad-socket-health', ({ videoUUID }) => {
310 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
311 ' Stopping session of video %s.', videoUUID,
315 this.stopSessionOf(videoUUID, LiveVideoError.BAD_SOCKET_HEALTH)
318 muxingSession.on('duration-exceeded', ({ videoUUID }) => {
319 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
321 this.stopSessionOf(videoUUID, LiveVideoError.DURATION_EXCEEDED)
324 muxingSession.on('quota-exceeded', ({ videoUUID }) => {
325 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
327 this.stopSessionOf(videoUUID, LiveVideoError.QUOTA_EXCEEDED)
330 muxingSession.on('transcoding-error', ({ videoUUID }) => {
331 this.stopSessionOf(videoUUID, LiveVideoError.FFMPEG_ERROR)
334 muxingSession.on('transcoding-end', ({ videoUUID }) => {
335 this.onMuxingFFmpegEnd(videoUUID, sessionId)
338 muxingSession.on('after-cleanup', ({ videoUUID }) => {
339 this.muxingSessions.delete(sessionId)
341 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
343 muxingSession.destroy()
345 return this.onAfterMuxingCleanup({ videoUUID, liveSession })
346 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
349 this.muxingSessions.set(sessionId, muxingSession)
351 muxingSession.runMuxing()
353 logger.error('Cannot run muxing.', { err, ...localLTags })
354 this.abortSession(sessionId)
358 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
359 const videoId = live.videoId
362 const video = await VideoModel.loadFull(videoId)
364 logger.info('Will publish and federate live %s.', video.url, localLTags)
366 video.state = VideoState.PUBLISHED
367 video.publishedAt = new Date()
372 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
375 await federateVideoIfNeeded(video, false)
377 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
380 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
382 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
386 private onMuxingFFmpegEnd (videoUUID: string, sessionId: string) {
387 this.videoSessions.delete(videoUUID)
389 this.saveEndingSession(videoUUID, null)
390 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
393 private async onAfterMuxingCleanup (options: {
395 liveSession?: MVideoLiveSession
396 cleanupNow?: boolean // Default false
398 const { videoUUID, liveSession: liveSessionArg, cleanupNow = false } = options
400 logger.debug('Live of video %s has been cleaned up. Moving to its next state.', videoUUID, lTags(videoUUID))
403 const fullVideo = await VideoModel.loadFull(videoUUID)
404 if (!fullVideo) return
406 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
408 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
410 // On server restart during a live
411 if (!liveSession.endDate) {
412 liveSession.endDate = new Date()
413 await liveSession.save()
416 JobQueue.Instance.createJobAsync({
417 type: 'video-live-ending',
419 videoId: fullVideo.id,
421 replayDirectory: live.saveReplay
422 ? await this.findReplayDirectory(fullVideo)
425 liveSessionId: liveSession.id,
426 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
428 publishedAt: fullVideo.publishedAt.toISOString()
433 : VIDEO_LIVE.CLEANUP_DELAY
436 fullVideo.state = live.permanentLive
437 ? VideoState.WAITING_FOR_LIVE
438 : VideoState.LIVE_ENDED
440 await fullVideo.save()
442 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
444 await federateVideoIfNeeded(fullVideo, false)
446 logger.error('Cannot save/federate new video state of live streaming of video %s.', videoUUID, { err, ...lTags(videoUUID) })
450 private async handleBrokenLives () {
451 await RunnerJobModel.cancelAllJobs({ type: 'live-rtmp-hls-transcoding' })
453 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
455 for (const uuid of videoUUIDs) {
456 await this.onAfterMuxingCleanup({ videoUUID: uuid, cleanupNow: true })
460 private async findReplayDirectory (video: MVideo) {
461 const directory = getLiveReplayBaseDirectory(video)
462 const files = await readdir(directory)
464 if (files.length === 0) return undefined
466 return join(directory, files.sort().reverse()[0])
469 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
470 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
472 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
473 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
476 if (resolutionsEnabled.length === 0) {
477 return [ originResolution ]
480 return resolutionsEnabled
483 private async saveStartingSession (videoLive: MVideoLiveVideoWithSetting) {
484 const replaySettings = videoLive.saveReplay
485 ? new VideoLiveReplaySettingModel({
486 privacy: videoLive.ReplaySetting.privacy
490 return sequelizeTypescript.transaction(async t => {
491 if (videoLive.saveReplay) {
492 await replaySettings.save({ transaction: t })
495 return VideoLiveSessionModel.create({
496 startDate: new Date(),
497 liveVideoId: videoLive.videoId,
498 saveReplay: videoLive.saveReplay,
499 replaySettingId: videoLive.saveReplay ? replaySettings.id : null,
500 endingProcessed: false
501 }, { transaction: t })
505 private async saveEndingSession (videoUUID: string, error: LiveVideoError | null) {
506 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoUUID)
507 if (!liveSession) return
509 liveSession.endDate = new Date()
510 liveSession.error = error
512 return liveSession.save()
515 static get Instance () {
516 return this.instance || (this.instance = new this())
520 // ---------------------------------------------------------------------------