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