]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/shared/muxing-session.ts
Translated using Weblate (Icelandic)
[github/Chocobozzz/PeerTube.git] / server / lib / live / shared / muxing-session.ts
1 import { mapSeries } from 'bluebird'
2 import { FSWatcher, watch } from 'chokidar'
3 import { FfmpegCommand } from 'fluent-ffmpeg'
4 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
5 import PQueue from 'p-queue'
6 import { basename, join } from 'path'
7 import { EventEmitter } from 'stream'
8 import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg'
9 import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
10 import { CONFIG } from '@server/initializers/config'
11 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants'
12 import { removeHLSFileObjectStorageByPath, storeHLSFileFromFilename, storeHLSFileFromPath } from '@server/lib/object-storage'
13 import { VideoFileModel } from '@server/models/video/video-file'
14 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
15 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
16 import { VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
17 import {
18 generateHLSMasterPlaylistFilename,
19 generateHlsSha256SegmentsFilename,
20 getLiveDirectory,
21 getLiveReplayBaseDirectory
22 } from '../../paths'
23 import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles'
24 import { isAbleToUploadVideo } from '../../user'
25 import { LiveQuotaStore } from '../live-quota-store'
26 import { LiveSegmentShaStore } from '../live-segment-sha-store'
27 import { buildConcatenatedName } from '../live-utils'
28
29 import memoizee = require('memoizee')
30 interface MuxingSessionEvents {
31 'live-ready': (options: { videoId: number }) => void
32
33 'bad-socket-health': (options: { videoId: number }) => void
34 'duration-exceeded': (options: { videoId: number }) => void
35 'quota-exceeded': (options: { videoId: number }) => void
36
37 'ffmpeg-end': (options: { videoId: number }) => void
38 'ffmpeg-error': (options: { videoId: number }) => void
39
40 'after-cleanup': (options: { videoId: number }) => void
41 }
42
43 declare 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
53 class 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
61 private readonly inputUrl: string
62 private readonly fps: number
63 private readonly allResolutions: number[]
64
65 private readonly bitrate: number
66 private readonly ratio: number
67
68 private readonly hasAudio: boolean
69
70 private readonly videoId: number
71 private readonly videoUUID: string
72 private readonly saveReplay: boolean
73
74 private readonly outDirectory: string
75 private readonly replayDirectory: string
76
77 private readonly lTags: LoggerTagsFn
78
79 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
80
81 private streamingPlaylist: MStreamingPlaylistVideo
82 private liveSegmentShaStore: LiveSegmentShaStore
83
84 private tsWatcher: FSWatcher
85 private masterWatcher: FSWatcher
86 private m3u8Watcher: FSWatcher
87
88 private masterPlaylistCreated = false
89 private liveReady = false
90
91 private aborted = false
92
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
106 inputUrl: string
107 fps: number
108 bitrate: number
109 ratio: number
110 allResolutions: number[]
111 hasAudio: boolean
112 }) {
113 super()
114
115 this.context = options.context
116 this.user = options.user
117 this.sessionId = options.sessionId
118 this.videoLive = options.videoLive
119 this.inputUrl = options.inputUrl
120 this.fps = options.fps
121
122 this.bitrate = options.bitrate
123 this.ratio = options.ratio
124
125 this.hasAudio = options.hasAudio
126
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
134 this.outDirectory = getLiveDirectory(this.videoLive.Video)
135 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
136
137 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
138 }
139
140 async runMuxing () {
141 this.streamingPlaylist = await this.createLivePlaylist()
142
143 this.createLiveShaStore()
144 this.createFiles()
145
146 await this.prepareDirectories()
147
148 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
149 ? await getLiveTranscodingCommand({
150 inputUrl: this.inputUrl,
151
152 outPath: this.outDirectory,
153 masterPlaylistName: this.streamingPlaylist.playlistFilename,
154
155 latencyMode: this.videoLive.latencyMode,
156
157 resolutions: this.allResolutions,
158 fps: this.fps,
159 bitrate: this.bitrate,
160 ratio: this.ratio,
161
162 hasAudio: this.hasAudio,
163
164 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
165 profile: CONFIG.LIVE.TRANSCODING.PROFILE
166 })
167 : getLiveMuxingCommand({
168 inputUrl: this.inputUrl,
169 outPath: this.outDirectory,
170 masterPlaylistName: this.streamingPlaylist.playlistFilename,
171 latencyMode: this.videoLive.latencyMode
172 })
173
174 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
175
176 this.watchMasterFile()
177 this.watchTSFiles()
178 this.watchM3U8File()
179
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
187 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
188 this.onFFmpegError({ err, stdout, stderr, ffmpegShellCommand })
189 })
190
191 this.ffmpegCommand.on('end', () => {
192 this.emit('ffmpeg-end', ({ videoId: this.videoId }))
193
194 this.onFFmpegEnded()
195 })
196
197 this.ffmpegCommand.run()
198 }
199
200 abort () {
201 if (!this.ffmpegCommand) return
202
203 this.aborted = true
204 this.ffmpegCommand.kill('SIGINT')
205 }
206
207 destroy () {
208 this.removeAllListeners()
209 this.isAbleToUploadVideoWithCache.clear()
210 this.hasClientSocketInBadHealthWithCache.clear()
211 }
212
213 private onFFmpegError (options: {
214 err: any
215 stdout: string
216 stderr: string
217 ffmpegShellCommand: string
218 }) {
219 const { err, stdout, stderr, ffmpegShellCommand } = options
220
221 this.onFFmpegEnded()
222
223 // Don't care that we killed the ffmpeg process
224 if (err?.message?.includes('Exiting normally')) return
225
226 logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
227
228 this.emit('ffmpeg-error', ({ videoId: this.videoId }))
229 }
230
231 private onFFmpegEnded () {
232 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
233
234 setTimeout(() => {
235 // Wait latest segments generation, and close watchers
236
237 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close(), this.m3u8Watcher.close() ])
238 .then(() => {
239 // Process remaining segments hash
240 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
241 this.processSegments(this.segmentsToProcessPerPlaylist[key])
242 }
243 })
244 .catch(err => {
245 logger.error(
246 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
247 { err, ...this.lTags() }
248 )
249 })
250
251 this.emit('after-cleanup', { videoId: this.videoId })
252 }, 1000)
253 }
254
255 private watchMasterFile () {
256 this.masterWatcher = watch(this.outDirectory + '/' + this.streamingPlaylist.playlistFilename)
257
258 this.masterWatcher.on('add', async () => {
259 try {
260 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
261 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
262
263 this.streamingPlaylist.playlistUrl = url
264 }
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() })
271 }
272
273 this.masterPlaylistCreated = true
274
275 this.masterWatcher.close()
276 .catch(err => logger.error('Cannot close master watcher of %s.', this.outDirectory, { err, ...this.lTags() }))
277 })
278 }
279
280 private watchM3U8File () {
281 this.m3u8Watcher = watch(this.outDirectory + '/*.m3u8')
282
283 const sendQueues = new Map<string, PQueue>()
284
285 const onChangeOrAdd = async (m3u8Path: string) => {
286 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
287
288 try {
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))
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
303 private watchTSFiles () {
304 const startStreamDateTime = new Date().getTime()
305
306 this.tsWatcher = watch(this.outDirectory + '/*.ts')
307
308 const playlistIdMatcher = /^([\d+])-/
309
310 const addHandler = async (segmentPath: string) => {
311 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
312
313 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
314
315 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
316 this.processSegments(segmentsToProcess)
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
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 {
346 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
347 } catch (err) {
348 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
349 }
350 }
351 }
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
359 if (this.aborted) return false
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) {
370 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
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,
384 storage: this.streamingPlaylist.storage,
385 videoStreamingPlaylistId: this.streamingPlaylist.id
386 })
387
388 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
389 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
390 }
391 }
392
393 private async prepareDirectories () {
394 await ensureDir(this.outDirectory)
395
396 if (this.videoLive.saveReplay === true) {
397 await ensureDir(this.replayDirectory)
398 }
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
412 private processSegments (segmentPaths: string[]) {
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 }
420
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() })
434 }
435 }
436
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 }
443 }
444
445 private hasClientSocketInBadHealth (sessionId: string) {
446 const rtmpSession = this.context.sessions.get(sessionId)
447
448 if (!rtmpSession) {
449 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
450 return
451 }
452
453 for (const playerSessionId of rtmpSession.players) {
454 const playerSession = this.context.sessions.get(playerSessionId)
455
456 if (!playerSession) {
457 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
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
469 private async addSegmentToReplay (segmentPath: string) {
470 const segmentName = basename(segmentPath)
471 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
472
473 try {
474 const data = await readFile(segmentPath)
475
476 await appendFile(dest, data)
477 } catch (err) {
478 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
479 }
480 }
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 }
506 }
507
508 // ---------------------------------------------------------------------------
509
510 export {
511 MuxingSession
512 }