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