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