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, getLiveReplayBaseDirectory } 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': ({ videoId: 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 outDirectory: string
67 private readonly replayDirectory: string
69 private readonly lTags: LoggerTagsFn
71 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
73 private tsWatcher: FSWatcher
74 private masterWatcher: FSWatcher
76 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
77 return isAbleToUploadVideo(userId, 1000)
78 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
80 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
81 return this.hasClientSocketInBadHealth(sessionId)
82 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
84 constructor (options: {
88 videoLive: MVideoLiveVideo
89 streamingPlaylist: MStreamingPlaylistVideo
94 allResolutions: number[]
98 this.context = options.context
99 this.user = options.user
100 this.sessionId = options.sessionId
101 this.videoLive = options.videoLive
102 this.streamingPlaylist = options.streamingPlaylist
103 this.inputUrl = options.inputUrl
104 this.fps = options.fps
106 this.bitrate = options.bitrate
107 this.ratio = options.ratio
109 this.allResolutions = options.allResolutions
111 this.videoId = this.videoLive.Video.id
112 this.videoUUID = this.videoLive.Video.uuid
114 this.saveReplay = this.videoLive.saveReplay
116 this.outDirectory = getLiveDirectory(this.videoLive.Video)
117 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
119 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
125 await this.prepareDirectories()
127 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
128 ? await getLiveTranscodingCommand({
129 inputUrl: this.inputUrl,
131 outPath: this.outDirectory,
132 masterPlaylistName: this.streamingPlaylist.playlistFilename,
134 latencyMode: this.videoLive.latencyMode,
136 resolutions: this.allResolutions,
138 bitrate: this.bitrate,
141 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
142 profile: CONFIG.LIVE.TRANSCODING.PROFILE
144 : getLiveMuxingCommand({
145 inputUrl: this.inputUrl,
146 outPath: this.outDirectory,
147 masterPlaylistName: this.streamingPlaylist.playlistFilename,
148 latencyMode: this.videoLive.latencyMode
151 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
154 this.watchMasterFile()
156 let ffmpegShellCommand: string
157 this.ffmpegCommand.on('start', cmdline => {
158 ffmpegShellCommand = cmdline
160 logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() })
163 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
164 this.onFFmpegError({ err, stdout, stderr, ffmpegShellCommand })
167 this.ffmpegCommand.on('end', () => {
168 this.emit('ffmpeg-end', ({ videoId: this.videoId }))
173 this.ffmpegCommand.run()
177 if (!this.ffmpegCommand) return
179 this.ffmpegCommand.kill('SIGINT')
183 this.removeAllListeners()
184 this.isAbleToUploadVideoWithCache.clear()
185 this.hasClientSocketInBadHealthWithCache.clear()
188 private onFFmpegError (options: {
192 ffmpegShellCommand: string
194 const { err, stdout, stderr, ffmpegShellCommand } = options
198 // Don't care that we killed the ffmpeg process
199 if (err?.message?.includes('Exiting normally')) return
201 logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
203 this.emit('ffmpeg-error', ({ videoId: this.videoId }))
206 private onFFmpegEnded () {
207 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
210 // Wait latest segments generation, and close watchers
212 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ])
214 // Process remaining segments hash
215 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
216 this.processSegments(this.segmentsToProcessPerPlaylist[key])
221 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
222 { err, ...this.lTags() }
226 this.emit('after-cleanup', { videoId: this.videoId })
230 private watchMasterFile () {
231 this.masterWatcher = watch(this.outDirectory + '/' + this.streamingPlaylist.playlistFilename)
233 this.masterWatcher.on('add', () => {
234 this.emit('master-playlist-created', { videoId: this.videoId })
236 this.masterWatcher.close()
237 .catch(err => logger.error('Cannot close master watcher of %s.', this.outDirectory, { err, ...this.lTags() }))
241 private watchTSFiles () {
242 const startStreamDateTime = new Date().getTime()
244 this.tsWatcher = watch(this.outDirectory + '/*.ts')
246 const playlistIdMatcher = /^([\d+])-/
248 const addHandler = async (segmentPath: string) => {
249 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
251 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
253 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
254 this.processSegments(segmentsToProcess)
256 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
258 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
259 this.emit('bad-socket-health', { videoId: this.videoId })
263 // Duration constraint check
264 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
265 this.emit('duration-exceeded', { videoId: this.videoId })
269 // Check user quota if the user enabled replay saving
270 if (await this.isQuotaExceeded(segmentPath) === true) {
271 this.emit('quota-exceeded', { videoId: this.videoId })
275 const deleteHandler = (segmentPath: string) => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath)
277 this.tsWatcher.on('add', p => addHandler(p))
278 this.tsWatcher.on('unlink', p => deleteHandler(p))
281 private async isQuotaExceeded (segmentPath: string) {
282 if (this.saveReplay !== true) return false
285 const segmentStat = await stat(segmentPath)
287 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
289 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
291 return canUpload !== true
293 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
297 private createFiles () {
298 for (let i = 0; i < this.allResolutions.length; i++) {
299 const resolution = this.allResolutions[i]
301 const file = new VideoFileModel({
307 videoStreamingPlaylistId: this.streamingPlaylist.id
310 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
311 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
315 private async prepareDirectories () {
316 await ensureDir(this.outDirectory)
318 if (this.videoLive.saveReplay === true) {
319 await ensureDir(this.replayDirectory)
323 private isDurationConstraintValid (streamingStartTime: number) {
324 const maxDuration = CONFIG.LIVE.MAX_DURATION
326 if (maxDuration < 0) return true
328 const now = new Date().getTime()
329 const max = streamingStartTime + maxDuration
334 private processSegments (segmentPaths: string[]) {
335 mapSeries(segmentPaths, async previousSegment => {
336 // Add sha hash of previous segments, because ffmpeg should have finished generating them
337 await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
339 if (this.saveReplay) {
340 await this.addSegmentToReplay(previousSegment)
342 }).catch(err => logger.error('Cannot process segments', { err, ...this.lTags() }))
345 private hasClientSocketInBadHealth (sessionId: string) {
346 const rtmpSession = this.context.sessions.get(sessionId)
349 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
353 for (const playerSessionId of rtmpSession.players) {
354 const playerSession = this.context.sessions.get(playerSessionId)
356 if (!playerSession) {
357 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
361 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
369 private async addSegmentToReplay (segmentPath: string) {
370 const segmentName = basename(segmentPath)
371 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
374 const data = await readFile(segmentPath)
376 await appendFile(dest, data)
378 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
383 // ---------------------------------------------------------------------------