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