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