]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live-manager.ts
Fix audio issues with live replay
[github/Chocobozzz/PeerTube.git] / server / lib / live-manager.ts
1
2 import * as chokidar from 'chokidar'
3 import { FfmpegCommand } from 'fluent-ffmpeg'
4 import { appendFile, copy, ensureDir, readFile, stat } from 'fs-extra'
5 import { basename, join } from 'path'
6 import { isTestInstance } from '@server/helpers/core-utils'
7 import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils'
8 import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
9 import { logger } from '@server/helpers/logger'
10 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
11 import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants'
12 import { UserModel } from '@server/models/account/user'
13 import { VideoModel } from '@server/models/video/video'
14 import { VideoFileModel } from '@server/models/video/video-file'
15 import { VideoLiveModel } from '@server/models/video/video-live'
16 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
17 import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
18 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
19 import { federateVideoIfNeeded } from './activitypub/videos'
20 import { buildSha256Segment } from './hls'
21 import { JobQueue } from './job-queue'
22 import { cleanupLive } from './job-queue/handlers/video-live-ending'
23 import { PeerTubeSocket } from './peertube-socket'
24 import { isAbleToUploadVideo } from './user'
25 import { getHLSDirectory } from './video-paths'
26 import { availableEncoders } from './video-transcoding-profiles'
27 import * as Bluebird from 'bluebird'
28
29 import memoizee = require('memoizee')
30
31 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
32 const context = require('node-media-server/node_core_ctx')
33 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
34
35 // Disable node media server logs
36 nodeMediaServerLogger.setLogType(0)
37
38 const config = {
39 rtmp: {
40 port: CONFIG.LIVE.RTMP.PORT,
41 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
42 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
43 ping: VIDEO_LIVE.RTMP.PING,
44 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
45 },
46 transcoding: {
47 ffmpeg: 'ffmpeg'
48 }
49 }
50
51 class LiveManager {
52
53 private static instance: LiveManager
54
55 private readonly transSessions = new Map<string, FfmpegCommand>()
56 private readonly videoSessions = new Map<number, string>()
57 // Values are Date().getTime()
58 private readonly watchersPerVideo = new Map<number, number[]>()
59 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
60 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
61
62 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
63 return isAbleToUploadVideo(userId, 1000)
64 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
65
66 private rtmpServer: any
67
68 private constructor () {
69 }
70
71 init () {
72 const events = this.getContext().nodeEvent
73 events.on('postPublish', (sessionId: string, streamPath: string) => {
74 logger.debug('RTMP received stream', { id: sessionId, streamPath })
75
76 const splittedPath = streamPath.split('/')
77 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
78 logger.warn('Live path is incorrect.', { streamPath })
79 return this.abortSession(sessionId)
80 }
81
82 this.handleSession(sessionId, streamPath, splittedPath[2])
83 .catch(err => logger.error('Cannot handle sessions.', { err }))
84 })
85
86 events.on('donePublish', sessionId => {
87 logger.info('Live session ended.', { sessionId })
88 })
89
90 registerConfigChangedHandler(() => {
91 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
92 this.run()
93 return
94 }
95
96 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
97 this.stop()
98 }
99 })
100
101 // Cleanup broken lives, that were terminated by a server restart for example
102 this.handleBrokenLives()
103 .catch(err => logger.error('Cannot handle broken lives.', { err }))
104
105 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
106 }
107
108 run () {
109 logger.info('Running RTMP server on port %d', config.rtmp.port)
110
111 this.rtmpServer = new NodeRtmpServer(config)
112 this.rtmpServer.run()
113 }
114
115 stop () {
116 logger.info('Stopping RTMP server.')
117
118 this.rtmpServer.stop()
119 this.rtmpServer = undefined
120 }
121
122 isRunning () {
123 return !!this.rtmpServer
124 }
125
126 getSegmentsSha256 (videoUUID: string) {
127 return this.segmentsSha256.get(videoUUID)
128 }
129
130 stopSessionOf (videoId: number) {
131 const sessionId = this.videoSessions.get(videoId)
132 if (!sessionId) return
133
134 this.videoSessions.delete(videoId)
135 this.abortSession(sessionId)
136 }
137
138 getLiveQuotaUsedByUser (userId: number) {
139 const currentLives = this.livesPerUser.get(userId)
140 if (!currentLives) return 0
141
142 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
143 }
144
145 addViewTo (videoId: number) {
146 if (this.videoSessions.has(videoId) === false) return
147
148 let watchers = this.watchersPerVideo.get(videoId)
149
150 if (!watchers) {
151 watchers = []
152 this.watchersPerVideo.set(videoId, watchers)
153 }
154
155 watchers.push(new Date().getTime())
156 }
157
158 cleanupShaSegments (videoUUID: string) {
159 this.segmentsSha256.delete(videoUUID)
160 }
161
162 addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
163 const segmentName = basename(segmentPath)
164 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, this.buildConcatenatedName(segmentName))
165
166 return readFile(segmentPath)
167 .then(data => appendFile(dest, data))
168 .catch(err => logger.error('Cannot copy segment %s to repay directory.', segmentPath, { err }))
169 }
170
171 buildConcatenatedName (segmentOrPlaylistPath: string) {
172 const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/)
173
174 return 'concat-' + num[1] + '.ts'
175 }
176
177 private processSegments (hlsVideoPath: string, videoUUID: string, videoLive: MVideoLive, segmentPaths: string[]) {
178 Bluebird.mapSeries(segmentPaths, async previousSegment => {
179 // Add sha hash of previous segments, because ffmpeg should have finished generating them
180 await this.addSegmentSha(videoUUID, previousSegment)
181
182 if (videoLive.saveReplay) {
183 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
184 }
185 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err }))
186 }
187
188 private getContext () {
189 return context
190 }
191
192 private abortSession (id: string) {
193 const session = this.getContext().sessions.get(id)
194 if (session) {
195 session.stop()
196 this.getContext().sessions.delete(id)
197 }
198
199 const transSession = this.transSessions.get(id)
200 if (transSession) {
201 transSession.kill('SIGINT')
202 this.transSessions.delete(id)
203 }
204 }
205
206 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
207 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
208 if (!videoLive) {
209 logger.warn('Unknown live video with stream key %s.', streamKey)
210 return this.abortSession(sessionId)
211 }
212
213 const video = videoLive.Video
214 if (video.isBlacklisted()) {
215 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
216 return this.abortSession(sessionId)
217 }
218
219 // Cleanup old potential live files (could happen with a permanent live)
220 this.cleanupShaSegments(video.uuid)
221
222 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
223 if (oldStreamingPlaylist) {
224 await cleanupLive(video, oldStreamingPlaylist)
225 }
226
227 this.videoSessions.set(video.id, sessionId)
228
229 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
230
231 const session = this.getContext().sessions.get(sessionId)
232 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
233
234 const [ resolutionResult, fps ] = await Promise.all([
235 getVideoFileResolution(rtmpUrl),
236 getVideoFileFPS(rtmpUrl)
237 ])
238
239 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
240 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
241 : []
242
243 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
244
245 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
246
247 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
248 videoId: video.id,
249 playlistUrl,
250 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
251 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
252 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
253
254 type: VideoStreamingPlaylistType.HLS
255 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
256
257 return this.runMuxing({
258 sessionId,
259 videoLive,
260 playlist: videoStreamingPlaylist,
261 rtmpUrl,
262 fps,
263 allResolutions
264 })
265 }
266
267 private async runMuxing (options: {
268 sessionId: string
269 videoLive: MVideoLiveVideo
270 playlist: MStreamingPlaylist
271 rtmpUrl: string
272 fps: number
273 allResolutions: number[]
274 }) {
275 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
276 const startStreamDateTime = new Date().getTime()
277
278 const user = await UserModel.loadByLiveId(videoLive.id)
279 if (!this.livesPerUser.has(user.id)) {
280 this.livesPerUser.set(user.id, [])
281 }
282
283 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
284 const livesOfUser = this.livesPerUser.get(user.id)
285 livesOfUser.push(currentUserLive)
286
287 for (let i = 0; i < allResolutions.length; i++) {
288 const resolution = allResolutions[i]
289
290 VideoFileModel.upsert({
291 resolution,
292 size: -1,
293 extname: '.ts',
294 infoHash: null,
295 fps,
296 videoStreamingPlaylistId: playlist.id
297 }).catch(err => {
298 logger.error('Cannot create file for live streaming.', { err })
299 })
300 }
301
302 const outPath = getHLSDirectory(videoLive.Video)
303 await ensureDir(outPath)
304
305 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
306
307 if (videoLive.saveReplay === true) {
308 await ensureDir(replayDirectory)
309 }
310
311 const videoUUID = videoLive.Video.uuid
312
313 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
314 ? await getLiveTranscodingCommand({
315 rtmpUrl,
316 outPath,
317 resolutions: allResolutions,
318 fps,
319 availableEncoders,
320 profile: 'default'
321 })
322 : getLiveMuxingCommand(rtmpUrl, outPath)
323
324 logger.info('Running live muxing/transcoding for %s.', videoUUID)
325 this.transSessions.set(sessionId, ffmpegExec)
326
327 const tsWatcher = chokidar.watch(outPath + '/*.ts')
328
329 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
330 const playlistIdMatcher = /^([\d+])-/
331
332 const addHandler = segmentPath => {
333 logger.debug('Live add handler of %s.', segmentPath)
334
335 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
336
337 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
338 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcess)
339
340 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
341
342 // Duration constraint check
343 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
344 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
345
346 this.stopSessionOf(videoLive.videoId)
347 }
348
349 // Check user quota if the user enabled replay saving
350 if (videoLive.saveReplay === true) {
351 stat(segmentPath)
352 .then(segmentStat => {
353 currentUserLive.size += segmentStat.size
354 })
355 .then(() => this.isQuotaConstraintValid(user, videoLive))
356 .then(quotaValid => {
357 if (quotaValid !== true) {
358 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
359
360 this.stopSessionOf(videoLive.videoId)
361 }
362 })
363 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
364 }
365 }
366
367 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
368
369 tsWatcher.on('add', p => addHandler(p))
370 tsWatcher.on('unlink', p => deleteHandler(p))
371
372 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
373 masterWatcher.on('add', async () => {
374 try {
375 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
376
377 video.state = VideoState.PUBLISHED
378 await video.save()
379 videoLive.Video = video
380
381 setTimeout(() => {
382 federateVideoIfNeeded(video, false)
383 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
384
385 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
386 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
387
388 } catch (err) {
389 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
390 } finally {
391 masterWatcher.close()
392 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
393 }
394 })
395
396 const onFFmpegEnded = () => {
397 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
398
399 this.transSessions.delete(sessionId)
400
401 this.watchersPerVideo.delete(videoLive.videoId)
402 this.videoSessions.delete(videoLive.videoId)
403
404 const newLivesPerUser = this.livesPerUser.get(user.id)
405 .filter(o => o.liveId !== videoLive.id)
406 this.livesPerUser.set(user.id, newLivesPerUser)
407
408 setTimeout(() => {
409 // Wait latest segments generation, and close watchers
410
411 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
412 .then(() => {
413 // Process remaining segments hash
414 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
415 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcessPerPlaylist[key])
416 }
417 })
418 .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err }))
419
420 this.onEndTransmuxing(videoLive.Video.id)
421 .catch(err => logger.error('Error in closed transmuxing.', { err }))
422 }, 1000)
423 }
424
425 ffmpegExec.on('error', (err, stdout, stderr) => {
426 onFFmpegEnded()
427
428 // Don't care that we killed the ffmpeg process
429 if (err?.message?.includes('Exiting normally')) return
430
431 logger.error('Live transcoding error.', { err, stdout, stderr })
432
433 this.abortSession(sessionId)
434 })
435
436 ffmpegExec.on('end', () => onFFmpegEnded())
437
438 ffmpegExec.run()
439 }
440
441 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
442 try {
443 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
444 if (!fullVideo) return
445
446 const live = await VideoLiveModel.loadByVideoId(videoId)
447
448 if (!live.permanentLive) {
449 JobQueue.Instance.createJob({
450 type: 'video-live-ending',
451 payload: {
452 videoId: fullVideo.id
453 }
454 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
455
456 fullVideo.state = VideoState.LIVE_ENDED
457 } else {
458 fullVideo.state = VideoState.WAITING_FOR_LIVE
459 }
460
461 await fullVideo.save()
462
463 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
464
465 await federateVideoIfNeeded(fullVideo, false)
466 } catch (err) {
467 logger.error('Cannot save/federate new video state of live streaming.', { err })
468 }
469 }
470
471 private async addSegmentSha (videoUUID: string, segmentPath: string) {
472 const segmentName = basename(segmentPath)
473 logger.debug('Adding live sha segment %s.', segmentPath)
474
475 const shaResult = await buildSha256Segment(segmentPath)
476
477 if (!this.segmentsSha256.has(videoUUID)) {
478 this.segmentsSha256.set(videoUUID, new Map())
479 }
480
481 const filesMap = this.segmentsSha256.get(videoUUID)
482 filesMap.set(segmentName, shaResult)
483 }
484
485 private removeSegmentSha (videoUUID: string, segmentPath: string) {
486 const segmentName = basename(segmentPath)
487
488 logger.debug('Removing live sha segment %s.', segmentPath)
489
490 const filesMap = this.segmentsSha256.get(videoUUID)
491 if (!filesMap) {
492 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
493 return
494 }
495
496 if (!filesMap.has(segmentName)) {
497 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
498 return
499 }
500
501 filesMap.delete(segmentName)
502 }
503
504 private isDurationConstraintValid (streamingStartTime: number) {
505 const maxDuration = CONFIG.LIVE.MAX_DURATION
506 // No limit
507 if (maxDuration === null) return true
508
509 const now = new Date().getTime()
510 const max = streamingStartTime + maxDuration
511
512 return now <= max
513 }
514
515 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
516 if (live.saveReplay !== true) return true
517
518 return this.isAbleToUploadVideoWithCache(user.id)
519 }
520
521 private async updateLiveViews () {
522 if (!this.isRunning()) return
523
524 if (!isTestInstance()) logger.info('Updating live video views.')
525
526 for (const videoId of this.watchersPerVideo.keys()) {
527 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
528
529 const watchers = this.watchersPerVideo.get(videoId)
530
531 const numWatchers = watchers.length
532
533 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
534 video.views = numWatchers
535 await video.save()
536
537 await federateVideoIfNeeded(video, false)
538
539 // Only keep not expired watchers
540 const newWatchers = watchers.filter(w => w > notBefore)
541 this.watchersPerVideo.set(videoId, newWatchers)
542
543 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
544 }
545 }
546
547 private async handleBrokenLives () {
548 const videoIds = await VideoModel.listPublishedLiveIds()
549
550 for (const id of videoIds) {
551 await this.onEndTransmuxing(id, true)
552 }
553 }
554
555 static get Instance () {
556 return this.instance || (this.instance = new this())
557 }
558 }
559
560 // ---------------------------------------------------------------------------
561
562 export {
563 LiveManager
564 }