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