2 import { mapSeries } from 'bluebird'
3 import { FSWatcher, watch } from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
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, VIDEO_LIVE } from '@server/initializers/constants'
12 import { removeHLSFileObjectStorage, storeHLSFileFromFilename, storeHLSFileFromPath } from '@server/lib/object-storage'
13 import { VideoFileModel } from '@server/models/video/video-file'
14 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
15 import { VideoStorage } from '@shared/models'
16 import { getLiveDirectory, getLiveReplayBaseDirectory } from '../../paths'
17 import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles'
18 import { isAbleToUploadVideo } from '../../user'
19 import { LiveQuotaStore } from '../live-quota-store'
20 import { LiveSegmentShaStore } from '../live-segment-sha-store'
21 import { buildConcatenatedName } from '../live-utils'
23 import memoizee = require('memoizee')
25 interface MuxingSessionEvents {
26 'live-ready': (options: { videoId: number }) => void
28 'bad-socket-health': (options: { videoId: number }) => void
29 'duration-exceeded': (options: { videoId: number }) => void
30 'quota-exceeded': (options: { videoId: number }) => void
32 'ffmpeg-end': (options: { videoId: number }) => void
33 'ffmpeg-error': (options: { videoId: number }) => void
35 'after-cleanup': (options: { videoId: number }) => void
38 declare interface MuxingSession {
39 on<U extends keyof MuxingSessionEvents>(
40 event: U, listener: MuxingSessionEvents[U]
43 emit<U extends keyof MuxingSessionEvents>(
44 event: U, ...args: Parameters<MuxingSessionEvents[U]>
48 class MuxingSession extends EventEmitter {
50 private ffmpegCommand: FfmpegCommand
52 private readonly context: any
53 private readonly user: MUserId
54 private readonly sessionId: string
55 private readonly videoLive: MVideoLiveVideo
56 private readonly streamingPlaylist: MStreamingPlaylistVideo
57 private readonly inputUrl: string
58 private readonly fps: number
59 private readonly allResolutions: number[]
61 private readonly bitrate: number
62 private readonly ratio: number
64 private readonly hasAudio: boolean
66 private readonly videoId: number
67 private readonly videoUUID: string
68 private readonly saveReplay: boolean
70 private readonly outDirectory: string
71 private readonly replayDirectory: string
73 private readonly liveSegmentShaStore: LiveSegmentShaStore
75 private readonly lTags: LoggerTagsFn
77 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
79 private tsWatcher: FSWatcher
80 private masterWatcher: FSWatcher
81 private m3u8Watcher: FSWatcher
83 private masterPlaylistCreated = false
84 private liveReady = false
86 private aborted = false
88 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
89 return isAbleToUploadVideo(userId, 1000)
90 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
92 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
93 return this.hasClientSocketInBadHealth(sessionId)
94 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
96 constructor (options: {
100 videoLive: MVideoLiveVideo
101 streamingPlaylist: MStreamingPlaylistVideo
106 allResolutions: number[]
111 this.context = options.context
112 this.user = options.user
113 this.sessionId = options.sessionId
114 this.videoLive = options.videoLive
115 this.streamingPlaylist = options.streamingPlaylist
116 this.inputUrl = options.inputUrl
117 this.fps = options.fps
119 this.bitrate = options.bitrate
120 this.ratio = options.ratio
122 this.hasAudio = options.hasAudio
124 this.allResolutions = options.allResolutions
126 this.videoId = this.videoLive.Video.id
127 this.videoUUID = this.videoLive.Video.uuid
129 this.saveReplay = this.videoLive.saveReplay
131 this.outDirectory = getLiveDirectory(this.videoLive.Video)
132 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
134 this.liveSegmentShaStore = new LiveSegmentShaStore({
135 videoUUID: this.videoLive.Video.uuid,
136 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
137 streamingPlaylist: this.streamingPlaylist,
138 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
141 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
147 await this.prepareDirectories()
149 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
150 ? await getLiveTranscodingCommand({
151 inputUrl: this.inputUrl,
153 outPath: this.outDirectory,
154 masterPlaylistName: this.streamingPlaylist.playlistFilename,
156 latencyMode: this.videoLive.latencyMode,
158 resolutions: this.allResolutions,
160 bitrate: this.bitrate,
163 hasAudio: this.hasAudio,
165 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
166 profile: CONFIG.LIVE.TRANSCODING.PROFILE
168 : getLiveMuxingCommand({
169 inputUrl: this.inputUrl,
170 outPath: this.outDirectory,
171 masterPlaylistName: this.streamingPlaylist.playlistFilename,
172 latencyMode: this.videoLive.latencyMode
175 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
177 this.watchMasterFile()
181 let ffmpegShellCommand: string
182 this.ffmpegCommand.on('start', cmdline => {
183 ffmpegShellCommand = cmdline
185 logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() })
188 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
189 this.onFFmpegError({ err, stdout, stderr, ffmpegShellCommand })
192 this.ffmpegCommand.on('end', () => {
193 this.emit('ffmpeg-end', ({ videoId: this.videoId }))
198 this.ffmpegCommand.run()
202 if (!this.ffmpegCommand) return
205 this.ffmpegCommand.kill('SIGINT')
209 this.removeAllListeners()
210 this.isAbleToUploadVideoWithCache.clear()
211 this.hasClientSocketInBadHealthWithCache.clear()
214 private onFFmpegError (options: {
218 ffmpegShellCommand: string
220 const { err, stdout, stderr, ffmpegShellCommand } = options
224 // Don't care that we killed the ffmpeg process
225 if (err?.message?.includes('Exiting normally')) return
227 logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
229 this.emit('ffmpeg-error', ({ videoId: this.videoId }))
232 private onFFmpegEnded () {
233 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
236 // Wait latest segments generation, and close watchers
238 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close(), this.m3u8Watcher.close() ])
240 // Process remaining segments hash
241 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
242 this.processSegments(this.segmentsToProcessPerPlaylist[key])
247 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
248 { err, ...this.lTags() }
252 this.emit('after-cleanup', { videoId: this.videoId })
256 private watchMasterFile () {
257 this.masterWatcher = watch(this.outDirectory + '/' + this.streamingPlaylist.playlistFilename)
259 this.masterWatcher.on('add', async () => {
260 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
262 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
264 this.streamingPlaylist.playlistUrl = url
265 await this.streamingPlaylist.save()
267 logger.error('Cannot upload live master file to object storage.', { err, ...this.lTags() })
271 this.masterPlaylistCreated = true
273 this.masterWatcher.close()
274 .catch(err => logger.error('Cannot close master watcher of %s.', this.outDirectory, { err, ...this.lTags() }))
278 private watchM3U8File () {
279 this.m3u8Watcher = watch(this.outDirectory + '/*.m3u8')
281 const onChangeOrAdd = async (m3u8Path: string) => {
282 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
285 await storeHLSFileFromPath(this.streamingPlaylist, m3u8Path)
287 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
291 this.m3u8Watcher.on('change', onChangeOrAdd)
294 private watchTSFiles () {
295 const startStreamDateTime = new Date().getTime()
297 this.tsWatcher = watch(this.outDirectory + '/*.ts')
299 const playlistIdMatcher = /^([\d+])-/
301 const addHandler = async (segmentPath: string) => {
302 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
304 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
306 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
307 this.processSegments(segmentsToProcess)
309 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
311 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
312 this.emit('bad-socket-health', { videoId: this.videoId })
316 // Duration constraint check
317 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
318 this.emit('duration-exceeded', { videoId: this.videoId })
322 // Check user quota if the user enabled replay saving
323 if (await this.isQuotaExceeded(segmentPath) === true) {
324 this.emit('quota-exceeded', { videoId: this.videoId })
328 const deleteHandler = async (segmentPath: string) => {
330 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
332 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
335 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
337 await removeHLSFileObjectStorage(this.streamingPlaylist, segmentPath)
339 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
344 this.tsWatcher.on('add', p => addHandler(p))
345 this.tsWatcher.on('unlink', p => deleteHandler(p))
348 private async isQuotaExceeded (segmentPath: string) {
349 if (this.saveReplay !== true) return false
350 if (this.aborted) return false
353 const segmentStat = await stat(segmentPath)
355 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
357 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
359 return canUpload !== true
361 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
365 private createFiles () {
366 for (let i = 0; i < this.allResolutions.length; i++) {
367 const resolution = this.allResolutions[i]
369 const file = new VideoFileModel({
375 storage: this.streamingPlaylist.storage,
376 videoStreamingPlaylistId: this.streamingPlaylist.id
379 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
380 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
384 private async prepareDirectories () {
385 await ensureDir(this.outDirectory)
387 if (this.videoLive.saveReplay === true) {
388 await ensureDir(this.replayDirectory)
392 private isDurationConstraintValid (streamingStartTime: number) {
393 const maxDuration = CONFIG.LIVE.MAX_DURATION
395 if (maxDuration < 0) return true
397 const now = new Date().getTime()
398 const max = streamingStartTime + maxDuration
403 private processSegments (segmentPaths: string[]) {
404 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
406 if (this.aborted) return
408 logger.error('Cannot process segments', { err, ...this.lTags() })
412 private async processSegment (segmentPath: string) {
413 // Add sha hash of previous segments, because ffmpeg should have finished generating them
414 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
416 if (this.saveReplay) {
417 await this.addSegmentToReplay(segmentPath)
420 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
422 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
424 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
428 // Master playlist and segment JSON file are created, live is ready
429 if (this.masterPlaylistCreated && !this.liveReady) {
430 this.liveReady = true
432 this.emit('live-ready', { videoId: this.videoId })
436 private hasClientSocketInBadHealth (sessionId: string) {
437 const rtmpSession = this.context.sessions.get(sessionId)
440 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
444 for (const playerSessionId of rtmpSession.players) {
445 const playerSession = this.context.sessions.get(playerSessionId)
447 if (!playerSession) {
448 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
452 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
460 private async addSegmentToReplay (segmentPath: string) {
461 const segmentName = basename(segmentPath)
462 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
465 const data = await readFile(segmentPath)
467 await appendFile(dest, data)
469 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
474 // ---------------------------------------------------------------------------