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