2 import { AsyncQueue, queue } from 'async'
3 import * as chokidar from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { ensureDir, readdir, remove } from 'fs-extra'
6 import { basename, join } from 'path'
7 import { computeResolutionsToTranscode, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
8 import { logger } from '@server/helpers/logger'
9 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
10 import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
11 import { VideoFileModel } from '@server/models/video/video-file'
12 import { VideoLiveModel } from '@server/models/video/video-live'
13 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
14 import { MStreamingPlaylist, MVideo, MVideoLiveVideo } from '@server/types/models'
15 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
16 import { buildSha256Segment } from './hls'
17 import { getHLSDirectory } from './video-paths'
19 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
20 const context = require('node-media-server/node_core_ctx')
21 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
23 // Disable node media server logs
24 nodeMediaServerLogger.setLogType(0)
28 port: CONFIG.LIVE.RTMP.PORT,
29 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
30 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
31 ping: VIDEO_LIVE.RTMP.PING,
32 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
39 type SegmentSha256QueueParam = {
40 operation: 'update' | 'delete'
47 private static instance: LiveManager
49 private readonly transSessions = new Map<string, FfmpegCommand>()
50 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
52 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
53 private rtmpServer: any
55 private constructor () {
59 this.getContext().nodeEvent.on('postPublish', (sessionId: string, streamPath: string) => {
60 logger.debug('RTMP received stream', { id: sessionId, streamPath })
62 const splittedPath = streamPath.split('/')
63 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
64 logger.warn('Live path is incorrect.', { streamPath })
65 return this.abortSession(sessionId)
68 this.handleSession(sessionId, streamPath, splittedPath[2])
69 .catch(err => logger.error('Cannot handle sessions.', { err }))
72 this.getContext().nodeEvent.on('donePublish', sessionId => {
73 this.abortSession(sessionId)
76 this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => {
77 const promise = options.operation === 'update'
78 ? this.addSegmentSha(options)
79 : Promise.resolve(this.removeSegmentSha(options))
81 promise.then(() => cb())
83 logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err })
88 registerConfigChangedHandler(() => {
89 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
94 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
101 logger.info('Running RTMP server.')
103 this.rtmpServer = new NodeRtmpServer(config)
104 this.rtmpServer.run()
108 logger.info('Stopping RTMP server.')
110 this.rtmpServer.stop()
111 this.rtmpServer = undefined
114 getSegmentsSha256 (videoUUID: string) {
115 return this.segmentsSha256.get(videoUUID)
118 private getContext () {
122 private abortSession (id: string) {
123 const session = this.getContext().sessions.get(id)
124 if (session) session.stop()
126 const transSession = this.transSessions.get(id)
127 if (transSession) transSession.kill('SIGKILL')
130 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
131 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
133 logger.warn('Unknown live video with stream key %s.', streamKey)
134 return this.abortSession(sessionId)
137 const video = videoLive.Video
138 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
140 const session = this.getContext().sessions.get(sessionId)
141 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
142 ? computeResolutionsToTranscode(session.videoHeight, 'live')
145 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
147 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
150 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
151 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
152 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
154 type: VideoStreamingPlaylistType.HLS
155 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
157 video.state = VideoState.PUBLISHED
160 // FIXME: federation?
162 return this.runMuxing({
165 playlist: videoStreamingPlaylist,
167 originalResolution: session.videoHeight,
172 private async runMuxing (options: {
174 videoLive: MVideoLiveVideo
175 playlist: MStreamingPlaylist
177 resolutionsEnabled: number[]
178 originalResolution: number
180 const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options
181 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
183 for (let i = 0; i < allResolutions.length; i++) {
184 const resolution = allResolutions[i]
186 VideoFileModel.upsert({
192 videoStreamingPlaylistId: playlist.id
194 logger.error('Cannot create file for live streaming.', { err })
198 const outPath = getHLSDirectory(videoLive.Video)
199 await ensureDir(outPath)
201 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
202 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
203 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions)
204 : runLiveMuxing(rtmpUrl, outPath)
206 logger.info('Running live muxing/transcoding.')
208 this.transSessions.set(sessionId, ffmpegExec)
210 const onFFmpegEnded = () => {
212 .catch(err => logger.error('Cannot close watcher of %s.', outPath, { err }))
214 this.onEndTransmuxing(videoLive.Video, playlist, streamPath, outPath)
215 .catch(err => logger.error('Error in closed transmuxing.', { err }))
218 ffmpegExec.on('error', (err, stdout, stderr) => {
221 // Don't care that we killed the ffmpeg process
222 if (err?.message?.includes('SIGKILL')) return
224 logger.error('Live transcoding error.', { err, stdout, stderr })
227 ffmpegExec.on('end', () => onFFmpegEnded())
229 const videoUUID = videoLive.Video.uuid
230 const watcher = chokidar.watch(outPath + '/*.ts')
232 const updateHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
233 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
235 watcher.on('add', p => updateHandler(p))
236 watcher.on('change', p => updateHandler(p))
237 watcher.on('unlink', p => deleteHandler(p))
240 private async onEndTransmuxing (video: MVideo, playlist: MStreamingPlaylist, streamPath: string, outPath: string) {
241 logger.info('RTMP transmuxing for %s ended.', streamPath)
243 const files = await readdir(outPath)
245 for (const filename of files) {
247 filename.endsWith('.ts') ||
248 filename.endsWith('.m3u8') ||
249 filename.endsWith('.mpd') ||
250 filename.endsWith('.m4s') ||
251 filename.endsWith('.tmp')
253 const p = join(outPath, filename)
256 .catch(err => logger.error('Cannot remove %s.', p, { err }))
261 .catch(err => logger.error('Cannot remove live streaming playlist.', { err }))
263 video.state = VideoState.LIVE_ENDED
265 .catch(err => logger.error('Cannot save new video state of live streaming.', { err }))
268 private async addSegmentSha (options: SegmentSha256QueueParam) {
269 const segmentName = basename(options.segmentPath)
270 logger.debug('Updating live sha segment %s.', options.segmentPath)
272 const shaResult = await buildSha256Segment(options.segmentPath)
274 if (!this.segmentsSha256.has(options.videoUUID)) {
275 this.segmentsSha256.set(options.videoUUID, new Map())
278 const filesMap = this.segmentsSha256.get(options.videoUUID)
279 filesMap.set(segmentName, shaResult)
282 private removeSegmentSha (options: SegmentSha256QueueParam) {
283 const segmentName = basename(options.segmentPath)
285 logger.debug('Removing live sha segment %s.', options.segmentPath)
287 const filesMap = this.segmentsSha256.get(options.videoUUID)
289 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
293 if (!filesMap.has(segmentName)) {
294 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
298 filesMap.delete(segmentName)
301 static get Instance () {
302 return this.instance || (this.instance = new this())
306 // ---------------------------------------------------------------------------