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-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 { getLiveDirectory } from '../../paths'
15 import { VideoTranscodingProfilesManager } from '../../transcoding/video-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 rtmpUrl: 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.rtmpUrl = options.rtmpUrl
101 this.fps = options.fps
103 this.bitrate = options.bitrate
104 this.ratio = options.bitrate
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 rtmpUrl: this.rtmpUrl,
126 masterPlaylistName: this.streamingPlaylist.playlistFilename,
128 resolutions: this.allResolutions,
130 bitrate: this.bitrate,
133 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
134 profile: CONFIG.LIVE.TRANSCODING.PROFILE
136 : getLiveMuxingCommand(this.rtmpUrl, outPath, this.streamingPlaylist.playlistFilename)
138 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags)
140 this.watchTSFiles(outPath)
141 this.watchMasterFile(outPath)
143 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
144 this.onFFmpegError(err, stdout, stderr, outPath)
147 this.ffmpegCommand.on('end', () => this.onFFmpegEnded(outPath))
149 this.ffmpegCommand.run()
153 if (!this.ffmpegCommand) return
155 this.ffmpegCommand.kill('SIGINT')
159 this.removeAllListeners()
160 this.isAbleToUploadVideoWithCache.clear()
161 this.hasClientSocketInBadHealthWithCache.clear()
164 private onFFmpegError (err: any, stdout: string, stderr: string, outPath: string) {
165 this.onFFmpegEnded(outPath)
167 // Don't care that we killed the ffmpeg process
168 if (err?.message?.includes('Exiting normally')) return
170 logger.error('Live transcoding error.', { err, stdout, stderr, ...this.lTags })
172 this.emit('ffmpeg-error', ({ sessionId: this.sessionId }))
175 private onFFmpegEnded (outPath: string) {
176 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.rtmpUrl, this.lTags)
179 // Wait latest segments generation, and close watchers
181 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ])
183 // Process remaining segments hash
184 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
185 this.processSegments(outPath, this.segmentsToProcessPerPlaylist[key])
190 'Cannot close watchers of %s or process remaining hash segments.', outPath,
191 { err, ...this.lTags }
195 this.emit('after-cleanup', { videoId: this.videoId })
199 private watchMasterFile (outPath: string) {
200 this.masterWatcher = watch(outPath + '/' + this.streamingPlaylist.playlistFilename)
202 this.masterWatcher.on('add', () => {
203 this.emit('master-playlist-created', { videoId: this.videoId })
205 this.masterWatcher.close()
206 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags }))
210 private watchTSFiles (outPath: string) {
211 const startStreamDateTime = new Date().getTime()
213 this.tsWatcher = watch(outPath + '/*.ts')
215 const playlistIdMatcher = /^([\d+])-/
217 const addHandler = async segmentPath => {
218 logger.debug('Live add handler of %s.', segmentPath, this.lTags)
220 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
222 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
223 this.processSegments(outPath, segmentsToProcess)
225 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
227 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
228 this.emit('bad-socket-health', { videoId: this.videoId })
232 // Duration constraint check
233 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
234 this.emit('duration-exceeded', { videoId: this.videoId })
238 // Check user quota if the user enabled replay saving
239 if (await this.isQuotaExceeded(segmentPath) === true) {
240 this.emit('quota-exceeded', { videoId: this.videoId })
244 const deleteHandler = segmentPath => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath)
246 this.tsWatcher.on('add', p => addHandler(p))
247 this.tsWatcher.on('unlink', p => deleteHandler(p))
250 private async isQuotaExceeded (segmentPath: string) {
251 if (this.saveReplay !== true) return false
254 const segmentStat = await stat(segmentPath)
256 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
258 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
260 return canUpload !== true
262 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags })
266 private createFiles () {
267 for (let i = 0; i < this.allResolutions.length; i++) {
268 const resolution = this.allResolutions[i]
270 const file = new VideoFileModel({
276 videoStreamingPlaylistId: this.streamingPlaylist.id
279 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
280 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags }))
284 private async prepareDirectories () {
285 const outPath = getLiveDirectory(this.videoLive.Video)
286 await ensureDir(outPath)
288 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
290 if (this.videoLive.saveReplay === true) {
291 await ensureDir(replayDirectory)
297 private isDurationConstraintValid (streamingStartTime: number) {
298 const maxDuration = CONFIG.LIVE.MAX_DURATION
300 if (maxDuration < 0) return true
302 const now = new Date().getTime()
303 const max = streamingStartTime + maxDuration
308 private processSegments (hlsVideoPath: string, segmentPaths: string[]) {
309 mapSeries(segmentPaths, async previousSegment => {
310 // Add sha hash of previous segments, because ffmpeg should have finished generating them
311 await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
313 if (this.saveReplay) {
314 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
316 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags }))
319 private hasClientSocketInBadHealth (sessionId: string) {
320 const rtmpSession = this.context.sessions.get(sessionId)
323 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags)
327 for (const playerSessionId of rtmpSession.players) {
328 const playerSession = this.context.sessions.get(playerSessionId)
330 if (!playerSession) {
331 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags)
335 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
343 private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
344 const segmentName = basename(segmentPath)
345 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, buildConcatenatedName(segmentName))
348 const data = await readFile(segmentPath)
350 await appendFile(dest, data)
352 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags })
357 // ---------------------------------------------------------------------------