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