2 import * as Bluebird from 'bluebird'
3 import * as chokidar 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-utils'
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 { VideoFileModel } from '@server/models/video/video-file'
13 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
14 import { VideoTranscodingProfilesManager } from '../../transcoding/video-transcoding-profiles'
15 import { isAbleToUploadVideo } from '../../user'
16 import { getHLSDirectory } from '../../video-paths'
17 import { LiveQuotaStore } from '../live-quota-store'
18 import { LiveSegmentShaStore } from '../live-segment-sha-store'
19 import { buildConcatenatedName } from '../live-utils'
21 import memoizee = require('memoizee')
23 interface MuxingSessionEvents {
24 'master-playlist-created': ({ videoId: number }) => void
26 'bad-socket-health': ({ videoId: number }) => void
27 'duration-exceeded': ({ videoId: number }) => void
28 'quota-exceeded': ({ videoId: number }) => void
30 'ffmpeg-end': ({ videoId: number }) => void
31 'ffmpeg-error': ({ sessionId: string }) => void
33 'after-cleanup': ({ videoId: number }) => void
36 declare interface MuxingSession {
37 on<U extends keyof MuxingSessionEvents>(
38 event: U, listener: MuxingSessionEvents[U]
41 emit<U extends keyof MuxingSessionEvents>(
42 event: U, ...args: Parameters<MuxingSessionEvents[U]>
46 class MuxingSession extends EventEmitter {
48 private ffmpegCommand: FfmpegCommand
50 private readonly context: any
51 private readonly user: MUserId
52 private readonly sessionId: string
53 private readonly videoLive: MVideoLiveVideo
54 private readonly streamingPlaylist: MStreamingPlaylistVideo
55 private readonly rtmpUrl: string
56 private readonly fps: number
57 private readonly allResolutions: number[]
59 private readonly videoId: number
60 private readonly videoUUID: string
61 private readonly saveReplay: boolean
65 private readonly lTags: LoggerTagsFn
67 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
69 private tsWatcher: chokidar.FSWatcher
70 private masterWatcher: chokidar.FSWatcher
72 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
73 return isAbleToUploadVideo(userId, 1000)
74 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
76 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
77 return this.hasClientSocketInBadHealth(sessionId)
78 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
80 constructor (options: {
84 videoLive: MVideoLiveVideo
85 streamingPlaylist: MStreamingPlaylistVideo
88 allResolutions: number[]
92 this.context = options.context
93 this.user = options.user
94 this.sessionId = options.sessionId
95 this.videoLive = options.videoLive
96 this.streamingPlaylist = options.streamingPlaylist
97 this.rtmpUrl = options.rtmpUrl
98 this.fps = options.fps
99 this.allResolutions = options.allResolutions
101 this.videoId = this.videoLive.Video.id
102 this.videoUUID = this.videoLive.Video.uuid
104 this.saveReplay = this.videoLive.saveReplay
106 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
108 this.toto = Buffer.alloc(1_000_000_000)
114 const outPath = await this.prepareDirectories()
116 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
117 ? await getLiveTranscodingCommand({
118 rtmpUrl: this.rtmpUrl,
120 resolutions: this.allResolutions,
122 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
123 profile: CONFIG.LIVE.TRANSCODING.PROFILE
125 : getLiveMuxingCommand(this.rtmpUrl, outPath)
127 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags)
129 this.watchTSFiles(outPath)
130 this.watchMasterFile(outPath)
132 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
133 this.onFFmpegError(err, stdout, stderr, outPath)
136 this.ffmpegCommand.on('end', () => this.onFFmpegEnded(outPath))
138 this.ffmpegCommand.run()
142 if (!this.ffmpegCommand) return
144 this.ffmpegCommand.kill('SIGINT')
148 this.removeAllListeners()
149 this.isAbleToUploadVideoWithCache.clear()
150 this.hasClientSocketInBadHealthWithCache.clear()
153 private onFFmpegError (err: any, stdout: string, stderr: string, outPath: string) {
154 this.onFFmpegEnded(outPath)
156 // Don't care that we killed the ffmpeg process
157 if (err?.message?.includes('Exiting normally')) return
159 logger.error('Live transcoding error.', { err, stdout, stderr, ...this.lTags })
161 this.emit('ffmpeg-error', ({ sessionId: this.sessionId }))
164 private onFFmpegEnded (outPath: string) {
165 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.rtmpUrl, this.lTags)
168 // Wait latest segments generation, and close watchers
170 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ])
172 // Process remaining segments hash
173 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
174 this.processSegments(outPath, this.segmentsToProcessPerPlaylist[key])
179 'Cannot close watchers of %s or process remaining hash segments.', outPath,
180 { err, ...this.lTags }
184 this.emit('after-cleanup', { videoId: this.videoId })
188 private watchMasterFile (outPath: string) {
189 this.masterWatcher = chokidar.watch(outPath + '/master.m3u8')
191 this.masterWatcher.on('add', async () => {
192 this.emit('master-playlist-created', { videoId: this.videoId })
194 this.masterWatcher.close()
195 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags }))
199 private watchTSFiles (outPath: string) {
200 const startStreamDateTime = new Date().getTime()
202 this.tsWatcher = chokidar.watch(outPath + '/*.ts')
204 const playlistIdMatcher = /^([\d+])-/
206 const addHandler = async segmentPath => {
207 logger.debug('Live add handler of %s.', segmentPath, this.lTags)
209 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
211 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
212 this.processSegments(outPath, segmentsToProcess)
214 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
216 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
217 this.emit('bad-socket-health', { videoId: this.videoId })
221 // Duration constraint check
222 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
223 this.emit('duration-exceeded', { videoId: this.videoId })
227 // Check user quota if the user enabled replay saving
228 if (await this.isQuotaExceeded(segmentPath) === true) {
229 this.emit('quota-exceeded', { videoId: this.videoId })
233 const deleteHandler = segmentPath => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath)
235 this.tsWatcher.on('add', p => addHandler(p))
236 this.tsWatcher.on('unlink', p => deleteHandler(p))
239 private async isQuotaExceeded (segmentPath: string) {
240 if (this.saveReplay !== true) return false
243 const segmentStat = await stat(segmentPath)
245 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
247 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
249 return canUpload !== true
251 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags })
255 private createFiles () {
256 for (let i = 0; i < this.allResolutions.length; i++) {
257 const resolution = this.allResolutions[i]
259 const file = new VideoFileModel({
265 videoStreamingPlaylistId: this.streamingPlaylist.id
268 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
269 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags }))
273 private async prepareDirectories () {
274 const outPath = getHLSDirectory(this.videoLive.Video)
275 await ensureDir(outPath)
277 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
279 if (this.videoLive.saveReplay === true) {
280 await ensureDir(replayDirectory)
286 private isDurationConstraintValid (streamingStartTime: number) {
287 const maxDuration = CONFIG.LIVE.MAX_DURATION
289 if (maxDuration < 0) return true
291 const now = new Date().getTime()
292 const max = streamingStartTime + maxDuration
297 private processSegments (hlsVideoPath: string, segmentPaths: string[]) {
298 Bluebird.mapSeries(segmentPaths, async previousSegment => {
299 // Add sha hash of previous segments, because ffmpeg should have finished generating them
300 await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
302 if (this.saveReplay) {
303 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
305 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags }))
308 private hasClientSocketInBadHealth (sessionId: string) {
309 const rtmpSession = this.context.sessions.get(sessionId)
312 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags)
316 for (const playerSessionId of rtmpSession.players) {
317 const playerSession = this.context.sessions.get(playerSessionId)
319 if (!playerSession) {
320 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags)
324 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
332 private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
333 const segmentName = basename(segmentPath)
334 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, buildConcatenatedName(segmentName))
337 const data = await readFile(segmentPath)
339 await appendFile(dest, data)
341 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags })
346 // ---------------------------------------------------------------------------