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