]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live/shared/muxing-session.ts
Wait master playlist generation
[github/Chocobozzz/PeerTube.git] / server / lib / live / shared / muxing-session.ts
CommitLineData
41fb13c3
C
1import { mapSeries } from 'bluebird'
2import { FSWatcher, watch } from 'chokidar'
0c9668f7 3import { EventEmitter } from 'events'
8ebf2a5d 4import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
b3ce3606 5import PQueue from 'p-queue'
8ebf2a5d 6import { basename, join } from 'path'
0c9668f7 7import { computeOutputFPS } from '@server/helpers/ffmpeg'
8ebf2a5d
C
8import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
9import { CONFIG } from '@server/initializers/config'
afb371d9 10import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
34023e12
C
11import {
12 removeHLSFileObjectStorageByPath,
13 storeHLSFileFromContent,
14 storeHLSFileFromFilename,
15 storeHLSFileFromPath
16} from '@server/lib/object-storage'
8ebf2a5d 17import { VideoFileModel } from '@server/models/video/video-file'
afb371d9 18import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
8ebf2a5d 19import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
30453cb5 20import { wait } from '@shared/core-utils'
afb371d9
C
21import { VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
22import {
23 generateHLSMasterPlaylistFilename,
24 generateHlsSha256SegmentsFilename,
25 getLiveDirectory,
26 getLiveReplayBaseDirectory
27} from '../../paths'
8ebf2a5d 28import { isAbleToUploadVideo } from '../../user'
8ebf2a5d
C
29import { LiveQuotaStore } from '../live-quota-store'
30import { LiveSegmentShaStore } from '../live-segment-sha-store'
0c9668f7
C
31import { buildConcatenatedName, getLiveSegmentTime } from '../live-utils'
32import { AbstractTranscodingWrapper, FFmpegTranscodingWrapper, RemoteTranscodingWrapper } from './transcoding-wrapper'
8ebf2a5d
C
33
34import memoizee = require('memoizee')
8ebf2a5d 35interface MuxingSessionEvents {
0c9668f7 36 'live-ready': (options: { videoUUID: string }) => void
8ebf2a5d 37
0c9668f7
C
38 'bad-socket-health': (options: { videoUUID: string }) => void
39 'duration-exceeded': (options: { videoUUID: string }) => void
40 'quota-exceeded': (options: { videoUUID: string }) => void
8ebf2a5d 41
0c9668f7
C
42 'transcoding-end': (options: { videoUUID: string }) => void
43 'transcoding-error': (options: { videoUUID: string }) => void
8ebf2a5d 44
0c9668f7 45 'after-cleanup': (options: { videoUUID: string }) => void
8ebf2a5d
C
46}
47
48declare 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
58class MuxingSession extends EventEmitter {
59
0c9668f7 60 private transcodingWrapper: AbstractTranscodingWrapper
8ebf2a5d
C
61
62 private readonly context: any
63 private readonly user: MUserId
64 private readonly sessionId: string
65 private readonly videoLive: MVideoLiveVideo
28705705
C
66
67 private readonly inputLocalUrl: string
68 private readonly inputPublicUrl: string
69
8ebf2a5d
C
70 private readonly fps: number
71 private readonly allResolutions: number[]
72
679c12e6
C
73 private readonly bitrate: number
74 private readonly ratio: number
75
1ce4256a
C
76 private readonly hasAudio: boolean
77
8ebf2a5d
C
78 private readonly videoUUID: string
79 private readonly saveReplay: boolean
80
4ec52d04
C
81 private readonly outDirectory: string
82 private readonly replayDirectory: string
83
8ebf2a5d
C
84 private readonly lTags: LoggerTagsFn
85
34023e12
C
86 // Path -> Queue
87 private readonly objectStorageSendQueues = new Map<string, PQueue>()
88
8ebf2a5d
C
89 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
90
afb371d9
C
91 private streamingPlaylist: MStreamingPlaylistVideo
92 private liveSegmentShaStore: LiveSegmentShaStore
93
3a0c2a77 94 private filesWatcher: FSWatcher
cfd57d2c
C
95
96 private masterPlaylistCreated = false
97 private liveReady = false
8ebf2a5d 98
39d117a4
C
99 private aborted = false
100
8ebf2a5d
C
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
28705705
C
114
115 inputLocalUrl: string
116 inputPublicUrl: string
117
8ebf2a5d 118 fps: number
c826f34a 119 bitrate: number
679c12e6 120 ratio: number
8ebf2a5d 121 allResolutions: number[]
1ce4256a 122 hasAudio: boolean
8ebf2a5d
C
123 }) {
124 super()
125
126 this.context = options.context
127 this.user = options.user
128 this.sessionId = options.sessionId
129 this.videoLive = options.videoLive
28705705
C
130
131 this.inputLocalUrl = options.inputLocalUrl
132 this.inputPublicUrl = options.inputPublicUrl
133
8ebf2a5d 134 this.fps = options.fps
679c12e6 135
c826f34a 136 this.bitrate = options.bitrate
41085b15 137 this.ratio = options.ratio
679c12e6 138
1ce4256a
C
139 this.hasAudio = options.hasAudio
140
8ebf2a5d
C
141 this.allResolutions = options.allResolutions
142
8ebf2a5d
C
143 this.videoUUID = this.videoLive.Video.uuid
144
145 this.saveReplay = this.videoLive.saveReplay
146
4ec52d04
C
147 this.outDirectory = getLiveDirectory(this.videoLive.Video)
148 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
149
8ebf2a5d
C
150 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
151 }
152
153 async runMuxing () {
afb371d9
C
154 this.streamingPlaylist = await this.createLivePlaylist()
155
156 this.createLiveShaStore()
8ebf2a5d
C
157 this.createFiles()
158
4ec52d04 159 await this.prepareDirectories()
8ebf2a5d 160
0c9668f7 161 this.transcodingWrapper = this.buildTranscodingWrapper()
764b1a14 162
0c9668f7
C
163 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
164 this.transcodingWrapper.on('error', () => this.onTranscodingError())
764b1a14 165
0c9668f7 166 await this.transcodingWrapper.run()
8ebf2a5d 167
3a0c2a77
C
168 this.filesWatcher = watch(this.outDirectory, { depth: 0 })
169
b34ee7fa 170 this.watchMasterFile()
cfd57d2c 171 this.watchTSFiles()
8ebf2a5d
C
172 }
173
174 abort () {
0c9668f7 175 if (!this.transcodingWrapper) return
8ebf2a5d 176
39d117a4 177 this.aborted = true
0c9668f7 178 this.transcodingWrapper.abort()
609a4442
C
179 }
180
181 destroy () {
182 this.removeAllListeners()
183 this.isAbleToUploadVideoWithCache.clear()
184 this.hasClientSocketInBadHealthWithCache.clear()
8ebf2a5d
C
185 }
186
b34ee7fa 187 private watchMasterFile () {
30453cb5 188 this.filesWatcher.on('add', async path => {
3a0c2a77
C
189 if (path !== join(this.outDirectory, this.streamingPlaylist.playlistFilename)) return
190 if (this.masterPlaylistCreated === true) return
8ebf2a5d 191
afb371d9 192 try {
30453cb5
C
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
72d606dc 203
afb371d9 204 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
cfd57d2c
C
205 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
206
207 this.streamingPlaylist.playlistUrl = url
cfd57d2c 208 }
afb371d9
C
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() })
cfd57d2c
C
215 }
216
217 this.masterPlaylistCreated = true
8ebf2a5d 218
0c9668f7 219 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
8ebf2a5d
C
220 })
221 }
222
b34ee7fa 223 private watchTSFiles () {
8ebf2a5d
C
224 const startStreamDateTime = new Date().getTime()
225
75b7117f 226 const addHandler = async (segmentPath: string) => {
3a0c2a77
C
227 if (segmentPath.endsWith('.ts') !== true) return
228
229 logger.debug('Live add handler of TS file %s.', segmentPath, this.lTags())
8ebf2a5d 230
34023e12 231 const playlistId = this.getPlaylistIdFromTS(segmentPath)
8ebf2a5d
C
232
233 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
b34ee7fa 234 this.processSegments(segmentsToProcess)
8ebf2a5d
C
235
236 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
237
238 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
0c9668f7 239 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
8ebf2a5d
C
240 return
241 }
242
243 // Duration constraint check
244 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
0c9668f7 245 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
8ebf2a5d
C
246 return
247 }
248
249 // Check user quota if the user enabled replay saving
250 if (await this.isQuotaExceeded(segmentPath) === true) {
0c9668f7 251 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
8ebf2a5d
C
252 }
253 }
254
cfd57d2c 255 const deleteHandler = async (segmentPath: string) => {
3a0c2a77
C
256 if (segmentPath.endsWith('.ts') !== true) return
257
258 logger.debug('Live delete handler of TS file %s.', segmentPath, this.lTags())
259
cfd57d2c
C
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 {
aa887096 268 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
cfd57d2c
C
269 } catch (err) {
270 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
271 }
272 }
273 }
8ebf2a5d 274
3a0c2a77
C
275 this.filesWatcher.on('add', p => addHandler(p))
276 this.filesWatcher.on('unlink', p => deleteHandler(p))
8ebf2a5d
C
277 }
278
279 private async isQuotaExceeded (segmentPath: string) {
280 if (this.saveReplay !== true) return false
29399256 281 if (this.aborted) return false
8ebf2a5d
C
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) {
4c6757f2 292 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
8ebf2a5d
C
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,
cfd57d2c 306 storage: this.streamingPlaylist.storage,
8ebf2a5d
C
307 videoStreamingPlaylistId: this.streamingPlaylist.id
308 })
309
310 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
4c6757f2 311 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
8ebf2a5d
C
312 }
313 }
314
315 private async prepareDirectories () {
4ec52d04 316 await ensureDir(this.outDirectory)
8ebf2a5d
C
317
318 if (this.videoLive.saveReplay === true) {
4ec52d04 319 await ensureDir(this.replayDirectory)
8ebf2a5d 320 }
8ebf2a5d
C
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
b34ee7fa 334 private processSegments (segmentPaths: string[]) {
cfd57d2c
C
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 }
8ebf2a5d 342
cfd57d2c
C
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)
34023e12
C
354
355 await this.processM3U8ToObjectStorage(segmentPath)
cfd57d2c
C
356 } catch (err) {
357 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
8ebf2a5d 358 }
cfd57d2c 359 }
29399256 360
cfd57d2c
C
361 // Master playlist and segment JSON file are created, live is ready
362 if (this.masterPlaylistCreated && !this.liveReady) {
363 this.liveReady = true
364
0c9668f7 365 this.emit('live-ready', { videoUUID: this.videoUUID })
cfd57d2c 366 }
8ebf2a5d
C
367 }
368
34023e12
C
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
0c9668f7
C
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
28705705 399 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputLocalUrl, this.lTags())
0c9668f7
C
400
401 setTimeout(() => {
402 // Wait latest segments generation, and close watchers
403
3a0c2a77
C
404 const promise = this.filesWatcher?.close() || Promise.resolve()
405 promise
0c9668f7
C
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
8ebf2a5d
C
423 private hasClientSocketInBadHealth (sessionId: string) {
424 const rtmpSession = this.context.sessions.get(sessionId)
425
426 if (!rtmpSession) {
4c6757f2 427 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
8ebf2a5d
C
428 return
429 }
430
431 for (const playerSessionId of rtmpSession.players) {
432 const playerSession = this.context.sessions.get(playerSessionId)
433
434 if (!playerSession) {
4c6757f2 435 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
8ebf2a5d
C
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
b34ee7fa 447 private async addSegmentToReplay (segmentPath: string) {
8ebf2a5d 448 const segmentName = basename(segmentPath)
4ec52d04 449 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
8ebf2a5d
C
450
451 try {
452 const data = await readFile(segmentPath)
453
454 await appendFile(dest, data)
455 } catch (err) {
4c6757f2 456 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
8ebf2a5d
C
457 }
458 }
afb371d9
C
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 }
0c9668f7
C
484
485 private buildTranscodingWrapper () {
486 const options = {
487 streamingPlaylist: this.streamingPlaylist,
488 videoLive: this.videoLive,
489
490 lTags: this.lTags,
491
28705705
C
492 inputLocalUrl: this.inputLocalUrl,
493 inputPublicUrl: this.inputPublicUrl,
0c9668f7
C
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 }
34023e12
C
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 }
8ebf2a5d
C
525}
526
527// ---------------------------------------------------------------------------
528
529export {
530 MuxingSession
531}