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