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