1 import { mapSeries } from 'bluebird'
2 import { FSWatcher, watch } from 'chokidar'
3 import { FfmpegCommand } from 'fluent-ffmpeg'
4 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
5 import PQueue from 'p-queue'
6 import { basename, join } from 'path'
7 import { EventEmitter } from 'stream'
8 import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg'
9 import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
10 import { CONFIG } from '@server/initializers/config'
11 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
12 import { removeHLSFileObjectStorageByPath, storeHLSFileFromFilename, storeHLSFileFromPath } from '@server/lib/object-storage'
13 import { VideoFileModel } from '@server/models/video/video-file'
14 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
15 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
16 import { VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
18 generateHLSMasterPlaylistFilename,
19 generateHlsSha256SegmentsFilename,
21 getLiveReplayBaseDirectory
23 import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles'
24 import { isAbleToUploadVideo } from '../../user'
25 import { LiveQuotaStore } from '../live-quota-store'
26 import { LiveSegmentShaStore } from '../live-segment-sha-store'
27 import { buildConcatenatedName } from '../live-utils'
29 import memoizee = require('memoizee')
30 interface MuxingSessionEvents {
31 'live-ready': (options: { videoId: number }) => void
33 'bad-socket-health': (options: { videoId: number }) => void
34 'duration-exceeded': (options: { videoId: number }) => void
35 'quota-exceeded': (options: { videoId: number }) => void
37 'ffmpeg-end': (options: { videoId: number }) => void
38 'ffmpeg-error': (options: { videoId: number }) => void
40 'after-cleanup': (options: { videoId: number }) => void
43 declare interface MuxingSession {
44 on<U extends keyof MuxingSessionEvents>(
45 event: U, listener: MuxingSessionEvents[U]
48 emit<U extends keyof MuxingSessionEvents>(
49 event: U, ...args: Parameters<MuxingSessionEvents[U]>
53 class MuxingSession extends EventEmitter {
55 private ffmpegCommand: FfmpegCommand
57 private readonly context: any
58 private readonly user: MUserId
59 private readonly sessionId: string
60 private readonly videoLive: MVideoLiveVideo
61 private readonly inputUrl: string
62 private readonly fps: number
63 private readonly allResolutions: number[]
65 private readonly bitrate: number
66 private readonly ratio: number
68 private readonly hasAudio: boolean
70 private readonly videoId: number
71 private readonly videoUUID: string
72 private readonly saveReplay: boolean
74 private readonly outDirectory: string
75 private readonly replayDirectory: string
77 private readonly lTags: LoggerTagsFn
79 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
81 private streamingPlaylist: MStreamingPlaylistVideo
82 private liveSegmentShaStore: LiveSegmentShaStore
84 private tsWatcher: FSWatcher
85 private masterWatcher: FSWatcher
86 private m3u8Watcher: FSWatcher
88 private masterPlaylistCreated = false
89 private liveReady = false
91 private aborted = false
93 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
94 return isAbleToUploadVideo(userId, 1000)
95 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
97 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
98 return this.hasClientSocketInBadHealth(sessionId)
99 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
101 constructor (options: {
105 videoLive: MVideoLiveVideo
110 allResolutions: number[]
115 this.context = options.context
116 this.user = options.user
117 this.sessionId = options.sessionId
118 this.videoLive = options.videoLive
119 this.inputUrl = options.inputUrl
120 this.fps = options.fps
122 this.bitrate = options.bitrate
123 this.ratio = options.ratio
125 this.hasAudio = options.hasAudio
127 this.allResolutions = options.allResolutions
129 this.videoId = this.videoLive.Video.id
130 this.videoUUID = this.videoLive.Video.uuid
132 this.saveReplay = this.videoLive.saveReplay
134 this.outDirectory = getLiveDirectory(this.videoLive.Video)
135 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
137 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
141 this.streamingPlaylist = await this.createLivePlaylist()
143 this.createLiveShaStore()
146 await this.prepareDirectories()
148 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
149 ? await getLiveTranscodingCommand({
150 inputUrl: this.inputUrl,
152 outPath: this.outDirectory,
153 masterPlaylistName: this.streamingPlaylist.playlistFilename,
155 latencyMode: this.videoLive.latencyMode,
157 resolutions: this.allResolutions,
159 bitrate: this.bitrate,
162 hasAudio: this.hasAudio,
164 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
165 profile: CONFIG.LIVE.TRANSCODING.PROFILE
167 : getLiveMuxingCommand({
168 inputUrl: this.inputUrl,
169 outPath: this.outDirectory,
170 masterPlaylistName: this.streamingPlaylist.playlistFilename,
171 latencyMode: this.videoLive.latencyMode
174 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
176 this.watchMasterFile()
180 let ffmpegShellCommand: string
181 this.ffmpegCommand.on('start', cmdline => {
182 ffmpegShellCommand = cmdline
184 logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() })
187 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
188 this.onFFmpegError({ err, stdout, stderr, ffmpegShellCommand })
191 this.ffmpegCommand.on('end', () => {
192 this.emit('ffmpeg-end', ({ videoId: this.videoId }))
197 this.ffmpegCommand.run()
201 if (!this.ffmpegCommand) return
204 this.ffmpegCommand.kill('SIGINT')
208 this.removeAllListeners()
209 this.isAbleToUploadVideoWithCache.clear()
210 this.hasClientSocketInBadHealthWithCache.clear()
213 private onFFmpegError (options: {
217 ffmpegShellCommand: string
219 const { err, stdout, stderr, ffmpegShellCommand } = options
223 // Don't care that we killed the ffmpeg process
224 if (err?.message?.includes('Exiting normally')) return
226 logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
228 this.emit('ffmpeg-error', ({ videoId: this.videoId }))
231 private onFFmpegEnded () {
232 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
235 // Wait latest segments generation, and close watchers
237 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close(), this.m3u8Watcher.close() ])
239 // Process remaining segments hash
240 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
241 this.processSegments(this.segmentsToProcessPerPlaylist[key])
246 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
247 { err, ...this.lTags() }
251 this.emit('after-cleanup', { videoId: this.videoId })
255 private watchMasterFile () {
256 this.masterWatcher = watch(this.outDirectory + '/' + this.streamingPlaylist.playlistFilename)
258 this.masterWatcher.on('add', async () => {
260 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
261 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
263 this.streamingPlaylist.playlistUrl = url
266 this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions)
268 await this.streamingPlaylist.save()
270 logger.error('Cannot update streaming playlist.', { err, ...this.lTags() })
273 this.masterPlaylistCreated = true
275 this.masterWatcher.close()
276 .catch(err => logger.error('Cannot close master watcher of %s.', this.outDirectory, { err, ...this.lTags() }))
280 private watchM3U8File () {
281 this.m3u8Watcher = watch(this.outDirectory + '/*.m3u8')
283 const sendQueues = new Map<string, PQueue>()
285 const onChangeOrAdd = async (m3u8Path: string) => {
286 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
289 if (!sendQueues.has(m3u8Path)) {
290 sendQueues.set(m3u8Path, new PQueue({ concurrency: 1 }))
293 const queue = sendQueues.get(m3u8Path)
294 await queue.add(() => storeHLSFileFromPath(this.streamingPlaylist, m3u8Path))
296 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
300 this.m3u8Watcher.on('change', onChangeOrAdd)
303 private watchTSFiles () {
304 const startStreamDateTime = new Date().getTime()
306 this.tsWatcher = watch(this.outDirectory + '/*.ts')
308 const playlistIdMatcher = /^([\d+])-/
310 const addHandler = async (segmentPath: string) => {
311 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
313 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
315 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
316 this.processSegments(segmentsToProcess)
318 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
320 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
321 this.emit('bad-socket-health', { videoId: this.videoId })
325 // Duration constraint check
326 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
327 this.emit('duration-exceeded', { videoId: this.videoId })
331 // Check user quota if the user enabled replay saving
332 if (await this.isQuotaExceeded(segmentPath) === true) {
333 this.emit('quota-exceeded', { videoId: this.videoId })
337 const deleteHandler = async (segmentPath: string) => {
339 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
341 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
344 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
346 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
348 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
353 this.tsWatcher.on('add', p => addHandler(p))
354 this.tsWatcher.on('unlink', p => deleteHandler(p))
357 private async isQuotaExceeded (segmentPath: string) {
358 if (this.saveReplay !== true) return false
359 if (this.aborted) return false
362 const segmentStat = await stat(segmentPath)
364 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
366 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
368 return canUpload !== true
370 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
374 private createFiles () {
375 for (let i = 0; i < this.allResolutions.length; i++) {
376 const resolution = this.allResolutions[i]
378 const file = new VideoFileModel({
384 storage: this.streamingPlaylist.storage,
385 videoStreamingPlaylistId: this.streamingPlaylist.id
388 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
389 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
393 private async prepareDirectories () {
394 await ensureDir(this.outDirectory)
396 if (this.videoLive.saveReplay === true) {
397 await ensureDir(this.replayDirectory)
401 private isDurationConstraintValid (streamingStartTime: number) {
402 const maxDuration = CONFIG.LIVE.MAX_DURATION
404 if (maxDuration < 0) return true
406 const now = new Date().getTime()
407 const max = streamingStartTime + maxDuration
412 private processSegments (segmentPaths: string[]) {
413 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
415 if (this.aborted) return
417 logger.error('Cannot process segments', { err, ...this.lTags() })
421 private async processSegment (segmentPath: string) {
422 // Add sha hash of previous segments, because ffmpeg should have finished generating them
423 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
425 if (this.saveReplay) {
426 await this.addSegmentToReplay(segmentPath)
429 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
431 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
433 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
437 // Master playlist and segment JSON file are created, live is ready
438 if (this.masterPlaylistCreated && !this.liveReady) {
439 this.liveReady = true
441 this.emit('live-ready', { videoId: this.videoId })
445 private hasClientSocketInBadHealth (sessionId: string) {
446 const rtmpSession = this.context.sessions.get(sessionId)
449 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
453 for (const playerSessionId of rtmpSession.players) {
454 const playerSession = this.context.sessions.get(playerSessionId)
456 if (!playerSession) {
457 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
461 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
469 private async addSegmentToReplay (segmentPath: string) {
470 const segmentName = basename(segmentPath)
471 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
474 const data = await readFile(segmentPath)
476 await appendFile(dest, data)
478 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
482 private async createLivePlaylist (): Promise<MStreamingPlaylistVideo> {
483 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(this.videoLive.Video)
485 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
486 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
488 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
489 playlist.type = VideoStreamingPlaylistType.HLS
491 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
492 ? VideoStorage.OBJECT_STORAGE
493 : VideoStorage.FILE_SYSTEM
495 return playlist.save()
498 private createLiveShaStore () {
499 this.liveSegmentShaStore = new LiveSegmentShaStore({
500 videoUUID: this.videoLive.Video.uuid,
501 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
502 streamingPlaylist: this.streamingPlaylist,
503 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
508 // ---------------------------------------------------------------------------