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 tsWatcher: FSWatcher
83 private masterWatcher: FSWatcher
84 private m3u8Watcher: FSWatcher
86 private masterPlaylistCreated = false
87 private liveReady = false
89 private aborted = false
91 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
92 return isAbleToUploadVideo(userId, 1000)
93 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
95 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
96 return this.hasClientSocketInBadHealth(sessionId)
97 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
99 constructor (options: {
103 videoLive: MVideoLiveVideo
108 allResolutions: number[]
113 this.context = options.context
114 this.user = options.user
115 this.sessionId = options.sessionId
116 this.videoLive = options.videoLive
117 this.inputUrl = options.inputUrl
118 this.fps = options.fps
120 this.bitrate = options.bitrate
121 this.ratio = options.ratio
123 this.hasAudio = options.hasAudio
125 this.allResolutions = options.allResolutions
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.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
138 this.streamingPlaylist = await this.createLivePlaylist()
140 this.createLiveShaStore()
143 await this.prepareDirectories()
145 this.transcodingWrapper = this.buildTranscodingWrapper()
147 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
148 this.transcodingWrapper.on('error', () => this.onTranscodingError())
150 await this.transcodingWrapper.run()
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.masterWatcher = watch(this.outDirectory + '/' + this.streamingPlaylist.playlistFilename)
173 this.masterWatcher.on('add', async () => {
175 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
176 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
178 this.streamingPlaylist.playlistUrl = url
181 this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions)
183 await this.streamingPlaylist.save()
185 logger.error('Cannot update streaming playlist.', { err, ...this.lTags() })
188 this.masterPlaylistCreated = true
190 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
192 this.masterWatcher.close()
193 .catch(err => logger.error('Cannot close master watcher of %s.', this.outDirectory, { err, ...this.lTags() }))
197 private watchM3U8File () {
198 this.m3u8Watcher = watch(this.outDirectory + '/*.m3u8')
200 const sendQueues = new Map<string, PQueue>()
202 const onChangeOrAdd = async (m3u8Path: string) => {
203 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
206 if (!sendQueues.has(m3u8Path)) {
207 sendQueues.set(m3u8Path, new PQueue({ concurrency: 1 }))
210 const queue = sendQueues.get(m3u8Path)
211 await queue.add(() => storeHLSFileFromPath(this.streamingPlaylist, m3u8Path))
213 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
217 this.m3u8Watcher.on('change', onChangeOrAdd)
220 private watchTSFiles () {
221 const startStreamDateTime = new Date().getTime()
223 this.tsWatcher = watch(this.outDirectory + '/*.ts')
225 const playlistIdMatcher = /^([\d+])-/
227 const addHandler = async (segmentPath: string) => {
228 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
230 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
232 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
233 this.processSegments(segmentsToProcess)
235 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
237 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
238 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
242 // Duration constraint check
243 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
244 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
248 // Check user quota if the user enabled replay saving
249 if (await this.isQuotaExceeded(segmentPath) === true) {
250 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
254 const deleteHandler = async (segmentPath: string) => {
256 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
258 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
261 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
263 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
265 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
270 this.tsWatcher.on('add', p => addHandler(p))
271 this.tsWatcher.on('unlink', p => deleteHandler(p))
274 private async isQuotaExceeded (segmentPath: string) {
275 if (this.saveReplay !== true) return false
276 if (this.aborted) return false
279 const segmentStat = await stat(segmentPath)
281 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
283 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
285 return canUpload !== true
287 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
291 private createFiles () {
292 for (let i = 0; i < this.allResolutions.length; i++) {
293 const resolution = this.allResolutions[i]
295 const file = new VideoFileModel({
301 storage: this.streamingPlaylist.storage,
302 videoStreamingPlaylistId: this.streamingPlaylist.id
305 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
306 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
310 private async prepareDirectories () {
311 await ensureDir(this.outDirectory)
313 if (this.videoLive.saveReplay === true) {
314 await ensureDir(this.replayDirectory)
318 private isDurationConstraintValid (streamingStartTime: number) {
319 const maxDuration = CONFIG.LIVE.MAX_DURATION
321 if (maxDuration < 0) return true
323 const now = new Date().getTime()
324 const max = streamingStartTime + maxDuration
329 private processSegments (segmentPaths: string[]) {
330 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
332 if (this.aborted) return
334 logger.error('Cannot process segments', { err, ...this.lTags() })
338 private async processSegment (segmentPath: string) {
339 // Add sha hash of previous segments, because ffmpeg should have finished generating them
340 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
342 if (this.saveReplay) {
343 await this.addSegmentToReplay(segmentPath)
346 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
348 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
350 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
354 // Master playlist and segment JSON file are created, live is ready
355 if (this.masterPlaylistCreated && !this.liveReady) {
356 this.liveReady = true
358 this.emit('live-ready', { videoUUID: this.videoUUID })
362 private onTranscodingError () {
363 this.emit('transcoding-error', ({ videoUUID: this.videoUUID }))
366 private onTranscodedEnded () {
367 this.emit('transcoding-end', ({ videoUUID: this.videoUUID }))
369 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
372 // Wait latest segments generation, and close watchers
374 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close(), this.m3u8Watcher.close() ])
376 // Process remaining segments hash
377 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
378 this.processSegments(this.segmentsToProcessPerPlaylist[key])
383 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
384 { err, ...this.lTags() }
388 this.emit('after-cleanup', { videoUUID: this.videoUUID })
392 private hasClientSocketInBadHealth (sessionId: string) {
393 const rtmpSession = this.context.sessions.get(sessionId)
396 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
400 for (const playerSessionId of rtmpSession.players) {
401 const playerSession = this.context.sessions.get(playerSessionId)
403 if (!playerSession) {
404 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
408 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
416 private async addSegmentToReplay (segmentPath: string) {
417 const segmentName = basename(segmentPath)
418 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
421 const data = await readFile(segmentPath)
423 await appendFile(dest, data)
425 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
429 private async createLivePlaylist (): Promise<MStreamingPlaylistVideo> {
430 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(this.videoLive.Video)
432 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
433 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
435 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
436 playlist.type = VideoStreamingPlaylistType.HLS
438 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
439 ? VideoStorage.OBJECT_STORAGE
440 : VideoStorage.FILE_SYSTEM
442 return playlist.save()
445 private createLiveShaStore () {
446 this.liveSegmentShaStore = new LiveSegmentShaStore({
447 videoUUID: this.videoLive.Video.uuid,
448 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
449 streamingPlaylist: this.streamingPlaylist,
450 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
454 private buildTranscodingWrapper () {
456 streamingPlaylist: this.streamingPlaylist,
457 videoLive: this.videoLive,
461 inputUrl: this.inputUrl,
463 toTranscode: this.allResolutions.map(resolution => ({
465 fps: computeOutputFPS({ inputFPS: this.fps, resolution })
469 bitrate: this.bitrate,
471 hasAudio: this.hasAudio,
473 segmentListSize: VIDEO_LIVE.SEGMENTS_LIST_SIZE,
474 segmentDuration: getLiveSegmentTime(this.videoLive.latencyMode),
476 outDirectory: this.outDirectory
479 return CONFIG.LIVE.TRANSCODING.ENABLED && CONFIG.LIVE.TRANSCODING.REMOTE_RUNNERS.ENABLED
480 ? new RemoteTranscodingWrapper(options)
481 : new FFmpegTranscodingWrapper(options)
485 // ---------------------------------------------------------------------------