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