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