]>
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 | ||
0d8de275 | 290 | const file = new VideoFileModel({ |
c6c0fa6c C |
291 | resolution, |
292 | size: -1, | |
293 | extname: '.ts', | |
294 | infoHash: null, | |
bd54ad19 | 295 | fps, |
c6c0fa6c | 296 | videoStreamingPlaylistId: playlist.id |
c6c0fa6c | 297 | }) |
0d8de275 C |
298 | |
299 | VideoFileModel.customUpsert(file, 'streaming-playlist', null) | |
300 | .catch(err => logger.error('Cannot create file for live streaming.', { err })) | |
c6c0fa6c C |
301 | } |
302 | ||
303 | const outPath = getHLSDirectory(videoLive.Video) | |
304 | await ensureDir(outPath) | |
305 | ||
937581b8 C |
306 | const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY) |
307 | ||
308 | if (videoLive.saveReplay === true) { | |
309 | await ensureDir(replayDirectory) | |
310 | } | |
311 | ||
68e70a74 | 312 | const videoUUID = videoLive.Video.uuid |
fb719404 | 313 | |
c6c0fa6c | 314 | const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED |
5a547f69 C |
315 | ? await getLiveTranscodingCommand({ |
316 | rtmpUrl, | |
317 | outPath, | |
33ff70ba | 318 | resolutions: allResolutions, |
5a547f69 | 319 | fps, |
5a547f69 C |
320 | availableEncoders, |
321 | profile: 'default' | |
322 | }) | |
937581b8 | 323 | : getLiveMuxingCommand(rtmpUrl, outPath) |
c6c0fa6c | 324 | |
68e70a74 | 325 | logger.info('Running live muxing/transcoding for %s.', videoUUID) |
c6c0fa6c C |
326 | this.transSessions.set(sessionId, ffmpegExec) |
327 | ||
a5cf76af C |
328 | const tsWatcher = chokidar.watch(outPath + '/*.ts') |
329 | ||
786b855a C |
330 | const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {} |
331 | const playlistIdMatcher = /^([\d+])-/ | |
fb719404 | 332 | |
6bff8ce2 C |
333 | const addHandler = segmentPath => { |
334 | logger.debug('Live add handler of %s.', segmentPath) | |
335 | ||
336 | const playlistId = basename(segmentPath).match(playlistIdMatcher)[0] | |
337 | ||
338 | const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || [] | |
3851e732 | 339 | this.processSegments(outPath, videoUUID, videoLive, segmentsToProcess) |
210856a7 | 340 | |
786b855a | 341 | segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ] |
fb719404 | 342 | |
210856a7 | 343 | // Duration constraint check |
fb719404 | 344 | if (this.isDurationConstraintValid(startStreamDateTime) !== true) { |
97969c4e C |
345 | logger.info('Stopping session of %s: max duration exceeded.', videoUUID) |
346 | ||
fb719404 C |
347 | this.stopSessionOf(videoLive.videoId) |
348 | } | |
349 | ||
97969c4e | 350 | // Check user quota if the user enabled replay saving |
fb719404 C |
351 | if (videoLive.saveReplay === true) { |
352 | stat(segmentPath) | |
353 | .then(segmentStat => { | |
354 | currentUserLive.size += segmentStat.size | |
355 | }) | |
356 | .then(() => this.isQuotaConstraintValid(user, videoLive)) | |
357 | .then(quotaValid => { | |
358 | if (quotaValid !== true) { | |
97969c4e C |
359 | logger.info('Stopping session of %s: user quota exceeded.', videoUUID) |
360 | ||
fb719404 C |
361 | this.stopSessionOf(videoLive.videoId) |
362 | } | |
363 | }) | |
364 | .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err })) | |
365 | } | |
a5cf76af C |
366 | } |
367 | ||
210856a7 | 368 | const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath) |
a5cf76af | 369 | |
fb719404 | 370 | tsWatcher.on('add', p => addHandler(p)) |
a5cf76af C |
371 | tsWatcher.on('unlink', p => deleteHandler(p)) |
372 | ||
373 | const masterWatcher = chokidar.watch(outPath + '/master.m3u8') | |
374 | masterWatcher.on('add', async () => { | |
375 | try { | |
376 | const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId) | |
377 | ||
378 | video.state = VideoState.PUBLISHED | |
379 | await video.save() | |
380 | videoLive.Video = video | |
381 | ||
501af82d C |
382 | setTimeout(() => { |
383 | federateVideoIfNeeded(video, false) | |
384 | .catch(err => logger.error('Cannot federate live video %s.', video.url, { err })) | |
385 | ||
386 | PeerTubeSocket.Instance.sendVideoLiveNewState(video) | |
387 | }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION) | |
a5cf76af | 388 | |
a5cf76af | 389 | } catch (err) { |
501af82d | 390 | logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err }) |
a5cf76af C |
391 | } finally { |
392 | masterWatcher.close() | |
393 | .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err })) | |
394 | } | |
395 | }) | |
396 | ||
c6c0fa6c | 397 | const onFFmpegEnded = () => { |
68e70a74 | 398 | logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl) |
c6c0fa6c | 399 | |
284ef529 | 400 | this.transSessions.delete(sessionId) |
bb4ba6d9 | 401 | |
e4bf7856 | 402 | this.watchersPerVideo.delete(videoLive.videoId) |
bb4ba6d9 C |
403 | this.videoSessions.delete(videoLive.videoId) |
404 | ||
405 | const newLivesPerUser = this.livesPerUser.get(user.id) | |
406 | .filter(o => o.liveId !== videoLive.id) | |
407 | this.livesPerUser.set(user.id, newLivesPerUser) | |
284ef529 | 408 | |
6bff8ce2 C |
409 | setTimeout(() => { |
410 | // Wait latest segments generation, and close watchers | |
411 | ||
412 | Promise.all([ tsWatcher.close(), masterWatcher.close() ]) | |
8c666c44 C |
413 | .then(() => { |
414 | // Process remaining segments hash | |
415 | for (const key of Object.keys(segmentsToProcessPerPlaylist)) { | |
3851e732 | 416 | this.processSegments(outPath, videoUUID, videoLive, segmentsToProcessPerPlaylist[key]) |
8c666c44 C |
417 | } |
418 | }) | |
419 | .catch(err => logger.error('Cannot close watchers of %s or process remaining hash segments.', outPath, { err })) | |
6bff8ce2 C |
420 | |
421 | this.onEndTransmuxing(videoLive.Video.id) | |
422 | .catch(err => logger.error('Error in closed transmuxing.', { err })) | |
423 | }, 1000) | |
c6c0fa6c C |
424 | } |
425 | ||
426 | ffmpegExec.on('error', (err, stdout, stderr) => { | |
427 | onFFmpegEnded() | |
428 | ||
429 | // Don't care that we killed the ffmpeg process | |
97969c4e | 430 | if (err?.message?.includes('Exiting normally')) return |
c6c0fa6c C |
431 | |
432 | logger.error('Live transcoding error.', { err, stdout, stderr }) | |
77e9f859 C |
433 | |
434 | this.abortSession(sessionId) | |
c6c0fa6c C |
435 | }) |
436 | ||
437 | ffmpegExec.on('end', () => onFFmpegEnded()) | |
9252a33d C |
438 | |
439 | ffmpegExec.run() | |
c6c0fa6c C |
440 | } |
441 | ||
fb719404 | 442 | private async onEndTransmuxing (videoId: number, cleanupNow = false) { |
a5cf76af C |
443 | try { |
444 | const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) | |
445 | if (!fullVideo) return | |
c6c0fa6c | 446 | |
bb4ba6d9 C |
447 | const live = await VideoLiveModel.loadByVideoId(videoId) |
448 | ||
449 | if (!live.permanentLive) { | |
450 | JobQueue.Instance.createJob({ | |
451 | type: 'video-live-ending', | |
452 | payload: { | |
453 | videoId: fullVideo.id | |
454 | } | |
455 | }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY }) | |
456 | ||
457 | fullVideo.state = VideoState.LIVE_ENDED | |
458 | } else { | |
459 | fullVideo.state = VideoState.WAITING_FOR_LIVE | |
460 | } | |
c6c0fa6c | 461 | |
a5cf76af | 462 | await fullVideo.save() |
c6c0fa6c | 463 | |
a5cf76af | 464 | PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) |
c6c0fa6c | 465 | |
a5cf76af C |
466 | await federateVideoIfNeeded(fullVideo, false) |
467 | } catch (err) { | |
468 | logger.error('Cannot save/federate new video state of live streaming.', { err }) | |
469 | } | |
c6c0fa6c C |
470 | } |
471 | ||
210856a7 C |
472 | private async addSegmentSha (videoUUID: string, segmentPath: string) { |
473 | const segmentName = basename(segmentPath) | |
474 | logger.debug('Adding live sha segment %s.', segmentPath) | |
c6c0fa6c | 475 | |
210856a7 | 476 | const shaResult = await buildSha256Segment(segmentPath) |
c6c0fa6c | 477 | |
210856a7 C |
478 | if (!this.segmentsSha256.has(videoUUID)) { |
479 | this.segmentsSha256.set(videoUUID, new Map()) | |
c6c0fa6c C |
480 | } |
481 | ||
210856a7 | 482 | const filesMap = this.segmentsSha256.get(videoUUID) |
c6c0fa6c C |
483 | filesMap.set(segmentName, shaResult) |
484 | } | |
485 | ||
210856a7 C |
486 | private removeSegmentSha (videoUUID: string, segmentPath: string) { |
487 | const segmentName = basename(segmentPath) | |
c6c0fa6c | 488 | |
210856a7 | 489 | logger.debug('Removing live sha segment %s.', segmentPath) |
c6c0fa6c | 490 | |
210856a7 | 491 | const filesMap = this.segmentsSha256.get(videoUUID) |
c6c0fa6c | 492 | if (!filesMap) { |
210856a7 | 493 | logger.warn('Unknown files map to remove sha for %s.', videoUUID) |
c6c0fa6c C |
494 | return |
495 | } | |
496 | ||
497 | if (!filesMap.has(segmentName)) { | |
210856a7 | 498 | logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath) |
c6c0fa6c C |
499 | return |
500 | } | |
501 | ||
502 | filesMap.delete(segmentName) | |
503 | } | |
504 | ||
fb719404 C |
505 | private isDurationConstraintValid (streamingStartTime: number) { |
506 | const maxDuration = CONFIG.LIVE.MAX_DURATION | |
507 | // No limit | |
c9bc850e | 508 | if (maxDuration < 0) return true |
fb719404 C |
509 | |
510 | const now = new Date().getTime() | |
511 | const max = streamingStartTime + maxDuration | |
512 | ||
513 | return now <= max | |
514 | } | |
515 | ||
516 | private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) { | |
517 | if (live.saveReplay !== true) return true | |
518 | ||
519 | return this.isAbleToUploadVideoWithCache(user.id) | |
520 | } | |
521 | ||
e4bf7856 C |
522 | private async updateLiveViews () { |
523 | if (!this.isRunning()) return | |
524 | ||
c655c9ef | 525 | if (!isTestInstance()) logger.info('Updating live video views.') |
e4bf7856 C |
526 | |
527 | for (const videoId of this.watchersPerVideo.keys()) { | |
528 | const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE | |
529 | ||
530 | const watchers = this.watchersPerVideo.get(videoId) | |
531 | ||
532 | const numWatchers = watchers.length | |
533 | ||
534 | const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) | |
535 | video.views = numWatchers | |
536 | await video.save() | |
537 | ||
538 | await federateVideoIfNeeded(video, false) | |
539 | ||
a800dbf3 C |
540 | PeerTubeSocket.Instance.sendVideoViewsUpdate(video) |
541 | ||
e4bf7856 C |
542 | // Only keep not expired watchers |
543 | const newWatchers = watchers.filter(w => w > notBefore) | |
544 | this.watchersPerVideo.set(videoId, newWatchers) | |
545 | ||
546 | logger.debug('New live video views for %s is %d.', video.url, numWatchers) | |
547 | } | |
548 | } | |
549 | ||
5c0904fc C |
550 | private async handleBrokenLives () { |
551 | const videoIds = await VideoModel.listPublishedLiveIds() | |
552 | ||
553 | for (const id of videoIds) { | |
554 | await this.onEndTransmuxing(id, true) | |
555 | } | |
556 | } | |
557 | ||
c6c0fa6c C |
558 | static get Instance () { |
559 | return this.instance || (this.instance = new this()) | |
560 | } | |
561 | } | |
562 | ||
563 | // --------------------------------------------------------------------------- | |
564 | ||
565 | export { | |
566 | LiveManager | |
567 | } |