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