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