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