1 import { mapSeries } from 'bluebird'
2 import { FSWatcher, watch } from 'chokidar'
3 import { EventEmitter } from 'events'
4 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
5 import PQueue from 'p-queue'
6 import { basename, join } from 'path'
7 import { computeOutputFPS } from '@server/helpers/ffmpeg'
8 import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
9 import { CONFIG } from '@server/initializers/config'
10 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
11 import { removeHLSFileObjectStorageByPath, storeHLSFileFromContent, storeHLSFileFromPath } from '@server/lib/object-storage'
12 import { VideoFileModel } from '@server/models/video/video-file'
13 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
14 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
15 import { VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
17 generateHLSMasterPlaylistFilename,
18 generateHlsSha256SegmentsFilename,
20 getLiveReplayBaseDirectory
22 import { isAbleToUploadVideo } from '../../user'
23 import { LiveQuotaStore } from '../live-quota-store'
24 import { LiveSegmentShaStore } from '../live-segment-sha-store'
25 import { buildConcatenatedName, getLiveSegmentTime } from '../live-utils'
26 import { AbstractTranscodingWrapper, FFmpegTranscodingWrapper, RemoteTranscodingWrapper } from './transcoding-wrapper'
28 import memoizee = require('memoizee')
29 interface MuxingSessionEvents {
30 'live-ready': (options: { videoUUID: string }) => void
32 'bad-socket-health': (options: { videoUUID: string }) => void
33 'duration-exceeded': (options: { videoUUID: string }) => void
34 'quota-exceeded': (options: { videoUUID: string }) => void
36 'transcoding-end': (options: { videoUUID: string }) => void
37 'transcoding-error': (options: { videoUUID: string }) => void
39 'after-cleanup': (options: { videoUUID: string }) => void
42 declare interface MuxingSession {
43 on<U extends keyof MuxingSessionEvents>(
44 event: U, listener: MuxingSessionEvents[U]
47 emit<U extends keyof MuxingSessionEvents>(
48 event: U, ...args: Parameters<MuxingSessionEvents[U]>
52 class MuxingSession extends EventEmitter {
54 private transcodingWrapper: AbstractTranscodingWrapper
56 private readonly context: any
57 private readonly user: MUserId
58 private readonly sessionId: string
59 private readonly videoLive: MVideoLiveVideo
61 private readonly inputLocalUrl: string
62 private readonly inputPublicUrl: string
64 private readonly fps: number
65 private readonly allResolutions: number[]
67 private readonly bitrate: number
68 private readonly ratio: number
70 private readonly hasAudio: boolean
72 private readonly videoUUID: string
73 private readonly saveReplay: boolean
75 private readonly outDirectory: string
76 private readonly replayDirectory: string
78 private readonly lTags: LoggerTagsFn
81 private readonly objectStorageSendQueues = new Map<string, PQueue>()
83 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
85 private streamingPlaylist: MStreamingPlaylistVideo
86 private liveSegmentShaStore: LiveSegmentShaStore
88 private filesWatcher: FSWatcher
90 private masterPlaylistCreated = false
91 private liveReady = false
93 private aborted = false
95 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
96 return isAbleToUploadVideo(userId, 1000)
97 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
99 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
100 return this.hasClientSocketInBadHealth(sessionId)
101 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
103 constructor (options: {
107 videoLive: MVideoLiveVideo
109 inputLocalUrl: string
110 inputPublicUrl: string
115 allResolutions: number[]
120 this.context = options.context
121 this.user = options.user
122 this.sessionId = options.sessionId
123 this.videoLive = options.videoLive
125 this.inputLocalUrl = options.inputLocalUrl
126 this.inputPublicUrl = options.inputPublicUrl
128 this.fps = options.fps
130 this.bitrate = options.bitrate
131 this.ratio = options.ratio
133 this.hasAudio = options.hasAudio
135 this.allResolutions = options.allResolutions
137 this.videoUUID = this.videoLive.Video.uuid
139 this.saveReplay = this.videoLive.saveReplay
141 this.outDirectory = getLiveDirectory(this.videoLive.Video)
142 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
144 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
148 this.streamingPlaylist = await this.createLivePlaylist()
150 this.createLiveShaStore()
153 await this.prepareDirectories()
155 this.transcodingWrapper = this.buildTranscodingWrapper()
157 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
158 this.transcodingWrapper.on('error', () => this.onTranscodingError())
160 await this.transcodingWrapper.run()
162 this.filesWatcher = watch(this.outDirectory, { depth: 0 })
164 this.watchMasterFile()
169 if (!this.transcodingWrapper) return
172 this.transcodingWrapper.abort()
176 this.removeAllListeners()
177 this.isAbleToUploadVideoWithCache.clear()
178 this.hasClientSocketInBadHealthWithCache.clear()
181 private watchMasterFile () {
182 this.filesWatcher.on('add', async path => {
183 if (path !== join(this.outDirectory, this.streamingPlaylist.playlistFilename)) return
184 if (this.masterPlaylistCreated === true) return
187 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
188 const masterContent = await readFile(path, 'utf-8')
189 logger.debug('Uploading live master playlist on object storage for %s', this.videoUUID, { masterContent, ...this.lTags() })
191 const url = await storeHLSFileFromContent(this.streamingPlaylist, this.streamingPlaylist.playlistFilename, masterContent)
193 this.streamingPlaylist.playlistUrl = url
196 this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions)
198 await this.streamingPlaylist.save()
200 logger.error('Cannot update streaming playlist.', { err, ...this.lTags() })
203 this.masterPlaylistCreated = true
205 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
209 private watchTSFiles () {
210 const startStreamDateTime = new Date().getTime()
212 const addHandler = async (segmentPath: string) => {
213 if (segmentPath.endsWith('.ts') !== true) return
215 logger.debug('Live add handler of TS file %s.', segmentPath, this.lTags())
217 const playlistId = this.getPlaylistIdFromTS(segmentPath)
219 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
220 this.processSegments(segmentsToProcess)
222 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
224 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
225 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
229 // Duration constraint check
230 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
231 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
235 // Check user quota if the user enabled replay saving
236 if (await this.isQuotaExceeded(segmentPath) === true) {
237 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
241 const deleteHandler = async (segmentPath: string) => {
242 if (segmentPath.endsWith('.ts') !== true) return
244 logger.debug('Live delete handler of TS file %s.', segmentPath, this.lTags())
247 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
249 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
252 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
254 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
256 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
261 this.filesWatcher.on('add', p => addHandler(p))
262 this.filesWatcher.on('unlink', p => deleteHandler(p))
265 private async isQuotaExceeded (segmentPath: string) {
266 if (this.saveReplay !== true) return false
267 if (this.aborted) return false
270 const segmentStat = await stat(segmentPath)
272 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.sessionId, segmentStat.size)
274 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
276 return canUpload !== true
278 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
282 private createFiles () {
283 for (let i = 0; i < this.allResolutions.length; i++) {
284 const resolution = this.allResolutions[i]
286 const file = new VideoFileModel({
292 storage: this.streamingPlaylist.storage,
293 videoStreamingPlaylistId: this.streamingPlaylist.id
296 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
297 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
301 private async prepareDirectories () {
302 await ensureDir(this.outDirectory)
304 if (this.videoLive.saveReplay === true) {
305 await ensureDir(this.replayDirectory)
309 private isDurationConstraintValid (streamingStartTime: number) {
310 const maxDuration = CONFIG.LIVE.MAX_DURATION
312 if (maxDuration < 0) return true
314 const now = new Date().getTime()
315 const max = streamingStartTime + maxDuration
320 private processSegments (segmentPaths: string[]) {
321 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
323 if (this.aborted) return
325 logger.error('Cannot process segments', { err, ...this.lTags() })
329 private async processSegment (segmentPath: string) {
330 // Add sha hash of previous segments, because ffmpeg should have finished generating them
331 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
333 if (this.saveReplay) {
334 await this.addSegmentToReplay(segmentPath)
337 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
339 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
341 await this.processM3U8ToObjectStorage(segmentPath)
343 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
347 // Master playlist and segment JSON file are created, live is ready
348 if (this.masterPlaylistCreated && !this.liveReady) {
349 this.liveReady = true
351 this.emit('live-ready', { videoUUID: this.videoUUID })
355 private async processM3U8ToObjectStorage (segmentPath: string) {
356 const m3u8Path = join(this.outDirectory, this.getPlaylistNameFromTS(segmentPath))
358 logger.debug('Process M3U8 file %s.', m3u8Path, this.lTags())
360 const segmentName = basename(segmentPath)
362 const playlistContent = await readFile(m3u8Path, 'utf-8')
363 // Remove new chunk references, that will be processed later
364 const filteredPlaylistContent = playlistContent.substring(0, playlistContent.lastIndexOf(segmentName) + segmentName.length) + '\n'
367 if (!this.objectStorageSendQueues.has(m3u8Path)) {
368 this.objectStorageSendQueues.set(m3u8Path, new PQueue({ concurrency: 1 }))
371 const queue = this.objectStorageSendQueues.get(m3u8Path)
372 await queue.add(() => storeHLSFileFromContent(this.streamingPlaylist, m3u8Path, filteredPlaylistContent))
374 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
378 private onTranscodingError () {
379 this.emit('transcoding-error', ({ videoUUID: this.videoUUID }))
382 private onTranscodedEnded () {
383 this.emit('transcoding-end', ({ videoUUID: this.videoUUID }))
385 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputLocalUrl, this.lTags())
388 // Wait latest segments generation, and close watchers
390 const promise = this.filesWatcher?.close() || Promise.resolve()
393 // Process remaining segments hash
394 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
395 this.processSegments(this.segmentsToProcessPerPlaylist[key])
400 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
401 { err, ...this.lTags() }
405 this.emit('after-cleanup', { videoUUID: this.videoUUID })
409 private hasClientSocketInBadHealth (sessionId: string) {
410 const rtmpSession = this.context.sessions.get(sessionId)
413 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
417 for (const playerSessionId of rtmpSession.players) {
418 const playerSession = this.context.sessions.get(playerSessionId)
420 if (!playerSession) {
421 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
425 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
433 private async addSegmentToReplay (segmentPath: string) {
434 const segmentName = basename(segmentPath)
435 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
438 const data = await readFile(segmentPath)
440 await appendFile(dest, data)
442 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
446 private async createLivePlaylist (): Promise<MStreamingPlaylistVideo> {
447 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(this.videoLive.Video)
449 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
450 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
452 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
453 playlist.type = VideoStreamingPlaylistType.HLS
455 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
456 ? VideoStorage.OBJECT_STORAGE
457 : VideoStorage.FILE_SYSTEM
459 return playlist.save()
462 private createLiveShaStore () {
463 this.liveSegmentShaStore = new LiveSegmentShaStore({
464 videoUUID: this.videoLive.Video.uuid,
465 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
466 streamingPlaylist: this.streamingPlaylist,
467 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
471 private buildTranscodingWrapper () {
473 streamingPlaylist: this.streamingPlaylist,
474 videoLive: this.videoLive,
478 sessionId: this.sessionId,
479 inputLocalUrl: this.inputLocalUrl,
480 inputPublicUrl: this.inputPublicUrl,
482 toTranscode: this.allResolutions.map(resolution => ({
484 fps: computeOutputFPS({ inputFPS: this.fps, resolution })
488 bitrate: this.bitrate,
490 hasAudio: this.hasAudio,
492 segmentListSize: VIDEO_LIVE.SEGMENTS_LIST_SIZE,
493 segmentDuration: getLiveSegmentTime(this.videoLive.latencyMode),
495 outDirectory: this.outDirectory
498 return CONFIG.LIVE.TRANSCODING.ENABLED && CONFIG.LIVE.TRANSCODING.REMOTE_RUNNERS.ENABLED
499 ? new RemoteTranscodingWrapper(options)
500 : new FFmpegTranscodingWrapper(options)
503 private getPlaylistIdFromTS (segmentPath: string) {
504 const playlistIdMatcher = /^([\d+])-/
506 return basename(segmentPath).match(playlistIdMatcher)[1]
509 private getPlaylistNameFromTS (segmentPath: string) {
510 return `${this.getPlaylistIdFromTS(segmentPath)}.m3u8`
514 // ---------------------------------------------------------------------------