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