]>
Commit | Line | Data |
---|---|---|
8ebf2a5d | 1 | |
41fb13c3 C |
2 | import { mapSeries } from 'bluebird' |
3 | import { FSWatcher, watch } from 'chokidar' | |
8ebf2a5d C |
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' | |
c729caf6 | 8 | import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg' |
8ebf2a5d C |
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' | |
4ec52d04 | 14 | import { getLiveDirectory, getLiveReplayBaseDirectory } from '../../paths' |
c729caf6 | 15 | import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles' |
8ebf2a5d | 16 | import { isAbleToUploadVideo } from '../../user' |
8ebf2a5d C |
17 | import { LiveQuotaStore } from '../live-quota-store' |
18 | import { LiveSegmentShaStore } from '../live-segment-sha-store' | |
19 | import { buildConcatenatedName } from '../live-utils' | |
20 | ||
21 | import memoizee = require('memoizee') | |
22 | ||
23 | interface MuxingSessionEvents { | |
24 | 'master-playlist-created': ({ videoId: number }) => void | |
25 | ||
26 | 'bad-socket-health': ({ videoId: number }) => void | |
27 | 'duration-exceeded': ({ videoId: number }) => void | |
28 | 'quota-exceeded': ({ videoId: number }) => void | |
29 | ||
30 | 'ffmpeg-end': ({ videoId: number }) => void | |
26e3e98f | 31 | 'ffmpeg-error': ({ videoId: string }) => void |
8ebf2a5d C |
32 | |
33 | 'after-cleanup': ({ videoId: number }) => void | |
34 | } | |
35 | ||
36 | declare interface MuxingSession { | |
37 | on<U extends keyof MuxingSessionEvents>( | |
38 | event: U, listener: MuxingSessionEvents[U] | |
39 | ): this | |
40 | ||
41 | emit<U extends keyof MuxingSessionEvents>( | |
42 | event: U, ...args: Parameters<MuxingSessionEvents[U]> | |
43 | ): boolean | |
44 | } | |
45 | ||
46 | class MuxingSession extends EventEmitter { | |
47 | ||
48 | private ffmpegCommand: FfmpegCommand | |
49 | ||
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 | |
df1db951 | 55 | private readonly inputUrl: string |
8ebf2a5d C |
56 | private readonly fps: number |
57 | private readonly allResolutions: number[] | |
58 | ||
679c12e6 C |
59 | private readonly bitrate: number |
60 | private readonly ratio: number | |
61 | ||
8ebf2a5d C |
62 | private readonly videoId: number |
63 | private readonly videoUUID: string | |
64 | private readonly saveReplay: boolean | |
65 | ||
4ec52d04 C |
66 | private readonly outDirectory: string |
67 | private readonly replayDirectory: string | |
68 | ||
8ebf2a5d C |
69 | private readonly lTags: LoggerTagsFn |
70 | ||
71 | private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {} | |
72 | ||
41fb13c3 C |
73 | private tsWatcher: FSWatcher |
74 | private masterWatcher: FSWatcher | |
8ebf2a5d C |
75 | |
76 | private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => { | |
77 | return isAbleToUploadVideo(userId, 1000) | |
78 | }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD }) | |
79 | ||
80 | private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => { | |
81 | return this.hasClientSocketInBadHealth(sessionId) | |
82 | }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH }) | |
83 | ||
84 | constructor (options: { | |
85 | context: any | |
86 | user: MUserId | |
87 | sessionId: string | |
88 | videoLive: MVideoLiveVideo | |
89 | streamingPlaylist: MStreamingPlaylistVideo | |
df1db951 | 90 | inputUrl: string |
8ebf2a5d | 91 | fps: number |
c826f34a | 92 | bitrate: number |
679c12e6 | 93 | ratio: number |
8ebf2a5d C |
94 | allResolutions: number[] |
95 | }) { | |
96 | super() | |
97 | ||
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 | |
df1db951 | 103 | this.inputUrl = options.inputUrl |
8ebf2a5d | 104 | this.fps = options.fps |
679c12e6 | 105 | |
c826f34a | 106 | this.bitrate = options.bitrate |
41085b15 | 107 | this.ratio = options.ratio |
679c12e6 | 108 | |
8ebf2a5d C |
109 | this.allResolutions = options.allResolutions |
110 | ||
111 | this.videoId = this.videoLive.Video.id | |
112 | this.videoUUID = this.videoLive.Video.uuid | |
113 | ||
114 | this.saveReplay = this.videoLive.saveReplay | |
115 | ||
4ec52d04 C |
116 | this.outDirectory = getLiveDirectory(this.videoLive.Video) |
117 | this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString()) | |
118 | ||
8ebf2a5d C |
119 | this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID) |
120 | } | |
121 | ||
122 | async runMuxing () { | |
123 | this.createFiles() | |
124 | ||
4ec52d04 | 125 | await this.prepareDirectories() |
8ebf2a5d C |
126 | |
127 | this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED | |
128 | ? await getLiveTranscodingCommand({ | |
df1db951 | 129 | inputUrl: this.inputUrl, |
764b1a14 | 130 | |
4ec52d04 | 131 | outPath: this.outDirectory, |
764b1a14 C |
132 | masterPlaylistName: this.streamingPlaylist.playlistFilename, |
133 | ||
f443a746 C |
134 | latencyMode: this.videoLive.latencyMode, |
135 | ||
8ebf2a5d C |
136 | resolutions: this.allResolutions, |
137 | fps: this.fps, | |
c826f34a | 138 | bitrate: this.bitrate, |
679c12e6 | 139 | ratio: this.ratio, |
c826f34a | 140 | |
8ebf2a5d C |
141 | availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), |
142 | profile: CONFIG.LIVE.TRANSCODING.PROFILE | |
143 | }) | |
f443a746 C |
144 | : getLiveMuxingCommand({ |
145 | inputUrl: this.inputUrl, | |
4ec52d04 | 146 | outPath: this.outDirectory, |
f443a746 C |
147 | masterPlaylistName: this.streamingPlaylist.playlistFilename, |
148 | latencyMode: this.videoLive.latencyMode | |
149 | }) | |
8ebf2a5d | 150 | |
4c6757f2 | 151 | logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags()) |
8ebf2a5d | 152 | |
4ec52d04 C |
153 | this.watchTSFiles(this.outDirectory) |
154 | this.watchMasterFile(this.outDirectory) | |
8ebf2a5d | 155 | |
4c6757f2 C |
156 | let ffmpegShellCommand: string |
157 | this.ffmpegCommand.on('start', cmdline => { | |
158 | ffmpegShellCommand = cmdline | |
159 | ||
160 | logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() }) | |
161 | }) | |
162 | ||
8ebf2a5d | 163 | this.ffmpegCommand.on('error', (err, stdout, stderr) => { |
4ec52d04 | 164 | this.onFFmpegError({ err, stdout, stderr, outPath: this.outDirectory, ffmpegShellCommand }) |
8ebf2a5d C |
165 | }) |
166 | ||
26e3e98f C |
167 | this.ffmpegCommand.on('end', () => { |
168 | this.emit('ffmpeg-end', ({ videoId: this.videoId })) | |
169 | ||
170 | this.onFFmpegEnded(this.outDirectory) | |
171 | }) | |
8ebf2a5d C |
172 | |
173 | this.ffmpegCommand.run() | |
174 | } | |
175 | ||
176 | abort () { | |
609a4442 | 177 | if (!this.ffmpegCommand) return |
8ebf2a5d C |
178 | |
179 | this.ffmpegCommand.kill('SIGINT') | |
609a4442 C |
180 | } |
181 | ||
182 | destroy () { | |
183 | this.removeAllListeners() | |
184 | this.isAbleToUploadVideoWithCache.clear() | |
185 | this.hasClientSocketInBadHealthWithCache.clear() | |
8ebf2a5d C |
186 | } |
187 | ||
4c6757f2 C |
188 | private onFFmpegError (options: { |
189 | err: any | |
190 | stdout: string | |
191 | stderr: string | |
192 | outPath: string | |
193 | ffmpegShellCommand: string | |
194 | }) { | |
195 | const { err, stdout, stderr, outPath, ffmpegShellCommand } = options | |
196 | ||
8ebf2a5d C |
197 | this.onFFmpegEnded(outPath) |
198 | ||
199 | // Don't care that we killed the ffmpeg process | |
200 | if (err?.message?.includes('Exiting normally')) return | |
201 | ||
4c6757f2 | 202 | logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() }) |
8ebf2a5d | 203 | |
26e3e98f | 204 | this.emit('ffmpeg-error', ({ videoId: this.videoId })) |
8ebf2a5d C |
205 | } |
206 | ||
207 | private onFFmpegEnded (outPath: string) { | |
4c6757f2 | 208 | logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags()) |
8ebf2a5d C |
209 | |
210 | setTimeout(() => { | |
211 | // Wait latest segments generation, and close watchers | |
212 | ||
213 | Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ]) | |
214 | .then(() => { | |
215 | // Process remaining segments hash | |
216 | for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) { | |
217 | this.processSegments(outPath, this.segmentsToProcessPerPlaylist[key]) | |
218 | } | |
219 | }) | |
220 | .catch(err => { | |
221 | logger.error( | |
222 | 'Cannot close watchers of %s or process remaining hash segments.', outPath, | |
4c6757f2 | 223 | { err, ...this.lTags() } |
8ebf2a5d C |
224 | ) |
225 | }) | |
226 | ||
227 | this.emit('after-cleanup', { videoId: this.videoId }) | |
228 | }, 1000) | |
229 | } | |
230 | ||
231 | private watchMasterFile (outPath: string) { | |
41fb13c3 | 232 | this.masterWatcher = watch(outPath + '/' + this.streamingPlaylist.playlistFilename) |
8ebf2a5d | 233 | |
98ab5dc8 | 234 | this.masterWatcher.on('add', () => { |
8ebf2a5d C |
235 | this.emit('master-playlist-created', { videoId: this.videoId }) |
236 | ||
237 | this.masterWatcher.close() | |
4c6757f2 | 238 | .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags() })) |
8ebf2a5d C |
239 | }) |
240 | } | |
241 | ||
242 | private watchTSFiles (outPath: string) { | |
243 | const startStreamDateTime = new Date().getTime() | |
244 | ||
41fb13c3 | 245 | this.tsWatcher = watch(outPath + '/*.ts') |
8ebf2a5d C |
246 | |
247 | const playlistIdMatcher = /^([\d+])-/ | |
248 | ||
75b7117f | 249 | const addHandler = async (segmentPath: string) => { |
4c6757f2 | 250 | logger.debug('Live add handler of %s.', segmentPath, this.lTags()) |
8ebf2a5d C |
251 | |
252 | const playlistId = basename(segmentPath).match(playlistIdMatcher)[0] | |
253 | ||
254 | const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || [] | |
255 | this.processSegments(outPath, segmentsToProcess) | |
256 | ||
257 | this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ] | |
258 | ||
259 | if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) { | |
260 | this.emit('bad-socket-health', { videoId: this.videoId }) | |
261 | return | |
262 | } | |
263 | ||
264 | // Duration constraint check | |
265 | if (this.isDurationConstraintValid(startStreamDateTime) !== true) { | |
266 | this.emit('duration-exceeded', { videoId: this.videoId }) | |
267 | return | |
268 | } | |
269 | ||
270 | // Check user quota if the user enabled replay saving | |
271 | if (await this.isQuotaExceeded(segmentPath) === true) { | |
272 | this.emit('quota-exceeded', { videoId: this.videoId }) | |
273 | } | |
274 | } | |
275 | ||
276 | const deleteHandler = segmentPath => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath) | |
277 | ||
278 | this.tsWatcher.on('add', p => addHandler(p)) | |
279 | this.tsWatcher.on('unlink', p => deleteHandler(p)) | |
280 | } | |
281 | ||
282 | private async isQuotaExceeded (segmentPath: string) { | |
283 | if (this.saveReplay !== true) return false | |
284 | ||
285 | try { | |
286 | const segmentStat = await stat(segmentPath) | |
287 | ||
288 | LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size) | |
289 | ||
290 | const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id) | |
291 | ||
292 | return canUpload !== true | |
293 | } catch (err) { | |
4c6757f2 | 294 | logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() }) |
8ebf2a5d C |
295 | } |
296 | } | |
297 | ||
298 | private createFiles () { | |
299 | for (let i = 0; i < this.allResolutions.length; i++) { | |
300 | const resolution = this.allResolutions[i] | |
301 | ||
302 | const file = new VideoFileModel({ | |
303 | resolution, | |
304 | size: -1, | |
305 | extname: '.ts', | |
306 | infoHash: null, | |
307 | fps: this.fps, | |
308 | videoStreamingPlaylistId: this.streamingPlaylist.id | |
309 | }) | |
310 | ||
311 | VideoFileModel.customUpsert(file, 'streaming-playlist', null) | |
4c6757f2 | 312 | .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() })) |
8ebf2a5d C |
313 | } |
314 | } | |
315 | ||
316 | private async prepareDirectories () { | |
4ec52d04 | 317 | await ensureDir(this.outDirectory) |
8ebf2a5d C |
318 | |
319 | if (this.videoLive.saveReplay === true) { | |
4ec52d04 | 320 | await ensureDir(this.replayDirectory) |
8ebf2a5d | 321 | } |
8ebf2a5d C |
322 | } |
323 | ||
324 | private isDurationConstraintValid (streamingStartTime: number) { | |
325 | const maxDuration = CONFIG.LIVE.MAX_DURATION | |
326 | // No limit | |
327 | if (maxDuration < 0) return true | |
328 | ||
329 | const now = new Date().getTime() | |
330 | const max = streamingStartTime + maxDuration | |
331 | ||
332 | return now <= max | |
333 | } | |
334 | ||
335 | private processSegments (hlsVideoPath: string, segmentPaths: string[]) { | |
41fb13c3 | 336 | mapSeries(segmentPaths, async previousSegment => { |
8ebf2a5d C |
337 | // Add sha hash of previous segments, because ffmpeg should have finished generating them |
338 | await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment) | |
339 | ||
340 | if (this.saveReplay) { | |
341 | await this.addSegmentToReplay(hlsVideoPath, previousSegment) | |
342 | } | |
4c6757f2 | 343 | }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags() })) |
8ebf2a5d C |
344 | } |
345 | ||
346 | private hasClientSocketInBadHealth (sessionId: string) { | |
347 | const rtmpSession = this.context.sessions.get(sessionId) | |
348 | ||
349 | if (!rtmpSession) { | |
4c6757f2 | 350 | logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags()) |
8ebf2a5d C |
351 | return |
352 | } | |
353 | ||
354 | for (const playerSessionId of rtmpSession.players) { | |
355 | const playerSession = this.context.sessions.get(playerSessionId) | |
356 | ||
357 | if (!playerSession) { | |
4c6757f2 | 358 | logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags()) |
8ebf2a5d C |
359 | continue |
360 | } | |
361 | ||
362 | if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) { | |
363 | return true | |
364 | } | |
365 | } | |
366 | ||
367 | return false | |
368 | } | |
369 | ||
370 | private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) { | |
371 | const segmentName = basename(segmentPath) | |
4ec52d04 | 372 | const dest = join(this.replayDirectory, buildConcatenatedName(segmentName)) |
8ebf2a5d C |
373 | |
374 | try { | |
375 | const data = await readFile(segmentPath) | |
376 | ||
377 | await appendFile(dest, data) | |
378 | } catch (err) { | |
4c6757f2 | 379 | logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() }) |
8ebf2a5d C |
380 | } |
381 | } | |
382 | } | |
383 | ||
384 | // --------------------------------------------------------------------------- | |
385 | ||
386 | export { | |
387 | MuxingSession | |
388 | } |