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