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