]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/shared/muxing-session.ts
Enable external plugins to test the PR
[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 { removeHLSFileObjectStorageByPath, storeHLSFileFromFilename, storeHLSFileFromPath } from '@server/lib/object-storage'
12 import { VideoFileModel } from '@server/models/video/video-file'
13 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
14 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
15 import { VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
16 import {
17 generateHLSMasterPlaylistFilename,
18 generateHlsSha256SegmentsFilename,
19 getLiveDirectory,
20 getLiveReplayBaseDirectory
21 } from '../../paths'
22 import { isAbleToUploadVideo } from '../../user'
23 import { LiveQuotaStore } from '../live-quota-store'
24 import { LiveSegmentShaStore } from '../live-segment-sha-store'
25 import { buildConcatenatedName, getLiveSegmentTime } from '../live-utils'
26 import { AbstractTranscodingWrapper, FFmpegTranscodingWrapper, RemoteTranscodingWrapper } from './transcoding-wrapper'
27
28 import memoizee = require('memoizee')
29 interface MuxingSessionEvents {
30 'live-ready': (options: { videoUUID: string }) => void
31
32 'bad-socket-health': (options: { videoUUID: string }) => void
33 'duration-exceeded': (options: { videoUUID: string }) => void
34 'quota-exceeded': (options: { videoUUID: string }) => void
35
36 'transcoding-end': (options: { videoUUID: string }) => void
37 'transcoding-error': (options: { videoUUID: string }) => void
38
39 'after-cleanup': (options: { videoUUID: string }) => void
40 }
41
42 declare 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
52 class MuxingSession extends EventEmitter {
53
54 private transcodingWrapper: AbstractTranscodingWrapper
55
56 private readonly context: any
57 private readonly user: MUserId
58 private readonly sessionId: string
59 private readonly videoLive: MVideoLiveVideo
60 private readonly inputUrl: string
61 private readonly fps: number
62 private readonly allResolutions: number[]
63
64 private readonly bitrate: number
65 private readonly ratio: number
66
67 private readonly hasAudio: boolean
68
69 private readonly videoUUID: string
70 private readonly saveReplay: boolean
71
72 private readonly outDirectory: string
73 private readonly replayDirectory: string
74
75 private readonly lTags: LoggerTagsFn
76
77 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
78
79 private streamingPlaylist: MStreamingPlaylistVideo
80 private liveSegmentShaStore: LiveSegmentShaStore
81
82 private filesWatcher: FSWatcher
83
84 private masterPlaylistCreated = false
85 private liveReady = false
86
87 private aborted = false
88
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
102 inputUrl: string
103 fps: number
104 bitrate: number
105 ratio: number
106 allResolutions: number[]
107 hasAudio: boolean
108 }) {
109 super()
110
111 this.context = options.context
112 this.user = options.user
113 this.sessionId = options.sessionId
114 this.videoLive = options.videoLive
115 this.inputUrl = options.inputUrl
116 this.fps = options.fps
117
118 this.bitrate = options.bitrate
119 this.ratio = options.ratio
120
121 this.hasAudio = options.hasAudio
122
123 this.allResolutions = options.allResolutions
124
125 this.videoUUID = this.videoLive.Video.uuid
126
127 this.saveReplay = this.videoLive.saveReplay
128
129 this.outDirectory = getLiveDirectory(this.videoLive.Video)
130 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
131
132 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
133 }
134
135 async runMuxing () {
136 this.streamingPlaylist = await this.createLivePlaylist()
137
138 this.createLiveShaStore()
139 this.createFiles()
140
141 await this.prepareDirectories()
142
143 this.transcodingWrapper = this.buildTranscodingWrapper()
144
145 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
146 this.transcodingWrapper.on('error', () => this.onTranscodingError())
147
148 await this.transcodingWrapper.run()
149
150 this.filesWatcher = watch(this.outDirectory, { depth: 0 })
151
152 this.watchMasterFile()
153 this.watchTSFiles()
154 this.watchM3U8File()
155 }
156
157 abort () {
158 if (!this.transcodingWrapper) return
159
160 this.aborted = true
161 this.transcodingWrapper.abort()
162 }
163
164 destroy () {
165 this.removeAllListeners()
166 this.isAbleToUploadVideoWithCache.clear()
167 this.hasClientSocketInBadHealthWithCache.clear()
168 }
169
170 private watchMasterFile () {
171 this.filesWatcher.on('add', async path => {
172 if (path !== join(this.outDirectory, this.streamingPlaylist.playlistFilename)) return
173 if (this.masterPlaylistCreated === true) return
174
175 try {
176 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
177 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
178
179 this.streamingPlaylist.playlistUrl = url
180 }
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() })
187 }
188
189 this.masterPlaylistCreated = true
190
191 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
192 })
193 }
194
195 private watchM3U8File () {
196 const sendQueues = new Map<string, PQueue>()
197
198 const onChange = async (m3u8Path: string) => {
199 if (m3u8Path.endsWith('.m3u8') !== true) return
200 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
201
202 logger.debug('Live change handler of M3U8 file %s.', m3u8Path, this.lTags())
203
204 try {
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))
211 } catch (err) {
212 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
213 }
214 }
215
216 this.filesWatcher.on('change', onChange)
217 }
218
219 private watchTSFiles () {
220 const startStreamDateTime = new Date().getTime()
221
222 const playlistIdMatcher = /^([\d+])-/
223
224 const addHandler = async (segmentPath: string) => {
225 if (segmentPath.endsWith('.ts') !== true) return
226
227 logger.debug('Live add handler of TS file %s.', segmentPath, this.lTags())
228
229 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
230
231 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
232 this.processSegments(segmentsToProcess)
233
234 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
235
236 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
237 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
238 return
239 }
240
241 // Duration constraint check
242 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
243 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
244 return
245 }
246
247 // Check user quota if the user enabled replay saving
248 if (await this.isQuotaExceeded(segmentPath) === true) {
249 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
250 }
251 }
252
253 const deleteHandler = async (segmentPath: string) => {
254 if (segmentPath.endsWith('.ts') !== true) return
255
256 logger.debug('Live delete handler of TS file %s.', segmentPath, this.lTags())
257
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 {
266 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
267 } catch (err) {
268 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
269 }
270 }
271 }
272
273 this.filesWatcher.on('add', p => addHandler(p))
274 this.filesWatcher.on('unlink', p => deleteHandler(p))
275 }
276
277 private async isQuotaExceeded (segmentPath: string) {
278 if (this.saveReplay !== true) return false
279 if (this.aborted) return false
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) {
290 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
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,
304 storage: this.streamingPlaylist.storage,
305 videoStreamingPlaylistId: this.streamingPlaylist.id
306 })
307
308 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
309 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
310 }
311 }
312
313 private async prepareDirectories () {
314 await ensureDir(this.outDirectory)
315
316 if (this.videoLive.saveReplay === true) {
317 await ensureDir(this.replayDirectory)
318 }
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
332 private processSegments (segmentPaths: string[]) {
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 }
340
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() })
354 }
355 }
356
357 // Master playlist and segment JSON file are created, live is ready
358 if (this.masterPlaylistCreated && !this.liveReady) {
359 this.liveReady = true
360
361 this.emit('live-ready', { videoUUID: this.videoUUID })
362 }
363 }
364
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
377 const promise = this.filesWatcher?.close() || Promise.resolve()
378 promise
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
396 private hasClientSocketInBadHealth (sessionId: string) {
397 const rtmpSession = this.context.sessions.get(sessionId)
398
399 if (!rtmpSession) {
400 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
401 return
402 }
403
404 for (const playerSessionId of rtmpSession.players) {
405 const playerSession = this.context.sessions.get(playerSessionId)
406
407 if (!playerSession) {
408 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
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
420 private async addSegmentToReplay (segmentPath: string) {
421 const segmentName = basename(segmentPath)
422 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
423
424 try {
425 const data = await readFile(segmentPath)
426
427 await appendFile(dest, data)
428 } catch (err) {
429 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
430 }
431 }
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 }
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 }
487 }
488
489 // ---------------------------------------------------------------------------
490
491 export {
492 MuxingSession
493 }