]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live-manager.ts
2702437c42549b2e6d24822042e4abd7b236ac78
[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 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
103 }
104
105 run () {
106 logger.info('Running RTMP server on port %d', config.rtmp.port)
107
108 this.rtmpServer = new NodeRtmpServer(config)
109 this.rtmpServer.run()
110 }
111
112 stop () {
113 logger.info('Stopping RTMP server.')
114
115 this.rtmpServer.stop()
116 this.rtmpServer = undefined
117 }
118
119 isRunning () {
120 return !!this.rtmpServer
121 }
122
123 getSegmentsSha256 (videoUUID: string) {
124 return this.segmentsSha256.get(videoUUID)
125 }
126
127 stopSessionOf (videoId: number) {
128 const sessionId = this.videoSessions.get(videoId)
129 if (!sessionId) return
130
131 this.videoSessions.delete(videoId)
132 this.abortSession(sessionId)
133 }
134
135 getLiveQuotaUsedByUser (userId: number) {
136 const currentLives = this.livesPerUser.get(userId)
137 if (!currentLives) return 0
138
139 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
140 }
141
142 addViewTo (videoId: number) {
143 if (this.videoSessions.has(videoId) === false) return
144
145 let watchers = this.watchersPerVideo.get(videoId)
146
147 if (!watchers) {
148 watchers = []
149 this.watchersPerVideo.set(videoId, watchers)
150 }
151
152 watchers.push(new Date().getTime())
153 }
154
155 private getContext () {
156 return context
157 }
158
159 private abortSession (id: string) {
160 const session = this.getContext().sessions.get(id)
161 if (session) {
162 session.stop()
163 this.getContext().sessions.delete(id)
164 }
165
166 const transSession = this.transSessions.get(id)
167 if (transSession) {
168 transSession.kill('SIGINT')
169 this.transSessions.delete(id)
170 }
171 }
172
173 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
174 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
175 if (!videoLive) {
176 logger.warn('Unknown live video with stream key %s.', streamKey)
177 return this.abortSession(sessionId)
178 }
179
180 const video = videoLive.Video
181 if (video.isBlacklisted()) {
182 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
183 return this.abortSession(sessionId)
184 }
185
186 this.videoSessions.set(video.id, sessionId)
187
188 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
189
190 const session = this.getContext().sessions.get(sessionId)
191 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
192
193 const [ resolutionResult, fps ] = await Promise.all([
194 getVideoFileResolution(rtmpUrl),
195 getVideoFileFPS(rtmpUrl)
196 ])
197
198 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
199 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
200 : []
201
202 const allResolutions = resolutionsEnabled.concat([ session.videoHeight ])
203
204 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { allResolutions })
205
206 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
207 videoId: video.id,
208 playlistUrl,
209 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
210 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
211 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
212
213 type: VideoStreamingPlaylistType.HLS
214 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
215
216 return this.runMuxing({
217 sessionId,
218 videoLive,
219 playlist: videoStreamingPlaylist,
220 rtmpUrl,
221 fps,
222 allResolutions
223 })
224 }
225
226 private async runMuxing (options: {
227 sessionId: string
228 videoLive: MVideoLiveVideo
229 playlist: MStreamingPlaylist
230 rtmpUrl: string
231 fps: number
232 allResolutions: number[]
233 }) {
234 const { sessionId, videoLive, playlist, allResolutions, fps, rtmpUrl } = options
235 const startStreamDateTime = new Date().getTime()
236
237 const user = await UserModel.loadByLiveId(videoLive.id)
238 if (!this.livesPerUser.has(user.id)) {
239 this.livesPerUser.set(user.id, [])
240 }
241
242 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
243 const livesOfUser = this.livesPerUser.get(user.id)
244 livesOfUser.push(currentUserLive)
245
246 for (let i = 0; i < allResolutions.length; i++) {
247 const resolution = allResolutions[i]
248
249 VideoFileModel.upsert({
250 resolution,
251 size: -1,
252 extname: '.ts',
253 infoHash: null,
254 fps,
255 videoStreamingPlaylistId: playlist.id
256 }).catch(err => {
257 logger.error('Cannot create file for live streaming.', { err })
258 })
259 }
260
261 const outPath = getHLSDirectory(videoLive.Video)
262 await ensureDir(outPath)
263
264 const videoUUID = videoLive.Video.uuid
265 const deleteSegments = videoLive.saveReplay === false
266
267 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
268 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
269 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
270
271 logger.info('Running live muxing/transcoding for %s.', videoUUID)
272 this.transSessions.set(sessionId, ffmpegExec)
273
274 const tsWatcher = chokidar.watch(outPath + '/*.ts')
275
276 const segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
277 const playlistIdMatcher = /^([\d+])-/
278
279 const addHandler = segmentPath => {
280 const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
281 const segmentsToProcess = segmentsToProcessPerPlaylist[playlistId] || []
282
283 // Add sha hash of previous segments, because ffmpeg should have finished generating them
284 for (const previousSegment of segmentsToProcess) {
285 this.addSegmentSha(videoUUID, previousSegment)
286 .catch(err => logger.error('Cannot add sha segment of video %s -> %s.', videoUUID, previousSegment, { err }))
287 }
288
289 segmentsToProcessPerPlaylist[playlistId] = [ segmentPath ]
290
291 // Duration constraint check
292 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
293 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
294
295 this.stopSessionOf(videoLive.videoId)
296 }
297
298 // Check user quota if the user enabled replay saving
299 if (videoLive.saveReplay === true) {
300 stat(segmentPath)
301 .then(segmentStat => {
302 currentUserLive.size += segmentStat.size
303 })
304 .then(() => this.isQuotaConstraintValid(user, videoLive))
305 .then(quotaValid => {
306 if (quotaValid !== true) {
307 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
308
309 this.stopSessionOf(videoLive.videoId)
310 }
311 })
312 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
313 }
314 }
315
316 const deleteHandler = segmentPath => this.removeSegmentSha(videoUUID, segmentPath)
317
318 tsWatcher.on('add', p => addHandler(p))
319 tsWatcher.on('unlink', p => deleteHandler(p))
320
321 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
322 masterWatcher.on('add', async () => {
323 try {
324 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
325
326 video.state = VideoState.PUBLISHED
327 await video.save()
328 videoLive.Video = video
329
330 setTimeout(() => {
331 federateVideoIfNeeded(video, false)
332 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err }))
333
334 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
335 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
336
337 } catch (err) {
338 logger.error('Cannot save/federate live video %d.', videoLive.videoId, { err })
339 } finally {
340 masterWatcher.close()
341 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
342 }
343 })
344
345 const onFFmpegEnded = () => {
346 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
347
348 this.transSessions.delete(sessionId)
349 this.watchersPerVideo.delete(videoLive.videoId)
350
351 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
352 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
353
354 this.onEndTransmuxing(videoLive.Video.id)
355 .catch(err => logger.error('Error in closed transmuxing.', { err }))
356 }
357
358 ffmpegExec.on('error', (err, stdout, stderr) => {
359 onFFmpegEnded()
360
361 // Don't care that we killed the ffmpeg process
362 if (err?.message?.includes('Exiting normally')) return
363
364 logger.error('Live transcoding error.', { err, stdout, stderr })
365
366 this.abortSession(sessionId)
367 })
368
369 ffmpegExec.on('end', () => onFFmpegEnded())
370 }
371
372 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
373 try {
374 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
375 if (!fullVideo) return
376
377 JobQueue.Instance.createJob({
378 type: 'video-live-ending',
379 payload: {
380 videoId: fullVideo.id
381 }
382 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
383
384 fullVideo.state = VideoState.LIVE_ENDED
385 await fullVideo.save()
386
387 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
388
389 await federateVideoIfNeeded(fullVideo, false)
390 } catch (err) {
391 logger.error('Cannot save/federate new video state of live streaming.', { err })
392 }
393 }
394
395 private async addSegmentSha (videoUUID: string, segmentPath: string) {
396 const segmentName = basename(segmentPath)
397 logger.debug('Adding live sha segment %s.', segmentPath)
398
399 const shaResult = await buildSha256Segment(segmentPath)
400
401 if (!this.segmentsSha256.has(videoUUID)) {
402 this.segmentsSha256.set(videoUUID, new Map())
403 }
404
405 const filesMap = this.segmentsSha256.get(videoUUID)
406 filesMap.set(segmentName, shaResult)
407 }
408
409 private removeSegmentSha (videoUUID: string, segmentPath: string) {
410 const segmentName = basename(segmentPath)
411
412 logger.debug('Removing live sha segment %s.', segmentPath)
413
414 const filesMap = this.segmentsSha256.get(videoUUID)
415 if (!filesMap) {
416 logger.warn('Unknown files map to remove sha for %s.', videoUUID)
417 return
418 }
419
420 if (!filesMap.has(segmentName)) {
421 logger.warn('Unknown segment in files map for video %s and segment %s.', videoUUID, segmentPath)
422 return
423 }
424
425 filesMap.delete(segmentName)
426 }
427
428 private isDurationConstraintValid (streamingStartTime: number) {
429 const maxDuration = CONFIG.LIVE.MAX_DURATION
430 // No limit
431 if (maxDuration === null) return true
432
433 const now = new Date().getTime()
434 const max = streamingStartTime + maxDuration
435
436 return now <= max
437 }
438
439 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
440 if (live.saveReplay !== true) return true
441
442 return this.isAbleToUploadVideoWithCache(user.id)
443 }
444
445 private async updateLiveViews () {
446 if (!this.isRunning()) return
447
448 if (!isTestInstance()) logger.info('Updating live video views.')
449
450 for (const videoId of this.watchersPerVideo.keys()) {
451 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
452
453 const watchers = this.watchersPerVideo.get(videoId)
454
455 const numWatchers = watchers.length
456
457 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
458 video.views = numWatchers
459 await video.save()
460
461 await federateVideoIfNeeded(video, false)
462
463 // Only keep not expired watchers
464 const newWatchers = watchers.filter(w => w > notBefore)
465 this.watchersPerVideo.set(videoId, newWatchers)
466
467 logger.debug('New live video views for %s is %d.', video.url, numWatchers)
468 }
469 }
470
471 static get Instance () {
472 return this.instance || (this.instance = new this())
473 }
474 }
475
476 // ---------------------------------------------------------------------------
477
478 export {
479 LiveManager
480 }