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