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