aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/live-manager.ts
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2021-06-16 15:14:41 +0200
committerChocobozzz <me@florianbigard.com>2021-06-17 08:47:03 +0200
commit8ebf2a5d5d126e6ef9b89109124adf2a5e9e293d (patch)
treeeee3ef972943be629519c2dc97928878dbd2d732 /server/lib/live-manager.ts
parentfd6584844b070cfc283902aba26f2853473e83d1 (diff)
downloadPeerTube-8ebf2a5d5d126e6ef9b89109124adf2a5e9e293d.tar.gz
PeerTube-8ebf2a5d5d126e6ef9b89109124adf2a5e9e293d.tar.zst
PeerTube-8ebf2a5d5d126e6ef9b89109124adf2a5e9e293d.zip
Refactor live manager
Diffstat (limited to 'server/lib/live-manager.ts')
-rw-r--r--server/lib/live-manager.ts633
1 files changed, 0 insertions, 633 deletions
diff --git a/server/lib/live-manager.ts b/server/lib/live-manager.ts
deleted file mode 100644
index 563ba2578..000000000
--- a/server/lib/live-manager.ts
+++ /dev/null
@@ -1,633 +0,0 @@
1
2import * as Bluebird from 'bluebird'
3import * as chokidar from 'chokidar'
4import { FfmpegCommand } from 'fluent-ffmpeg'
5import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
6import { createServer, Server } from 'net'
7import { basename, join } from 'path'
8import { isTestInstance } from '@server/helpers/core-utils'
9import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils'
10import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
11import { logger, loggerTagsFactory } from '@server/helpers/logger'
12import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
13import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants'
14import { UserModel } from '@server/models/user/user'
15import { VideoModel } from '@server/models/video/video'
16import { VideoFileModel } from '@server/models/video/video-file'
17import { VideoLiveModel } from '@server/models/video/video-live'
18import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
19import { MStreamingPlaylist, MStreamingPlaylistVideo, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
20import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
21import { federateVideoIfNeeded } from './activitypub/videos'
22import { buildSha256Segment } from './hls'
23import { JobQueue } from './job-queue'
24import { cleanupLive } from './job-queue/handlers/video-live-ending'
25import { PeerTubeSocket } from './peertube-socket'
26import { VideoTranscodingProfilesManager } from './transcoding/video-transcoding-profiles'
27import { isAbleToUploadVideo } from './user'
28import { getHLSDirectory } from './video-paths'
29
30import memoizee = require('memoizee')
31const NodeRtmpSession = require('node-media-server/node_rtmp_session')
32const context = require('node-media-server/node_core_ctx')
33const nodeMediaServerLogger = require('node-media-server/node_core_logger')
34
35// Disable node media server logs
36nodeMediaServerLogger.setLogType(0)
37
38const config = {
39 rtmp: {
40 port: CONFIG.LIVE.RTMP.PORT,
41 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
42 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
43 ping: VIDEO_LIVE.RTMP.PING,
44 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
45 },
46 transcoding: {
47 ffmpeg: 'ffmpeg'
48 }
49}
50
51const lTags = loggerTagsFactory('live')
52
53class LiveManager {
54
55 private static instance: LiveManager
56
57 private readonly transSessions = new Map<string, FfmpegCommand>()
58 private readonly videoSessions = new Map<number, string>()
59 // Values are Date().getTime()
60 private readonly watchersPerVideo = new Map<number, number[]>()
61 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
62 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
63
64 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
65 return isAbleToUploadVideo(userId, 1000)
66 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
67
68 private readonly hasClientSocketsInBadHealthWithCache = memoizee((sessionId: string) => {
69 return this.hasClientSocketsInBadHealth(sessionId)
70 }, { maxAge: MEMOIZE_TTL.LIVE_CHECK_SOCKET_HEALTH })
71
72 private rtmpServer: Server
73
74 private constructor () {
75 }
76
77 init () {
78 const events = this.getContext().nodeEvent
79 events.on('postPublish', (sessionId: string, streamPath: string) => {
80 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
81
82 const splittedPath = streamPath.split('/')
83 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
84 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
85 return this.abortSession(sessionId)
86 }
87
88 this.handleSession(sessionId, streamPath, splittedPath[2])
89 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
90 })
91
92 events.on('donePublish', sessionId => {
93 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
94 })
95
96 registerConfigChangedHandler(() => {
97 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
98 this.run()
99 return
100 }
101
102 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
103 this.stop()
104 }
105 })
106
107 // Cleanup broken lives, that were terminated by a server restart for example
108 this.handleBrokenLives()
109 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
110
111 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
112 }
113
114 run () {
115 logger.info('Running RTMP server on port %d', config.rtmp.port, lTags())
116
117 this.rtmpServer = createServer(socket => {
118 const session = new NodeRtmpSession(config, socket)
119
120 session.run()
121 })
122
123 this.rtmpServer.on('error', err => {
124 logger.error('Cannot run RTMP server.', { err, ...lTags() })
125 })
126
127 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
128 }
129
130 stop () {
131 logger.info('Stopping RTMP server.', lTags())
132
133 this.rtmpServer.close()
134 this.rtmpServer = undefined
135
136 // Sessions is an object
137 this.getContext().sessions.forEach((session: any) => {
138 if (session instanceof NodeRtmpSession) {
139 session.stop()
140 }
141 })
142 }
143
144 isRunning () {
145 return !!this.rtmpServer
146 }
147
148 getSegmentsSha256 (videoUUID: string) {
149 return this.segmentsSha256.get(videoUUID)
150 }
151
152 stopSessionOf (videoId: number) {
153 const sessionId = this.videoSessions.get(videoId)
154 if (!sessionId) return
155
156 this.videoSessions.delete(videoId)
157 this.abortSession(sessionId)
158 }
159
160 getLiveQuotaUsedByUser (userId: number) {
161 const currentLives = this.livesPerUser.get(userId)
162 if (!currentLives) return 0
163
164 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
165 }
166
167 addViewTo (videoId: number) {
168 if (this.videoSessions.has(videoId) === false) return
169
170 let watchers = this.watchersPerVideo.get(videoId)
171
172 if (!watchers) {
173 watchers = []
174 this.watchersPerVideo.set(videoId, watchers)
175 }
176
177 watchers.push(new Date().getTime())
178 }
179
180 cleanupShaSegments (videoUUID: string) {
181 this.segmentsSha256.delete(videoUUID)
182 }
183
184 addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
185 const segmentName = basename(segmentPath)
186 const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, this.buildConcatenatedName(segmentName))
187
188 return readFile(segmentPath)
189 .then(data => appendFile(dest, data))
190 .catch(err => logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...lTags() }))
191 }
192
193 buildConcatenatedName (segmentOrPlaylistPath: string) {
194 const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/)
195
196 return 'concat-' + num[1] + '.ts'
197 }
198
199 private processSegments (hlsVideoPath: string, videoUUID: string, videoLive: MVideoLive, segmentPaths: string[]) {
200 Bluebird.mapSeries(segmentPaths, async previousSegment => {
201 // Add sha hash of previous segments, because ffmpeg should have finished generating them
202 await this.addSegmentSha(videoUUID, previousSegment)
203
204 if (videoLive.saveReplay) {
205 await this.addSegmentToReplay(hlsVideoPath, previousSegment)
206 }
207 }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...lTags(videoUUID) }))
208 }
209
210 private getContext () {
211 return context
212 }
213
214 private abortSession (id: string) {
215 const session = this.getContext().sessions.get(id)
216 if (session) {
217 session.stop()
218 this.getContext().sessions.delete(id)
219 }
220
221 const transSession = this.transSessions.get(id)
222 if (transSession) {
223 transSession.kill('SIGINT')
224 this.transSessions.delete(id)
225 }
226 }
227
228 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
229 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
230 if (!videoLive) {
231 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
232 return this.abortSession(sessionId)
233 }
234
235 const video = videoLive.Video
236 if (video.isBlacklisted()) {
237 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
238 return this.abortSession(sessionId)
239 }
240
241 // Cleanup old potential live files (could happen with a permanent live)
242 this.cleanupShaSegments(video.uuid)
243
244 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
245 if (oldStreamingPlaylist) {
246 await cleanupLive(video, oldStreamingPlaylist)
247 }
248
249 this.videoSessions.set(video.id, sessionId)
250
251 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
252
253 const session = this.getContext().sessions.get(sessionId)
254 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
255
256 const [ resolutionResult, fps ] = await Promise.all([
257 getVideoFileResolution(rtmpUrl),
258 getVideoFileFPS(rtmpUrl)
259 ])
260
261 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
262 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
263 : []
264
265 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
266
267 logger.info(
268 'Will mux/transcode live video of original resolution %d.', session.videoHeight,
269 { allResolutions, ...lTags(sessionId, video.uuid) }
270 )
271
272 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
273 videoId: video.id,
274 playlistUrl,
275 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
276 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
277 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
278
279 type: VideoStreamingPlaylistType.HLS
280 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
281
282 return this.runMuxing({
283 sessionId,
284 videoLive,
285 playlist: Object.assign(videoStreamingPlaylist, { Video: video }),
286 rtmpUrl,
287 fps,
288 allResolutions
289 })
290 }
291
292 private async runMuxing (options: {
293 sessionId: string
294 videoLive: MVideoLiveVideo
295 playlist: MStreamingPlaylistVideo
296 rtmpUrl: string
297 fps: number
298 allResolutions: number[]
299 }) {
300 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
301 const startStreamDateTime = new Date().getTime()
302
303 const user = await UserModel.loadByLiveId(videoLive.id)
304 if (!this.livesPerUser.has(user.id)) {
305 this.livesPerUser.set(user.id, [])
306 }
307
308 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
309 const livesOfUser = this.livesPerUser.get(user.id)
310 livesOfUser.push(currentUserLive)
311
312 for (let i = 0; i < allResolutions.length; i++) {
313 const resolution = allResolutions[i]
314
315 const file = new VideoFileModel({
316 resolution,
317 size: -1,
318 extname: '.ts',
319 infoHash: null,
320 fps,
321 videoStreamingPlaylistId: playlist.id
322 })
323
324 VideoFileModel.customUpsert(file, 'streaming-playlist', null)
325 .catch(err => logger.error('Cannot create file for live streaming.', { err, ...lTags(sessionId, videoLive.Video.uuid) }))
326 }
327
328 const outPath = getHLSDirectory(videoLive.Video)
329 await ensureDir(outPath)
330
331 const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
332
333 if (videoLive.saveReplay === true) {
334 await ensureDir(replayDirectory)
335 }
336
337 const videoUUID = videoLive.Video.uuid
338
339 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
340 ? await getLiveTranscodingCommand({
341 rtmpUrl,
342 outPath,
343 resolutions: allResolutions,
344 fps,
345 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
346 profile: CONFIG.LIVE.TRANSCODING.PROFILE
347 })
348 : getLiveMuxingCommand(rtmpUrl, outPath)
349
350 logger.info('Running live muxing/transcoding for %s.', videoUUID, lTags(sessionId, videoUUID))
351 this.transSessions.set(sessionId, ffmpegExec)
352
353 const tsWatcher = chokidar.watch(outPath + '/*.ts')
354
355 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
356 const playlistIdMatcher = /^([\d+])-/
357
358 const addHandler = segmentPath => {
359 logger.debug('Live add handler of %s.', segmentPath, lTags(sessionId, videoUUID))
360
361 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
362
363 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
364 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcess)
365
366 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
367
368 if (this.hasClientSocketsInBadHealthWithCache(sessionId)) {
369 logger.error(
370 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
371 ' Stopping session of video %s.', videoUUID,
372 lTags(sessionId, videoUUID)
373 )
374
375 this.stopSessionOf(videoLive.videoId)
376 return
377 }
378
379 // Duration constraint check
380 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
381 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, lTags(sessionId, videoUUID))
382
383 this.stopSessionOf(videoLive.videoId)
384 return
385 }
386
387 // Check user quota if the user enabled replay saving
388 if (videoLive.saveReplay === true) {
389 stat(segmentPath)
390 .then(segmentStat => {
391 currentUserLive.size += segmentStat.size
392 })
393 .then(() => this.isQuotaConstraintValid(user, videoLive))
394 .then(quotaValid => {
395 if (quotaValid !== true) {
396 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, lTags(sessionId, videoUUID))
397
398 this.stopSessionOf(videoLive.videoId)
399 }
400 })
401 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err, ...lTags(sessionId, videoUUID) }))
402 }
403 }
404
405 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
406
407 tsWatcher.on('add', p => addHandler(p))
408 tsWatcher.on('unlink', p => deleteHandler(p))
409
410 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
411 masterWatcher.on('add', async () => {
412 try {
413 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
414
415 video.state = VideoState.PUBLISHED
416 await video.save()
417 videoLive.Video = video
418
419 setTimeout(() => {
420 federateVideoIfNeeded(video, false)
421 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...lTags(sessionId, videoUUID) }))
422
423 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
424 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
425
426 } catch (err) {
427 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err, ...lTags(sessionId, videoUUID) })
428 } finally {
429 masterWatcher.close()
430 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...lTags(sessionId, videoUUID) }))
431 }
432 })
433
434 const onFFmpegEnded = () => {
435 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl, lTags(sessionId, videoUUID))
436
437 this.transSessions.delete(sessionId)
438
439 this.watchersPerVideo.delete(videoLive.videoId)
440 this.videoSessions.delete(videoLive.videoId)
441
442 const newLivesPerUser = this.livesPerUser.get(user.id)
443 .filter(o => o.liveId !== videoLive.id)
444 this.livesPerUser.set(user.id, newLivesPerUser)
445
446 setTimeout(() => {
447 // Wait latest segments generation, and close watchers
448
449 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
450 .then(() => {
451 // Process remaining segments hash
452 for (const key of Object.keys(segmentsToProcessPerPlaylist)) {
453 this.processSegments(outPath, videoUUID, videoLive, segmentsToProcessPerPlaylist[key])
454 }
455 })
456 .catch(err => {
457 logger.error(
458 'Cannot close watchers of %s or process remaining hash segments.', outPath,
459 { err, ...lTags(sessionId, videoUUID) }
460 )
461 })
462
463 this.onEndTransmuxing(videoLive.Video.id)
464 .catch(err => logger.error('Error in closed transmuxing.', { err, ...lTags(sessionId, videoUUID) }))
465 }, 1000)
466 }
467
468 ffmpegExec.on('error', (err, stdout, stderr) => {
469 onFFmpegEnded()
470
471 // Don't care that we killed the ffmpeg process
472 if (err?.message?.includes('Exiting normally')) return
473
474 logger.error('Live transcoding error.', { err, stdout, stderr, ...lTags(sessionId, videoUUID) })
475
476 this.abortSession(sessionId)
477 })
478
479 ffmpegExec.on('end', () => onFFmpegEnded())
480
481 ffmpegExec.run()
482 }
483
484 private async onEndTransmuxing (videoUUID: string, cleanupNow = false) {
485 try {
486 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
487 if (!fullVideo) return
488
489 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
490
491 if (!live.permanentLive) {
492 JobQueue.Instance.createJob({
493 type: 'video-live-ending',
494 payload: {
495 videoId: fullVideo.id
496 }
497 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
498
499 fullVideo.state = VideoState.LIVE_ENDED
500 } else {
501 fullVideo.state = VideoState.WAITING_FOR_LIVE
502 }
503
504 await fullVideo.save()
505
506 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
507
508 await federateVideoIfNeeded(fullVideo, false)
509 } catch (err) {
510 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
511 }
512 }
513
514 private async addSegmentSha (videoUUID: string, segmentPath: string) {
515 const segmentName = basename(segmentPath)
516 logger.debug('Adding live sha segment %s.', segmentPath, lTags(videoUUID))
517
518 const shaResult = await buildSha256Segment(segmentPath)
519
520 if (!this.segmentsSha256.has(videoUUID)) {
521 this.segmentsSha256.set(videoUUID, new Map())
522 }
523
524 const filesMap = this.segmentsSha256.get(videoUUID)
525 filesMap.set(segmentName, shaResult)
526 }
527
528 private removeSegmentSha (videoUUID: string, segmentPath: string) {
529 const segmentName = basename(segmentPath)
530
531 logger.debug('Removing live sha segment %s.', segmentPath, lTags(videoUUID))
532
533 const filesMap = this.segmentsSha256.get(videoUUID)
534 if (!filesMap) {
535 logger.warn('Unknown files map to remove sha for %s.', videoUUID, lTags(videoUUID))
536 return
537 }
538
539 if (!filesMap.has(segmentName)) {
540 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath, lTags(videoUUID))
541 return
542 }
543
544 filesMap.delete(segmentName)
545 }
546
547 private isDurationConstraintValid (streamingStartTime: number) {
548 const maxDuration = CONFIG.LIVE.MAX_DURATION
549 // No limit
550 if (maxDuration < 0) return true
551
552 const now = new Date().getTime()
553 const max = streamingStartTime + maxDuration
554
555 return now <= max
556 }
557
558 private hasClientSocketsInBadHealth (sessionId: string) {
559 const rtmpSession = this.getContext().sessions.get(sessionId)
560
561 if (!rtmpSession) {
562 logger.warn('Cannot get session %s to check players socket health.', sessionId, lTags(sessionId))
563 return
564 }
565
566 for (const playerSessionId of rtmpSession.players) {
567 const playerSession = this.getContext().sessions.get(playerSessionId)
568
569 if (!playerSession) {
570 logger.error('Cannot get player session %s to check socket health.', playerSession, lTags(sessionId))
571 continue
572 }
573
574 if (playerSession.socket.writableLength > VIDEO_LIVE.MAX_SOCKET_WAITING_DATA) {
575 return true
576 }
577 }
578
579 return false
580 }
581
582 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
583 if (live.saveReplay !== true) return true
584
585 return this.isAbleToUploadVideoWithCache(user.id)
586 }
587
588 private async updateLiveViews () {
589 if (!this.isRunning()) return
590
591 if (!isTestInstance()) logger.info('Updating live video views.', lTags())
592
593 for (const videoId of this.watchersPerVideo.keys()) {
594 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
595
596 const watchers = this.watchersPerVideo.get(videoId)
597
598 const numWatchers = watchers.length
599
600 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
601 video.views = numWatchers
602 await video.save()
603
604 await federateVideoIfNeeded(video, false)
605
606 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
607
608 // Only keep not expired watchers
609 const newWatchers = watchers.filter(w => w > notBefore)
610 this.watchersPerVideo.set(videoId, newWatchers)
611
612 logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags())
613 }
614 }
615
616 private async handleBrokenLives () {
617 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
618
619 for (const uuid of videoUUIDs) {
620 await this.onEndTransmuxing(uuid, true)
621 }
622 }
623
624 static get Instance () {
625 return this.instance || (this.instance = new this())
626 }
627}
628
629// ---------------------------------------------------------------------------
630
631export {
632 LiveManager
633}