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