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
63 private readonly lTags: LoggerTagsFn
65 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
67 private tsWatcher: chokidar.FSWatcher
68 private masterWatcher: chokidar.FSWatcher
70 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
71 return isAbleToUploadVideo(userId, 1000)
72 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
74 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
75 return this.hasClientSocketInBadHealth(sessionId)
76 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
78 constructor (options: {
82 videoLive: MVideoLiveVideo
83 streamingPlaylist: MStreamingPlaylistVideo
86 allResolutions: number[]
90 this.context = options.context
91 this.user = options.user
92 this.sessionId = options.sessionId
93 this.videoLive = options.videoLive
94 this.streamingPlaylist = options.streamingPlaylist
95 this.rtmpUrl = options.rtmpUrl
96 this.fps = options.fps
97 this.allResolutions = options.allResolutions
99 this.videoId = this.videoLive.Video.id
100 this.videoUUID = this.videoLive.Video.uuid
102 this.saveReplay = this.videoLive.saveReplay
104 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
110 const outPath = await this.prepareDirectories()
112 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
113 ? await getLiveTranscodingCommand({
114 rtmpUrl: this.rtmpUrl,
117 masterPlaylistName: this.streamingPlaylist.playlistFilename,
119 resolutions: this.allResolutions,
121 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
122 profile: CONFIG.LIVE.TRANSCODING.PROFILE
124 : getLiveMuxingCommand(this.rtmpUrl, outPath, this.streamingPlaylist.playlistFilename)
126 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags)
128 this.watchTSFiles(outPath)
129 this.watchMasterFile(outPath)
131 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
132 this.onFFmpegError(err, stdout, stderr, outPath)
135 this.ffmpegCommand.on('end', () => this.onFFmpegEnded(outPath))
137 this.ffmpegCommand.run()
141 if (!this.ffmpegCommand) return
143 this.ffmpegCommand.kill('SIGINT')
147 this.removeAllListeners()
148 this.isAbleToUploadVideoWithCache.clear()
149 this.hasClientSocketInBadHealthWithCache.clear()
152 private onFFmpegError (err: any, stdout: string, stderr: string, outPath: string) {
153 this.onFFmpegEnded(outPath)
155 // Don't care that we killed the ffmpeg process
156 if (err?.message?.includes('Exiting normally')) return
158 logger.error('Live transcoding error.', { err, stdout, stderr, ...this.lTags })
160 this.emit('ffmpeg-error', ({ sessionId: this.sessionId }))
163 private onFFmpegEnded (outPath: string) {
164 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.rtmpUrl, this.lTags)
167 // Wait latest segments generation, and close watchers
169 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ])
171 // Process remaining segments hash
172 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
173 this.processSegments(outPath, this.segmentsToProcessPerPlaylist[key])
178 'Cannot close watchers of %s or process remaining hash segments.', outPath,
179 { err, ...this.lTags }
183 this.emit('after-cleanup', { videoId: this.videoId })
187 private watchMasterFile (outPath: string) {
188 this.masterWatcher = chokidar.watch(outPath + '/' + this.streamingPlaylist.playlistFilename)
190 this.masterWatcher.on('add', async () => {
191 this.emit('master-playlist-created', { videoId: this.videoId })
193 this.masterWatcher.close()
194 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags }))
198 private watchTSFiles (outPath: string) {
199 const startStreamDateTime = new Date().getTime()
201 this.tsWatcher = chokidar.watch(outPath + '/*.ts')
203 const playlistIdMatcher = /^([\d+])-/
205 const addHandler = async segmentPath => {
206 logger.debug('Live add handler of %s.', segmentPath, this.lTags)
208 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
210 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
211 this.processSegments(outPath, segmentsToProcess)
213 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
215 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
216 this.emit('bad-socket-health', { videoId: this.videoId })
220 // Duration constraint check
221 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
222 this.emit('duration-exceeded', { videoId: this.videoId })
226 // Check user quota if the user enabled replay saving
227 if (await this.isQuotaExceeded(segmentPath) === true) {
228 this.emit('quota-exceeded', { videoId: this.videoId })
232 const deleteHandler = segmentPath => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath)
234 this.tsWatcher.on('add', p => addHandler(p))
235 this.tsWatcher.on('unlink', p => deleteHandler(p))
238 private async isQuotaExceeded (segmentPath: string) {
239 if (this.saveReplay !== true) return false
242 const segmentStat = await stat(segmentPath)
244 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
246 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
248 return canUpload !== true
250 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags })
254 private createFiles () {
255 for (let i = 0; i < this.allResolutions.length; i++) {
256 const resolution = this.allResolutions[i]
258 const file = new VideoFileModel({
264 videoStreamingPlaylistId: this.streamingPlaylist.id
267 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
268 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags }))
272 private async prepareDirectories () {
273 const outPath = getHLSDirectory(this.videoLive.Video)
274 await ensureDir(outPath)
276 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
278 if (this.videoLive.saveReplay === true) {
279 await ensureDir(replayDirectory)
285 private isDurationConstraintValid (streamingStartTime: number) {
286 const maxDuration = CONFIG.LIVE.MAX_DURATION
288 if (maxDuration < 0) return true
290 const now = new Date().getTime()
291 const max = streamingStartTime + maxDuration
296 private processSegments (hlsVideoPath: string, segmentPaths: string[]) {
297 Bluebird.mapSeries(segmentPaths, async previousSegment => {
298 // Add sha hash of previous segments, because ffmpeg should have finished generating them
299 await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
301 if (this.saveReplay) {
302 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
304 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags }))
307 private hasClientSocketInBadHealth (sessionId: string) {
308 const rtmpSession = this.context.sessions.get(sessionId)
311 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags)
315 for (const playerSessionId of rtmpSession.players) {
316 const playerSession = this.context.sessions.get(playerSessionId)
318 if (!playerSession) {
319 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags)
323 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
331 private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
332 const segmentName = basename(segmentPath)
333 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, buildConcatenatedName(segmentName))
336 const data = await readFile(segmentPath)
338 await appendFile(dest, data)
340 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags })
345 // ---------------------------------------------------------------------------