]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/shared/muxing-session.ts
Typo
[github/Chocobozzz/PeerTube.git] / server / lib / live / shared / muxing-session.ts
1
2 import { mapSeries } from 'bluebird'
3 import { FSWatcher, watch } from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
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, VIDEO_LIVE } from '@server/initializers/constants'
12 import { VideoFileModel } from '@server/models/video/video-file'
13 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
14 import { getLiveDirectory, getLiveReplayBaseDirectory } from '../../paths'
15 import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles'
16 import { isAbleToUploadVideo } from '../../user'
17 import { LiveQuotaStore } from '../live-quota-store'
18 import { LiveSegmentShaStore } from '../live-segment-sha-store'
19 import { buildConcatenatedName } from '../live-utils'
20
21 import memoizee = require('memoizee')
22
23 interface MuxingSessionEvents {
24 'master-playlist-created': ({ videoId: number }) => void
25
26 'bad-socket-health': ({ videoId: number }) => void
27 'duration-exceeded': ({ videoId: number }) => void
28 'quota-exceeded': ({ videoId: number }) => void
29
30 'ffmpeg-end': ({ videoId: number }) => void
31 'ffmpeg-error': ({ sessionId: string }) => void
32
33 'after-cleanup': ({ videoId: number }) => void
34 }
35
36 declare interface MuxingSession {
37 on<U extends keyof MuxingSessionEvents>(
38 event: U, listener: MuxingSessionEvents[U]
39 ): this
40
41 emit<U extends keyof MuxingSessionEvents>(
42 event: U, ...args: Parameters<MuxingSessionEvents[U]>
43 ): boolean
44 }
45
46 class MuxingSession extends EventEmitter {
47
48 private ffmpegCommand: FfmpegCommand
49
50 private readonly context: any
51 private readonly user: MUserId
52 private readonly sessionId: string
53 private readonly videoLive: MVideoLiveVideo
54 private readonly streamingPlaylist: MStreamingPlaylistVideo
55 private readonly inputUrl: string
56 private readonly fps: number
57 private readonly allResolutions: number[]
58
59 private readonly bitrate: number
60 private readonly ratio: number
61
62 private readonly videoId: number
63 private readonly videoUUID: string
64 private readonly saveReplay: boolean
65
66 private readonly outDirectory: string
67 private readonly replayDirectory: string
68
69 private readonly lTags: LoggerTagsFn
70
71 private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
72
73 private tsWatcher: FSWatcher
74 private masterWatcher: FSWatcher
75
76 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
77 return isAbleToUploadVideo(userId, 1000)
78 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
79
80 private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {
81 return this.hasClientSocketInBadHealth(sessionId)
82 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
83
84 constructor (options: {
85 context: any
86 user: MUserId
87 sessionId: string
88 videoLive: MVideoLiveVideo
89 streamingPlaylist: MStreamingPlaylistVideo
90 inputUrl: string
91 fps: number
92 bitrate: number
93 ratio: number
94 allResolutions: number[]
95 }) {
96 super()
97
98 this.context = options.context
99 this.user = options.user
100 this.sessionId = options.sessionId
101 this.videoLive = options.videoLive
102 this.streamingPlaylist = options.streamingPlaylist
103 this.inputUrl = options.inputUrl
104 this.fps = options.fps
105
106 this.bitrate = options.bitrate
107 this.ratio = options.ratio
108
109 this.allResolutions = options.allResolutions
110
111 this.videoId = this.videoLive.Video.id
112 this.videoUUID = this.videoLive.Video.uuid
113
114 this.saveReplay = this.videoLive.saveReplay
115
116 this.outDirectory = getLiveDirectory(this.videoLive.Video)
117 this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
118
119 this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
120 }
121
122 async runMuxing () {
123 this.createFiles()
124
125 await this.prepareDirectories()
126
127 this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
128 ? await getLiveTranscodingCommand({
129 inputUrl: this.inputUrl,
130
131 outPath: this.outDirectory,
132 masterPlaylistName: this.streamingPlaylist.playlistFilename,
133
134 latencyMode: this.videoLive.latencyMode,
135
136 resolutions: this.allResolutions,
137 fps: this.fps,
138 bitrate: this.bitrate,
139 ratio: this.ratio,
140
141 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
142 profile: CONFIG.LIVE.TRANSCODING.PROFILE
143 })
144 : getLiveMuxingCommand({
145 inputUrl: this.inputUrl,
146 outPath: this.outDirectory,
147 masterPlaylistName: this.streamingPlaylist.playlistFilename,
148 latencyMode: this.videoLive.latencyMode
149 })
150
151 logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
152
153 this.watchTSFiles(this.outDirectory)
154 this.watchMasterFile(this.outDirectory)
155
156 let ffmpegShellCommand: string
157 this.ffmpegCommand.on('start', cmdline => {
158 ffmpegShellCommand = cmdline
159
160 logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() })
161 })
162
163 this.ffmpegCommand.on('error', (err, stdout, stderr) => {
164 this.onFFmpegError({ err, stdout, stderr, outPath: this.outDirectory, ffmpegShellCommand })
165 })
166
167 this.ffmpegCommand.on('end', () => this.onFFmpegEnded(this.outDirectory))
168
169 this.ffmpegCommand.run()
170 }
171
172 abort () {
173 if (!this.ffmpegCommand) return
174
175 this.ffmpegCommand.kill('SIGINT')
176 }
177
178 destroy () {
179 this.removeAllListeners()
180 this.isAbleToUploadVideoWithCache.clear()
181 this.hasClientSocketInBadHealthWithCache.clear()
182 }
183
184 private onFFmpegError (options: {
185 err: any
186 stdout: string
187 stderr: string
188 outPath: string
189 ffmpegShellCommand: string
190 }) {
191 const { err, stdout, stderr, outPath, ffmpegShellCommand } = options
192
193 this.onFFmpegEnded(outPath)
194
195 // Don't care that we killed the ffmpeg process
196 if (err?.message?.includes('Exiting normally')) return
197
198 logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
199
200 this.emit('ffmpeg-error', ({ sessionId: this.sessionId }))
201 }
202
203 private onFFmpegEnded (outPath: string) {
204 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
205
206 setTimeout(() => {
207 // Wait latest segments generation, and close watchers
208
209 Promise.all([ this.tsWatcher.close(), this.masterWatcher.close() ])
210 .then(() => {
211 // Process remaining segments hash
212 for (const key of Object.keys(this.segmentsToProcessPerPlaylist)) {
213 this.processSegments(outPath, this.segmentsToProcessPerPlaylist[key])
214 }
215 })
216 .catch(err => {
217 logger.error(
218 'Cannot close watchers of %s or process remaining hash segments.', outPath,
219 { err, ...this.lTags() }
220 )
221 })
222
223 this.emit('after-cleanup', { videoId: this.videoId })
224 }, 1000)
225 }
226
227 private watchMasterFile (outPath: string) {
228 this.masterWatcher = watch(outPath + '/' + this.streamingPlaylist.playlistFilename)
229
230 this.masterWatcher.on('add', () => {
231 this.emit('master-playlist-created', { videoId: this.videoId })
232
233 this.masterWatcher.close()
234 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags() }))
235 })
236 }
237
238 private watchTSFiles (outPath: string) {
239 const startStreamDateTime = new Date().getTime()
240
241 this.tsWatcher = watch(outPath + '/*.ts')
242
243 const playlistIdMatcher = /^([\d+])-/
244
245 const addHandler = async (segmentPath: string) => {
246 logger.debug('Live add handler of %s.', segmentPath, this.lTags())
247
248 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
249
250 const segmentsToProcess = this.segmentsToProcessPerPlaylist[playlistId] || []
251 this.processSegments(outPath, segmentsToProcess)
252
253 this.segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
254
255 if (this.hasClientSocketInBadHealthWithCache(this.sessionId)) {
256 this.emit('bad-socket-health', { videoId: this.videoId })
257 return
258 }
259
260 // Duration constraint check
261 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
262 this.emit('duration-exceeded', { videoId: this.videoId })
263 return
264 }
265
266 // Check user quota if the user enabled replay saving
267 if (await this.isQuotaExceeded(segmentPath) === true) {
268 this.emit('quota-exceeded', { videoId: this.videoId })
269 }
270 }
271
272 const deleteHandler = segmentPath => LiveSegmentShaStore.Instance.removeSegmentSha(this.videoUUID, segmentPath)
273
274 this.tsWatcher.on('add', p => addHandler(p))
275 this.tsWatcher.on('unlink', p => deleteHandler(p))
276 }
277
278 private async isQuotaExceeded (segmentPath: string) {
279 if (this.saveReplay !== true) 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 videoStreamingPlaylistId: this.streamingPlaylist.id
305 })
306
307 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
308 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
309 }
310 }
311
312 private async prepareDirectories () {
313 await ensureDir(this.outDirectory)
314
315 if (this.videoLive.saveReplay === true) {
316 await ensureDir(this.replayDirectory)
317 }
318 }
319
320 private isDurationConstraintValid (streamingStartTime: number) {
321 const maxDuration = CONFIG.LIVE.MAX_DURATION
322 // No limit
323 if (maxDuration < 0) return true
324
325 const now = new Date().getTime()
326 const max = streamingStartTime + maxDuration
327
328 return now <= max
329 }
330
331 private processSegments (hlsVideoPath: string, segmentPaths: string[]) {
332 mapSeries(segmentPaths, async previousSegment => {
333 // Add sha hash of previous segments, because ffmpeg should have finished generating them
334 await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
335
336 if (this.saveReplay) {
337 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
338 }
339 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags() }))
340 }
341
342 private hasClientSocketInBadHealth (sessionId: string) {
343 const rtmpSession = this.context.sessions.get(sessionId)
344
345 if (!rtmpSession) {
346 logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
347 return
348 }
349
350 for (const playerSessionId of rtmpSession.players) {
351 const playerSession = this.context.sessions.get(playerSessionId)
352
353 if (!playerSession) {
354 logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
355 continue
356 }
357
358 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
359 return true
360 }
361 }
362
363 return false
364 }
365
366 private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
367 const segmentName = basename(segmentPath)
368 const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
369
370 try {
371 const data = await readFile(segmentPath)
372
373 await appendFile(dest, data)
374 } catch (err) {
375 logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
376 }
377 }
378 }
379
380 // ---------------------------------------------------------------------------
381
382 export {
383 MuxingSession
384 }