]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/shared/muxing-session.ts
f3f8fc8863fc9c65ef1f8ed8c6f959159aef9223
[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 tsWatcher: FSWatcher
83 private masterWatcher: FSWatcher
84 private m3u8Watcher: FSWatcher
85
86 private masterPlaylistCreated = false
87 private liveReady = false
88
89 private aborted = false
90
91 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
92 return isAbleToUploadVideo(userId, 1000)
93 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
94
95 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
96 return this.hasClientSocketInBadHealth(sessionId)
97 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
98
99 constructor (options: {
100 context: any
101 user: MUserId
102 sessionId: string
103 videoLive: MVideoLiveVideo
104 inputUrl: string
105 fps: number
106 bitrate: number
107 ratio: number
108 allResolutions: number[]
109 hasAudio: boolean
110 }) {
111 super()
112
113 this.context = options.context
114 this.user = options.user
115 this.sessionId = options.sessionId
116 this.videoLive = options.videoLive
117 this.inputUrl = options.inputUrl
118 this.fps = options.fps
119
120 this.bitrate = options.bitrate
121 this.ratio = options.ratio
122
123 this.hasAudio = options.hasAudio
124
125 this.allResolutions = options.allResolutions
126
127 this.videoUUID = this.videoLive.Video.uuid
128
129 this.saveReplay = this.videoLive.saveReplay
130
131 this.outDirectory = getLiveDirectory(this.videoLive.Video)
132 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
133
134 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
135 }
136
137 async runMuxing () {
138 this.streamingPlaylist = await this.createLivePlaylist()
139
140 this.createLiveShaStore()
141 this.createFiles()
142
143 await this.prepareDirectories()
144
145 this.transcodingWrapper = this.buildTranscodingWrapper()
146
147 this.transcodingWrapper.on('end', () => this.onTranscodedEnded())
148 this.transcodingWrapper.on('error', () => this.onTranscodingError())
149
150 await this.transcodingWrapper.run()
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.masterWatcher = watch(this.outDirectory + '/' + this.streamingPlaylist.playlistFilename)
172
173 this.masterWatcher.on('add', async () => {
174 try {
175 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
176 const url = await storeHLSFileFromFilename(this.streamingPlaylist, this.streamingPlaylist.playlistFilename)
177
178 this.streamingPlaylist.playlistUrl = url
179 }
180
181 this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions)
182
183 await this.streamingPlaylist.save()
184 } catch (err) {
185 logger.error('Cannot update streaming playlist.', { err, ...this.lTags() })
186 }
187
188 this.masterPlaylistCreated = true
189
190 logger.info('Master playlist file for %s has been created', this.videoUUID, this.lTags())
191
192 this.masterWatcher.close()
193 .catch(err => logger.error('Cannot close master watcher of %s.', this.outDirectory, { err, ...this.lTags() }))
194 })
195 }
196
197 private watchM3U8File () {
198 this.m3u8Watcher = watch(this.outDirectory + '/*.m3u8')
199
200 const sendQueues = new Map<string, PQueue>()
201
202 const onChangeOrAdd = async (m3u8Path: string) => {
203 if (this.streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
204
205 try {
206 if (!sendQueues.has(m3u8Path)) {
207 sendQueues.set(m3u8Path, new PQueue({ concurrency: 1 }))
208 }
209
210 const queue = sendQueues.get(m3u8Path)
211 await queue.add(() => storeHLSFileFromPath(this.streamingPlaylist, m3u8Path))
212 } catch (err) {
213 logger.error('Cannot store in object storage m3u8 file %s', m3u8Path, { err, ...this.lTags() })
214 }
215 }
216
217 this.m3u8Watcher.on('change', onChangeOrAdd)
218 }
219
220 private watchTSFiles () {
221 const startStreamDateTime = new Date().getTime()
222
223 this.tsWatcher = watch(this.outDirectory + '/*.ts')
224
225 const playlistIdMatcher = /^([\d+])-/
226
227 const addHandler = async (segmentPath: string) => {
228 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
229
230 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
231
232 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
233 this.processSegments(segmentsToProcess)
234
235 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
236
237 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
238 this.emit('bad-socket-health', { videoUUID: this.videoUUID })
239 return
240 }
241
242 // Duration constraint check
243 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
244 this.emit('duration-exceeded', { videoUUID: this.videoUUID })
245 return
246 }
247
248 // Check user quota if the user enabled replay saving
249 if (await this.isQuotaExceeded(segmentPath) === true) {
250 this.emit('quota-exceeded', { videoUUID: this.videoUUID })
251 }
252 }
253
254 const deleteHandler = async (segmentPath: string) => {
255 try {
256 await this.liveSegmentShaStore.removeSegmentSha(segmentPath)
257 } catch (err) {
258 logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })
259 }
260
261 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
262 try {
263 await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
264 } catch (err) {
265 logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
266 }
267 }
268 }
269
270 this.tsWatcher.on('add', p => addHandler(p))
271 this.tsWatcher.on('unlink', p => deleteHandler(p))
272 }
273
274 private async isQuotaExceeded (segmentPath: string) {
275 if (this.saveReplay !== true) return false
276 if (this.aborted) return false
277
278 try {
279 const segmentStat = await stat(segmentPath)
280
281 LiveQuotaStore.Instance.addQuotaTo(this.user.id, this.videoLive.id, segmentStat.size)
282
283 const canUpload = await this.isAbleToUploadVideoWithCache(this.user.id)
284
285 return canUpload !== true
286 } catch (err) {
287 logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
288 }
289 }
290
291 private createFiles () {
292 for (let i = 0; i < this.allResolutions.length; i++) {
293 const resolution = this.allResolutions[i]
294
295 const file = new VideoFileModel({
296 resolution,
297 size: -1,
298 extname: '.ts',
299 infoHash: null,
300 fps: this.fps,
301 storage: this.streamingPlaylist.storage,
302 videoStreamingPlaylistId: this.streamingPlaylist.id
303 })
304
305 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
306 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
307 }
308 }
309
310 private async prepareDirectories () {
311 await ensureDir(this.outDirectory)
312
313 if (this.videoLive.saveReplay === true) {
314 await ensureDir(this.replayDirectory)
315 }
316 }
317
318 private isDurationConstraintValid (streamingStartTime: number) {
319 const maxDuration = CONFIG.LIVE.MAX_DURATION
320 // No limit
321 if (maxDuration < 0) return true
322
323 const now = new Date().getTime()
324 const max = streamingStartTime + maxDuration
325
326 return now <= max
327 }
328
329 private processSegments (segmentPaths: string[]) {
330 mapSeries(segmentPaths, previousSegment => this.processSegment(previousSegment))
331 .catch(err => {
332 if (this.aborted) return
333
334 logger.error('Cannot process segments', { err, ...this.lTags() })
335 })
336 }
337
338 private async processSegment (segmentPath: string) {
339 // Add sha hash of previous segments, because ffmpeg should have finished generating them
340 await this.liveSegmentShaStore.addSegmentSha(segmentPath)
341
342 if (this.saveReplay) {
343 await this.addSegmentToReplay(segmentPath)
344 }
345
346 if (this.streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
347 try {
348 await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
349 } catch (err) {
350 logger.error('Cannot store TS segment %s in object storage', segmentPath, { err, ...this.lTags() })
351 }
352 }
353
354 // Master playlist and segment JSON file are created, live is ready
355 if (this.masterPlaylistCreated && !this.liveReady) {
356 this.liveReady = true
357
358 this.emit('live-ready', { videoUUID: this.videoUUID })
359 }
360 }
361
362 private onTranscodingError () {
363 this.emit('transcoding-error', ({ videoUUID: this.videoUUID }))
364 }
365
366 private onTranscodedEnded () {
367 this.emit('transcoding-end', ({ videoUUID: this.videoUUID }))
368
369 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
370
371 setTimeout(() => {
372 // Wait latest segments generation, and close watchers
373
374 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close(), this.m3u8Watcher.close() ])
375 .then(() => {
376 // Process remaining segments hash
377 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
378 this.processSegments(this.segmentsToProcessPerPlaylist[key])
379 }
380 })
381 .catch(err => {
382 logger.error(
383 'Cannot close watchers of %s or process remaining hash segments.', this.outDirectory,
384 { err, ...this.lTags() }
385 )
386 })
387
388 this.emit('after-cleanup', { videoUUID: this.videoUUID })
389 }, 1000)
390 }
391
392 private hasClientSocketInBadHealth (sessionId: string) {
393 const rtmpSession = this.context.sessions.get(sessionId)
394
395 if (!rtmpSession) {
396 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
397 return
398 }
399
400 for (const playerSessionId of rtmpSession.players) {
401 const playerSession = this.context.sessions.get(playerSessionId)
402
403 if (!playerSession) {
404 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
405 continue
406 }
407
408 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
409 return true
410 }
411 }
412
413 return false
414 }
415
416 private async addSegmentToReplay (segmentPath: string) {
417 const segmentName = basename(segmentPath)
418 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
419
420 try {
421 const data = await readFile(segmentPath)
422
423 await appendFile(dest, data)
424 } catch (err) {
425 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
426 }
427 }
428
429 private async createLivePlaylist (): Promise<MStreamingPlaylistVideo> {
430 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(this.videoLive.Video)
431
432 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
433 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
434
435 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
436 playlist.type = VideoStreamingPlaylistType.HLS
437
438 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
439 ? VideoStorage.OBJECT_STORAGE
440 : VideoStorage.FILE_SYSTEM
441
442 return playlist.save()
443 }
444
445 private createLiveShaStore () {
446 this.liveSegmentShaStore = new LiveSegmentShaStore({
447 videoUUID: this.videoLive.Video.uuid,
448 sha256Path: join(this.outDirectory, this.streamingPlaylist.segmentsSha256Filename),
449 streamingPlaylist: this.streamingPlaylist,
450 sendToObjectStorage: CONFIG.OBJECT_STORAGE.ENABLED
451 })
452 }
453
454 private buildTranscodingWrapper () {
455 const options = {
456 streamingPlaylist: this.streamingPlaylist,
457 videoLive: this.videoLive,
458
459 lTags: this.lTags,
460
461 inputUrl: this.inputUrl,
462
463 toTranscode: this.allResolutions.map(resolution => ({
464 resolution,
465 fps: computeOutputFPS({ inputFPS: this.fps, resolution })
466 })),
467
468 fps: this.fps,
469 bitrate: this.bitrate,
470 ratio: this.ratio,
471 hasAudio: this.hasAudio,
472
473 segmentListSize: VIDEO_LIVE.SEGMENTS_LIST_SIZE,
474 segmentDuration: getLiveSegmentTime(this.videoLive.latencyMode),
475
476 outDirectory: this.outDirectory
477 }
478
479 return CONFIG.LIVE.TRANSCODING.ENABLED && CONFIG.LIVE.TRANSCODING.REMOTE_RUNNERS.ENABLED
480 ? new RemoteTranscodingWrapper(options)
481 : new FFmpegTranscodingWrapper(options)
482 }
483 }
484
485 // ---------------------------------------------------------------------------
486
487 export {
488 MuxingSession
489 }