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 { VideoFileModel } from '@server/models/video/video-file'
13 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
14 import { getLiveDirectory } from '../../paths'
15 import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles'
16 import { isAbleToUploadVideo } from '../../user'
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 inputUrl: string
56 private readonly fps: number
57 private readonly allResolutions: number[]
59 private readonly bitrate: number
60 private readonly ratio: number
62 private readonly videoId: number
63 private readonly videoUUID: string
64 private readonly saveReplay: boolean
66 private readonly lTags: LoggerTagsFn
68 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
70 private tsWatcher: FSWatcher
71 private masterWatcher: FSWatcher
73 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
74 return isAbleToUploadVideo(userId, 1000)
75 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
77 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
78 return this.hasClientSocketInBadHealth(sessionId)
79 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
81 constructor (options: {
85 videoLive: MVideoLiveVideo
86 streamingPlaylist: MStreamingPlaylistVideo
91 allResolutions: number[]
95 this.context = options.context
96 this.user = options.user
97 this.sessionId = options.sessionId
98 this.videoLive = options.videoLive
99 this.streamingPlaylist = options.streamingPlaylist
100 this.inputUrl = options.inputUrl
101 this.fps = options.fps
103 this.bitrate = options.bitrate
104 this.ratio = options.ratio
106 this.allResolutions = options.allResolutions
108 this.videoId = this.videoLive.Video.id
109 this.videoUUID = this.videoLive.Video.uuid
111 this.saveReplay = this.videoLive.saveReplay
113 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
119 const outPath = await this.prepareDirectories()
121 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
122 ? await getLiveTranscodingCommand({
123 inputUrl: this.inputUrl,
126 masterPlaylistName: this.streamingPlaylist.playlistFilename,
128 latencyMode: this.videoLive.latencyMode,
130 resolutions: this.allResolutions,
132 bitrate: this.bitrate,
135 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
136 profile: CONFIG.LIVE.TRANSCODING.PROFILE
138 : getLiveMuxingCommand({
139 inputUrl: this.inputUrl,
141 masterPlaylistName: this.streamingPlaylist.playlistFilename,
142 latencyMode: this.videoLive.latencyMode
145 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
147 this.watchTSFiles(outPath)
148 this.watchMasterFile(outPath)
150 let ffmpegShellCommand: string
151 this.ffmpegCommand.on('start', cmdline => {
152 ffmpegShellCommand = cmdline
154 logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() })
157 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
158 this.onFFmpegError({ err, stdout, stderr, outPath, ffmpegShellCommand })
161 this.ffmpegCommand.on('end', () => this.onFFmpegEnded(outPath))
163 this.ffmpegCommand.run()
167 if (!this.ffmpegCommand) return
169 this.ffmpegCommand.kill('SIGINT')
173 this.removeAllListeners()
174 this.isAbleToUploadVideoWithCache.clear()
175 this.hasClientSocketInBadHealthWithCache.clear()
178 private onFFmpegError (options: {
183 ffmpegShellCommand: string
185 const { err, stdout, stderr, outPath, ffmpegShellCommand } = options
187 this.onFFmpegEnded(outPath)
189 // Don't care that we killed the ffmpeg process
190 if (err?.message?.includes('Exiting normally')) return
192 logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
194 this.emit('ffmpeg-error', ({ sessionId: this.sessionId }))
197 private onFFmpegEnded (outPath: string) {
198 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
201 // Wait latest segments generation, and close watchers
203 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ])
205 // Process remaining segments hash
206 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
207 this.processSegments(outPath, this.segmentsToProcessPerPlaylist[key])
212 'Cannot close watchers of %s or process remaining hash segments.', outPath,
213 { err, ...this.lTags() }
217 this.emit('after-cleanup', { videoId: this.videoId })
221 private watchMasterFile (outPath: string) {
222 this.masterWatcher = watch(outPath + '/' + this.streamingPlaylist.playlistFilename)
224 this.masterWatcher.on('add', () => {
225 this.emit('master-playlist-created', { videoId: this.videoId })
227 this.masterWatcher.close()
228 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags() }))
232 private watchTSFiles (outPath: string) {
233 const startStreamDateTime = new Date().getTime()
235 this.tsWatcher = watch(outPath + '/*.ts')
237 const playlistIdMatcher = /^([\d+])-/
239 const addHandler = async (segmentPath: string) => {
240 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
242 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
244 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
245 this.processSegments(outPath, segmentsToProcess)
247 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
249 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
250 this.emit('bad-socket-health', { videoId: this.videoId })
254 // Duration constraint check
255 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
256 this.emit('duration-exceeded', { videoId: this.videoId })
260 // Check user quota if the user enabled replay saving
261 if (await this.isQuotaExceeded(segmentPath) === true) {
262 this.emit('quota-exceeded', { videoId: this.videoId })
266 const deleteHandler = segmentPath => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath)
268 this.tsWatcher.on('add', p => addHandler(p))
269 this.tsWatcher.on('unlink', p => deleteHandler(p))
272 private async isQuotaExceeded (segmentPath: string) {
273 if (this.saveReplay !== true) return false
276 const segmentStat = await stat(segmentPath)
278 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
280 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
282 return canUpload !== true
284 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
288 private createFiles () {
289 for (let i = 0; i < this.allResolutions.length; i++) {
290 const resolution = this.allResolutions[i]
292 const file = new VideoFileModel({
298 videoStreamingPlaylistId: this.streamingPlaylist.id
301 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
302 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
306 private async prepareDirectories () {
307 const outPath = getLiveDirectory(this.videoLive.Video)
308 await ensureDir(outPath)
310 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
312 if (this.videoLive.saveReplay === true) {
313 await ensureDir(replayDirectory)
319 private isDurationConstraintValid (streamingStartTime: number) {
320 const maxDuration = CONFIG.LIVE.MAX_DURATION
322 if (maxDuration < 0) return true
324 const now = new Date().getTime()
325 const max = streamingStartTime + maxDuration
330 private processSegments (hlsVideoPath: string, segmentPaths: string[]) {
331 mapSeries(segmentPaths, async previousSegment => {
332 // Add sha hash of previous segments, because ffmpeg should have finished generating them
333 await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
335 if (this.saveReplay) {
336 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
338 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags() }))
341 private hasClientSocketInBadHealth (sessionId: string) {
342 const rtmpSession = this.context.sessions.get(sessionId)
345 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
349 for (const playerSessionId of rtmpSession.players) {
350 const playerSession = this.context.sessions.get(playerSessionId)
352 if (!playerSession) {
353 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
357 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
365 private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
366 const segmentName = basename(segmentPath)
367 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, buildConcatenatedName(segmentName))
370 const data = await readFile(segmentPath)
372 await appendFile(dest, data)
374 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
379 // ---------------------------------------------------------------------------