]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/shared/muxing-session.ts
Wait master playlist generation
[github/Chocobozzz/PeerTube.git] / server / lib / live / shared / muxing-session.ts
1 import { mapSeries } from 'bluebird'
2 import { FSWatcher, watch } from 'chokidar'
3 import { EventEmitter } from 'events'
4 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
5 import PQueue from 'p-queue'
6 import { basename, join } from 'path'
7 import { computeOutputFPS } from '@server/helpers/ffmpeg'
8 import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
9 import { CONFIG } from '@server/initializers/config'
10 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
11 import {
12 removeHLSFileObjectStorageByPath,
13 storeHLSFileFromContent,
14 storeHLSFileFromFilename,
15 storeHLSFileFromPath
16 } from '@server/lib/object-storage'
17 import { VideoFileModel } from '@server/models/video/video-file'
18 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
19 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
20 import { wait } from '@shared/core-utils'
21 import { VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
22 import {
23 generateHLSMasterPlaylistFilename,
24 generateHlsSha256SegmentsFilename,
25 getLiveDirectory,
26 getLiveReplayBaseDirectory
27 } from '../../paths'
28 import { isAbleToUploadVideo } from '../../user'
29 import { LiveQuotaStore } from '../live-quota-store'
30 import { LiveSegmentShaStore } from '../live-segment-sha-store'
31 import { buildConcatenatedName, getLiveSegmentTime } from '../live-utils'
32 import { AbstractTranscodingWrapper, FFmpegTranscodingWrapper, RemoteTranscodingWrapper } from './transcoding-wrapper'
33
34 import memoizee = require('memoizee')
35 interface MuxingSessionEvents {
36 'live-ready': (options: { videoUUID: string }) => void
37
38 'bad-socket-health': (options: { videoUUID: string }) => void
39 'duration-exceeded': (options: { videoUUID: string }) => void
40 'quota-exceeded': (options: { videoUUID: string }) => void
41
42 'transcoding-end': (options: { videoUUID: string }) => void
43 'transcoding-error': (options: { videoUUID: string }) => void
44
45 'after-cleanup': (options: { videoUUID: string }) => void
46 }
47
48 declare interface MuxingSession {
49 on<U extends keyof MuxingSessionEvents>(
50 event: U, listener: MuxingSessionEvents[U]
51 ): this
52
53 emit<U extends keyof MuxingSessionEvents>(
54 event: U, ...args: Parameters<MuxingSessionEvents[U]>
55 ): boolean
56 }
57
58 class MuxingSession extends EventEmitter {
59
60 private transcodingWrapper: AbstractTranscodingWrapper
61
62 private readonly context: any
63 private readonly user: MUserId
64 private readonly sessionId: string
65 private readonly videoLive: MVideoLiveVideo
66
67 private readonly inputLocalUrl: string
68 private readonly inputPublicUrl: string
69
70 private readonly fps: number
71 private readonly allResolutions: number[]
72
73 private readonly bitrate: number
74 private readonly ratio: number
75
76 private readonly hasAudio: boolean
77
78 private readonly videoUUID: string
79 private readonly saveReplay: boolean
80
81 private readonly outDirectory: string
82 private readonly replayDirectory: string
83
84 private readonly lTags: LoggerTagsFn
85
86 // Path -> Queue
87 private readonly objectStorageSendQueues = new Map<string, PQueue>()
88
89 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
90
91 private streamingPlaylist: MStreamingPlaylistVideo
92 private liveSegmentShaStore: LiveSegmentShaStore
93
94 private filesWatcher: FSWatcher
95
96 private masterPlaylistCreated = false
97 private liveReady = false
98
99 private aborted = false
100
101 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
102 return isAbleToUploadVideo(userId, 1000)
103 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
104
105 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
106 return this.hasClientSocketInBadHealth(sessionId)
107 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
108
109 constructor (options: {
110 context: any
111 user: MUserId
112 sessionId: string
113 videoLive: MVideoLiveVideo
114
115 inputLocalUrl: string
116 inputPublicUrl: string
117
118 fps: number
119 bitrate: number
120 ratio: number
121 allResolutions: number[]
122 hasAudio: boolean
123 }) {
124 super()
125
126 this.context = options.context
127 this.user = options.user
128 this.sessionId = options.sessionId
129 this.videoLive = options.videoLive
130
131 this.inputLocalUrl = options.inputLocalUrl
132 this.inputPublicUrl = options.inputPublicUrl
133
134 this.fps = options.fps
135
136 this.bitrate = options.bitrate
137 this.ratio = options.ratio
138
139 this.hasAudio = options.hasAudio
140
141 this.allResolutions = options.allResolutions
142
143 this.videoUUID = this.videoLive.Video.uuid
144
145 this.saveReplay = this.videoLive.saveReplay
146
147 this.outDirectory = getLiveDirectory(this.videoLive.Video)
148 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
149
150 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
151 }
152
153 async runMuxing () {
154 this.streamingPlaylist = await this.createLivePlaylist()
155
156 this.createLiveShaStore()
157 this.createFiles()
158
159 await this.prepareDirectories()
160
161 this.transcodingWrapper = this.buildTranscodingWrapper()
162
163 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
164 this.transcodingWrapper.on('error', () => this.onTranscodingError())
165
166 await this.transcodingWrapper.run()
167
168 this.filesWatcher = watch(this.outDirectory, { depth: 0 })
169
170 this.watchMasterFile()
171 this.watchTSFiles()
172 }
173
174 abort () {
175 if (!this.transcodingWrapper) return
176
177 this.aborted = true
178 this.transcodingWrapper.abort()
179 }
180
181 destroy () {
182 this.removeAllListeners()
183 this.isAbleToUploadVideoWithCache.clear()
184 this.hasClientSocketInBadHealthWithCache.clear()
185 }
186
187 private watchMasterFile () {
188 this.filesWatcher.on('add', async path => {
189 if (path !== join(this.outDirectory, this.streamingPlaylist.playlistFilename)) return
190 if (this.masterPlaylistCreated === true) return
191
192 try {
193 let masterPlaylistContent: string
194
195 do {
196 masterPlaylistContent = await readFile(path, 'utf8')
197
198 if (!masterPlaylistContent) {
199 await wait(250)
200 logger.debug('Waiting for master playlist generation for ' + this.videoUUID, this.lTags())
201 }
202 } while (!masterPlaylistContent) // Not generated yet
203
204 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
205 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
206
207 this.streamingPlaylist.playlistUrl = url
208 }
209
210 this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions)
211
212 await this.streamingPlaylist.save()
213 } catch (err) {
214 logger.error('Cannot update streaming playlist.', { err, ...this.lTags() })
215 }
216
217 this.masterPlaylistCreated = true
218
219 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
220 })
221 }
222
223 private watchTSFiles () {
224 const startStreamDateTime = new Date().getTime()
225
226 const addHandler = async (segmentPath: string) => {
227 if (segmentPath.endsWith('.ts') !== true) return
228
229 logger.debug('Live add handler of TS file %s.', segmentPath, this.lTags())
230
231 const playlistId = this.getPlaylistIdFromTS(segmentPath)
232
233 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
234 this.processSegments(segmentsToProcess)
235
236 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
237
238 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
239 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
240 return
241 }
242
243 // Duration constraint check
244 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
245 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
246 return
247 }
248
249 // Check user quota if the user enabled replay saving
250 if (await this.isQuotaExceeded(segmentPath) === true) {
251 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
252 }
253 }
254
255 const deleteHandler = async (segmentPath: string) => {
256 if (segmentPath.endsWith('.ts') !== true) return
257
258 logger.debug('Live delete handler of TS file %s.', segmentPath, this.lTags())
259
260 try {
261 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
262 } catch (err) {
263 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
264 }
265
266 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
267 try {
268 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
269 } catch (err) {
270 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
271 }
272 }
273 }
274
275 this.filesWatcher.on('add', p => addHandler(p))
276 this.filesWatcher.on('unlink', p => deleteHandler(p))
277 }
278
279 private async isQuotaExceeded (segmentPath: string) {
280 if (this.saveReplay !== true) return false
281 if (this.aborted) return false
282
283 try {
284 const segmentStat = await stat(segmentPath)
285
286 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
287
288 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
289
290 return canUpload !== true
291 } catch (err) {
292 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
293 }
294 }
295
296 private createFiles () {
297 for (let i = 0; i < this.allResolutions.length; i++) {
298 const resolution = this.allResolutions[i]
299
300 const file = new VideoFileModel({
301 resolution,
302 size: -1,
303 extname: '.ts',
304 infoHash: null,
305 fps: this.fps,
306 storage: this.streamingPlaylist.storage,
307 videoStreamingPlaylistId: this.streamingPlaylist.id
308 })
309
310 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
311 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
312 }
313 }
314
315 private async prepareDirectories () {
316 await ensureDir(this.outDirectory)
317
318 if (this.videoLive.saveReplay === true) {
319 await ensureDir(this.replayDirectory)
320 }
321 }
322
323 private isDurationConstraintValid (streamingStartTime: number) {
324 const maxDuration = CONFIG.LIVE.MAX_DURATION
325 // No limit
326 if (maxDuration < 0) return true
327
328 const now = new Date().getTime()
329 const max = streamingStartTime + maxDuration
330
331 return now <= max
332 }
333
334 private processSegments (segmentPaths: string[]) {
335 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
336 .catch(err => {
337 if (this.aborted) return
338
339 logger.error('Cannot process segments', { err, ...this.lTags() })
340 })
341 }
342
343 private async processSegment (segmentPath: string) {
344 // Add sha hash of previous segments, because ffmpeg should have finished generating them
345 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
346
347 if (this.saveReplay) {
348 await this.addSegmentToReplay(segmentPath)
349 }
350
351 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
352 try {
353 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
354
355 await this.processM3U8ToObjectStorage(segmentPath)
356 } catch (err) {
357 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
358 }
359 }
360
361 // Master playlist and segment JSON file are created, live is ready
362 if (this.masterPlaylistCreated && !this.liveReady) {
363 this.liveReady = true
364
365 this.emit('live-ready', { videoUUID: this.videoUUID })
366 }
367 }
368
369 private async processM3U8ToObjectStorage (segmentPath: string) {
370 const m3u8Path = join(this.outDirectory, this.getPlaylistNameFromTS(segmentPath))
371
372 logger.debug('Process M3U8 file %s.', m3u8Path, this.lTags())
373
374 const segmentName = basename(segmentPath)
375
376 const playlistContent = await readFile(m3u8Path, 'utf-8')
377 // Remove new chunk references, that will be processed later
378 const filteredPlaylistContent = playlistContent.substring(0, playlistContent.lastIndexOf(segmentName) + segmentName.length) + '\n'
379
380 try {
381 if (!this.objectStorageSendQueues.has(m3u8Path)) {
382 this.objectStorageSendQueues.set(m3u8Path, new PQueue({ concurrency: 1 }))
383 }
384
385 const queue = this.objectStorageSendQueues.get(m3u8Path)
386 await queue.add(() => storeHLSFileFromContent(this.streamingPlaylist, m3u8Path, filteredPlaylistContent))
387 } catch (err) {
388 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
389 }
390 }
391
392 private onTranscodingError () {
393 this.emit('transcoding-error', ({ videoUUID: this.videoUUID }))
394 }
395
396 private onTranscodedEnded () {
397 this.emit('transcoding-end', ({ videoUUID: this.videoUUID }))
398
399 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputLocalUrl, this.lTags())
400
401 setTimeout(() => {
402 // Wait latest segments generation, and close watchers
403
404 const promise = this.filesWatcher?.close() || Promise.resolve()
405 promise
406 .then(() => {
407 // Process remaining segments hash
408 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
409 this.processSegments(this.segmentsToProcessPerPlaylist[key])
410 }
411 })
412 .catch(err => {
413 logger.error(
414 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
415 { err, ...this.lTags() }
416 )
417 })
418
419 this.emit('after-cleanup', { videoUUID: this.videoUUID })
420 }, 1000)
421 }
422
423 private hasClientSocketInBadHealth (sessionId: string) {
424 const rtmpSession = this.context.sessions.get(sessionId)
425
426 if (!rtmpSession) {
427 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
428 return
429 }
430
431 for (const playerSessionId of rtmpSession.players) {
432 const playerSession = this.context.sessions.get(playerSessionId)
433
434 if (!playerSession) {
435 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
436 continue
437 }
438
439 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
440 return true
441 }
442 }
443
444 return false
445 }
446
447 private async addSegmentToReplay (segmentPath: string) {
448 const segmentName = basename(segmentPath)
449 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
450
451 try {
452 const data = await readFile(segmentPath)
453
454 await appendFile(dest, data)
455 } catch (err) {
456 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
457 }
458 }
459
460 private async createLivePlaylist (): Promise<MStreamingPlaylistVideo> {
461 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(this.videoLive.Video)
462
463 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
464 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
465
466 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
467 playlist.type = VideoStreamingPlaylistType.HLS
468
469 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
470 ? VideoStorage.OBJECT_STORAGE
471 : VideoStorage.FILE_SYSTEM
472
473 return playlist.save()
474 }
475
476 private createLiveShaStore () {
477 this.liveSegmentShaStore = new LiveSegmentShaStore({
478 videoUUID: this.videoLive.Video.uuid,
479 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
480 streamingPlaylist: this.streamingPlaylist,
481 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
482 })
483 }
484
485 private buildTranscodingWrapper () {
486 const options = {
487 streamingPlaylist: this.streamingPlaylist,
488 videoLive: this.videoLive,
489
490 lTags: this.lTags,
491
492 inputLocalUrl: this.inputLocalUrl,
493 inputPublicUrl: this.inputPublicUrl,
494
495 toTranscode: this.allResolutions.map(resolution => ({
496 resolution,
497 fps: computeOutputFPS({ inputFPS: this.fps, resolution })
498 })),
499
500 fps: this.fps,
501 bitrate: this.bitrate,
502 ratio: this.ratio,
503 hasAudio: this.hasAudio,
504
505 segmentListSize: VIDEO_LIVE.SEGMENTS_LIST_SIZE,
506 segmentDuration: getLiveSegmentTime(this.videoLive.latencyMode),
507
508 outDirectory: this.outDirectory
509 }
510
511 return CONFIG.LIVE.TRANSCODING.ENABLED && CONFIG.LIVE.TRANSCODING.REMOTE_RUNNERS.ENABLED
512 ? new RemoteTranscodingWrapper(options)
513 : new FFmpegTranscodingWrapper(options)
514 }
515
516 private getPlaylistIdFromTS (segmentPath: string) {
517 const playlistIdMatcher = /^([\d+])-/
518
519 return basename(segmentPath).match(playlistIdMatcher)[1]
520 }
521
522 private getPlaylistNameFromTS (segmentPath: string) {
523 return `${this.getPlaylistIdFromTS(segmentPath)}.m3u8`
524 }
525 }
526
527 // ---------------------------------------------------------------------------
528
529 export {
530 MuxingSession
531 }