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