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, storeHLSFileFromFilename, 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
60 private readonly inputUrl: string
61 private readonly fps: number
62 private readonly allResolutions: number[]
64 private readonly bitrate: number
65 private readonly ratio: number
67 private readonly hasAudio: boolean
69 private readonly videoUUID: string
70 private readonly saveReplay: boolean
72 private readonly outDirectory: string
73 private readonly replayDirectory: string
75 private readonly lTags: LoggerTagsFn
77 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
79 private streamingPlaylist: MStreamingPlaylistVideo
80 private liveSegmentShaStore: LiveSegmentShaStore
82 private filesWatcher: FSWatcher
84 private masterPlaylistCreated = false
85 private liveReady = false
87 private aborted = false
89 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
90 return isAbleToUploadVideo(userId, 1000)
91 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
93 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
94 return this.hasClientSocketInBadHealth(sessionId)
95 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
97 constructor (options: {
101 videoLive: MVideoLiveVideo
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.inputUrl = options.inputUrl
116 this.fps = options.fps
118 this.bitrate = options.bitrate
119 this.ratio = options.ratio
121 this.hasAudio = options.hasAudio
123 this.allResolutions = options.allResolutions
125 this.videoUUID = this.videoLive.Video.uuid
127 this.saveReplay = this.videoLive.saveReplay
129 this.outDirectory = getLiveDirectory(this.videoLive.Video)
130 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
132 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
136 this.streamingPlaylist = await this.createLivePlaylist()
138 this.createLiveShaStore()
141 await this.prepareDirectories()
143 this.transcodingWrapper = this.buildTranscodingWrapper()
145 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
146 this.transcodingWrapper.on('error', () => this.onTranscodingError())
148 await this.transcodingWrapper.run()
150 this.filesWatcher = watch(this.outDirectory, { depth: 0 })
152 this.watchMasterFile()
158 if (!this.transcodingWrapper) return
161 this.transcodingWrapper.abort()
165 this.removeAllListeners()
166 this.isAbleToUploadVideoWithCache.clear()
167 this.hasClientSocketInBadHealthWithCache.clear()
170 private watchMasterFile () {
171 this.filesWatcher.on('add', async path => {
172 if (path !== join(this.outDirectory, this.streamingPlaylist.playlistFilename)) return
173 if (this.masterPlaylistCreated === true) return
176 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
177 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
179 this.streamingPlaylist.playlistUrl = url
182 this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions)
184 await this.streamingPlaylist.save()
186 logger.error('Cannot update streaming playlist.', { err, ...this.lTags() })
189 this.masterPlaylistCreated = true
191 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
195 private watchM3U8File () {
196 const sendQueues = new Map<string, PQueue>()
198 const onChange = async (m3u8Path: string) => {
199 if (m3u8Path.endsWith('.m3u8') !== true) return
200 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
202 logger.debug('Live change handler of M3U8 file %s.', m3u8Path, this.lTags())
205 if (!sendQueues.has(m3u8Path)) {
206 sendQueues.set(m3u8Path, new PQueue({ concurrency: 1 }))
209 const queue = sendQueues.get(m3u8Path)
210 await queue.add(() => storeHLSFileFromPath(this.streamingPlaylist, m3u8Path))
212 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
216 this.filesWatcher.on('change', onChange)
219 private watchTSFiles () {
220 const startStreamDateTime = new Date().getTime()
222 const playlistIdMatcher = /^([\d+])-/
224 const addHandler = async (segmentPath: string) => {
225 if (segmentPath.endsWith('.ts') !== true) return
227 logger.debug('Live add handler of TS file %s.', segmentPath, this.lTags())
229 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
231 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
232 this.processSegments(segmentsToProcess)
234 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
236 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
237 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
241 // Duration constraint check
242 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
243 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
247 // Check user quota if the user enabled replay saving
248 if (await this.isQuotaExceeded(segmentPath) === true) {
249 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
253 const deleteHandler = async (segmentPath: string) => {
254 if (segmentPath.endsWith('.ts') !== true) return
256 logger.debug('Live delete handler of TS file %s.', segmentPath, this.lTags())
259 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
261 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
264 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
266 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
268 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
273 this.filesWatcher.on('add', p => addHandler(p))
274 this.filesWatcher.on('unlink', p => deleteHandler(p))
277 private async isQuotaExceeded (segmentPath: string) {
278 if (this.saveReplay !== true) return false
279 if (this.aborted) return false
282 const segmentStat = await stat(segmentPath)
284 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
286 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
288 return canUpload !== true
290 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
294 private createFiles () {
295 for (let i = 0; i < this.allResolutions.length; i++) {
296 const resolution = this.allResolutions[i]
298 const file = new VideoFileModel({
304 storage: this.streamingPlaylist.storage,
305 videoStreamingPlaylistId: this.streamingPlaylist.id
308 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
309 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
313 private async prepareDirectories () {
314 await ensureDir(this.outDirectory)
316 if (this.videoLive.saveReplay === true) {
317 await ensureDir(this.replayDirectory)
321 private isDurationConstraintValid (streamingStartTime: number) {
322 const maxDuration = CONFIG.LIVE.MAX_DURATION
324 if (maxDuration < 0) return true
326 const now = new Date().getTime()
327 const max = streamingStartTime + maxDuration
332 private processSegments (segmentPaths: string[]) {
333 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
335 if (this.aborted) return
337 logger.error('Cannot process segments', { err, ...this.lTags() })
341 private async processSegment (segmentPath: string) {
342 // Add sha hash of previous segments, because ffmpeg should have finished generating them
343 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
345 if (this.saveReplay) {
346 await this.addSegmentToReplay(segmentPath)
349 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
351 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
353 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
357 // Master playlist and segment JSON file are created, live is ready
358 if (this.masterPlaylistCreated && !this.liveReady) {
359 this.liveReady = true
361 this.emit('live-ready', { videoUUID: this.videoUUID })
365 private onTranscodingError () {
366 this.emit('transcoding-error', ({ videoUUID: this.videoUUID }))
369 private onTranscodedEnded () {
370 this.emit('transcoding-end', ({ videoUUID: this.videoUUID }))
372 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
375 // Wait latest segments generation, and close watchers
377 const promise = this.filesWatcher?.close() || Promise.resolve()
380 // Process remaining segments hash
381 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
382 this.processSegments(this.segmentsToProcessPerPlaylist[key])
387 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
388 { err, ...this.lTags() }
392 this.emit('after-cleanup', { videoUUID: this.videoUUID })
396 private hasClientSocketInBadHealth (sessionId: string) {
397 const rtmpSession = this.context.sessions.get(sessionId)
400 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
404 for (const playerSessionId of rtmpSession.players) {
405 const playerSession = this.context.sessions.get(playerSessionId)
407 if (!playerSession) {
408 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
412 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
420 private async addSegmentToReplay (segmentPath: string) {
421 const segmentName = basename(segmentPath)
422 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
425 const data = await readFile(segmentPath)
427 await appendFile(dest, data)
429 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
433 private async createLivePlaylist (): Promise<MStreamingPlaylistVideo> {
434 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(this.videoLive.Video)
436 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
437 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
439 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
440 playlist.type = VideoStreamingPlaylistType.HLS
442 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
443 ? VideoStorage.OBJECT_STORAGE
444 : VideoStorage.FILE_SYSTEM
446 return playlist.save()
449 private createLiveShaStore () {
450 this.liveSegmentShaStore = new LiveSegmentShaStore({
451 videoUUID: this.videoLive.Video.uuid,
452 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
453 streamingPlaylist: this.streamingPlaylist,
454 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
458 private buildTranscodingWrapper () {
460 streamingPlaylist: this.streamingPlaylist,
461 videoLive: this.videoLive,
465 inputUrl: this.inputUrl,
467 toTranscode: this.allResolutions.map(resolution => ({
469 fps: computeOutputFPS({ inputFPS: this.fps, resolution })
473 bitrate: this.bitrate,
475 hasAudio: this.hasAudio,
477 segmentListSize: VIDEO_LIVE.SEGMENTS_LIST_SIZE,
478 segmentDuration: getLiveSegmentTime(this.videoLive.latencyMode),
480 outDirectory: this.outDirectory
483 return CONFIG.LIVE.TRANSCODING.ENABLED && CONFIG.LIVE.TRANSCODING.REMOTE_RUNNERS.ENABLED
484 ? new RemoteTranscodingWrapper(options)
485 : new FFmpegTranscodingWrapper(options)
489 // ---------------------------------------------------------------------------