]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live-manager.ts
9a2914cc5efecc92ac062561b25d212219e10728
[github/Chocobozzz/PeerTube.git] / server / lib / live-manager.ts
1
2 import { AsyncQueue, queue } from 'async'
3 import * as chokidar from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { ensureDir, stat } from 'fs-extra'
6 import { basename } from 'path'
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, 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 type SegmentSha256QueueParam = {
53 operation: 'update' | 'delete'
54 videoUUID: string
55 segmentPath: string
56 }
57
58 class LiveManager {
59
60 private static instance: LiveManager
61
62 private readonly transSessions = new Map<string, FfmpegCommand>()
63 private readonly videoSessions = new Map<number, string>()
64 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
65 private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>()
66
67 private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
68 return isAbleToUploadVideo(userId, 1000)
69 }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })
70
71 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
72 private rtmpServer: any
73
74 private constructor () {
75 }
76
77 init () {
78 const events = this.getContext().nodeEvent
79 events.on('postPublish', (sessionId: string, streamPath: string) => {
80 logger.debug('RTMP received stream', { id: sessionId, streamPath })
81
82 const splittedPath = streamPath.split('/')
83 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
84 logger.warn('Live path is incorrect.', { streamPath })
85 return this.abortSession(sessionId)
86 }
87
88 this.handleSession(sessionId, streamPath, splittedPath[2])
89 .catch(err => logger.error('Cannot handle sessions.', { err }))
90 })
91
92 events.on('donePublish', sessionId => {
93 logger.info('Live session ended.', { sessionId })
94 })
95
96 this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => {
97 const promise = options.operation === 'update'
98 ? this.addSegmentSha(options)
99 : Promise.resolve(this.removeSegmentSha(options))
100
101 promise.then(() => cb())
102 .catch(err => {
103 logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err })
104 cb()
105 })
106 })
107
108 registerConfigChangedHandler(() => {
109 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
110 this.run()
111 return
112 }
113
114 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
115 this.stop()
116 }
117 })
118 }
119
120 run () {
121 logger.info('Running RTMP server.')
122
123 this.rtmpServer = new NodeRtmpServer(config)
124 this.rtmpServer.run()
125 }
126
127 stop () {
128 logger.info('Stopping RTMP server.')
129
130 this.rtmpServer.stop()
131 this.rtmpServer = undefined
132 }
133
134 getSegmentsSha256 (videoUUID: string) {
135 return this.segmentsSha256.get(videoUUID)
136 }
137
138 stopSessionOf (videoId: number) {
139 const sessionId = this.videoSessions.get(videoId)
140 if (!sessionId) return
141
142 this.videoSessions.delete(videoId)
143 this.abortSession(sessionId)
144 }
145
146 getLiveQuotaUsedByUser (userId: number) {
147 const currentLives = this.livesPerUser.get(userId)
148 if (!currentLives) return 0
149
150 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
151 }
152
153 private getContext () {
154 return context
155 }
156
157 private abortSession (id: string) {
158 const session = this.getContext().sessions.get(id)
159 if (session) {
160 session.stop()
161 this.getContext().sessions.delete(id)
162 }
163
164 const transSession = this.transSessions.get(id)
165 if (transSession) {
166 transSession.kill('SIGINT')
167 this.transSessions.delete(id)
168 }
169 }
170
171 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
172 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
173 if (!videoLive) {
174 logger.warn('Unknown live video with stream key %s.', streamKey)
175 return this.abortSession(sessionId)
176 }
177
178 const video = videoLive.Video
179 if (video.isBlacklisted()) {
180 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
181 return this.abortSession(sessionId)
182 }
183
184 this.videoSessions.set(video.id, sessionId)
185
186 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
187
188 const session = this.getContext().sessions.get(sessionId)
189 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
190
191 const [ resolutionResult, fps ] = await Promise.all([
192 getVideoFileResolution(rtmpUrl),
193 getVideoFileFPS(rtmpUrl)
194 ])
195
196 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
197 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
198 : []
199
200 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
201
202 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
203 videoId: video.id,
204 playlistUrl,
205 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
206 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
207 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
208
209 type: VideoStreamingPlaylistType.HLS
210 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
211
212 return this.runMuxing({
213 sessionId,
214 videoLive,
215 playlist: videoStreamingPlaylist,
216 originalResolution: session.videoHeight,
217 rtmpUrl,
218 fps,
219 resolutionsEnabled
220 })
221 }
222
223 private async runMuxing (options: {
224 sessionId: string
225 videoLive: MVideoLiveVideo
226 playlist: MStreamingPlaylist
227 rtmpUrl: string
228 fps: number
229 resolutionsEnabled: number[]
230 originalResolution: number
231 }) {
232 const { sessionId, videoLive, playlist, resolutionsEnabled, originalResolution, fps, rtmpUrl } = options
233 const startStreamDateTime = new Date().getTime()
234 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
235
236 const user = await UserModel.loadByLiveId(videoLive.id)
237 if (!this.livesPerUser.has(user.id)) {
238 this.livesPerUser.set(user.id, [])
239 }
240
241 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
242 const livesOfUser = this.livesPerUser.get(user.id)
243 livesOfUser.push(currentUserLive)
244
245 for (let i = 0; i < allResolutions.length; i++) {
246 const resolution = allResolutions[i]
247
248 VideoFileModel.upsert({
249 resolution,
250 size: -1,
251 extname: '.ts',
252 infoHash: null,
253 fps,
254 videoStreamingPlaylistId: playlist.id
255 }).catch(err => {
256 logger.error('Cannot create file for live streaming.', { err })
257 })
258 }
259
260 const outPath = getHLSDirectory(videoLive.Video)
261 await ensureDir(outPath)
262
263 const videoUUID = videoLive.Video.uuid
264 const deleteSegments = videoLive.saveReplay === false
265
266 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
267 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
268 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
269
270 logger.info('Running live muxing/transcoding for %s.', videoUUID)
271 this.transSessions.set(sessionId, ffmpegExec)
272
273 const tsWatcher = chokidar.watch(outPath + '/*.ts')
274
275 const updateSegment = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
276
277 const addHandler = segmentPath => {
278 updateSegment(segmentPath)
279
280 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
281 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
282
283 this.stopSessionOf(videoLive.videoId)
284 }
285
286 // Check user quota if the user enabled replay saving
287 if (videoLive.saveReplay === true) {
288 stat(segmentPath)
289 .then(segmentStat => {
290 currentUserLive.size += segmentStat.size
291 })
292 .then(() => this.isQuotaConstraintValid(user, videoLive))
293 .then(quotaValid => {
294 if (quotaValid !== true) {
295 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
296
297 this.stopSessionOf(videoLive.videoId)
298 }
299 })
300 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
301 }
302 }
303
304 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
305
306 tsWatcher.on('add', p => addHandler(p))
307 tsWatcher.on('change', p => updateSegment(p))
308 tsWatcher.on('unlink', p => deleteHandler(p))
309
310 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
311 masterWatcher.on('add', async () => {
312 try {
313 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
314
315 video.state = VideoState.PUBLISHED
316 await video.save()
317 videoLive.Video = video
318
319 await federateVideoIfNeeded(video, false)
320
321 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
322 } catch (err) {
323 logger.error('Cannot federate video %d.', videoLive.videoId, { err })
324 } finally {
325 masterWatcher.close()
326 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
327 }
328 })
329
330 const onFFmpegEnded = () => {
331 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
332
333 this.transSessions.delete(sessionId)
334
335 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
336 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
337
338 this.onEndTransmuxing(videoLive.Video.id)
339 .catch(err => logger.error('Error in closed transmuxing.', { err }))
340 }
341
342 ffmpegExec.on('error', (err, stdout, stderr) => {
343 onFFmpegEnded()
344
345 // Don't care that we killed the ffmpeg process
346 if (err?.message?.includes('Exiting normally')) return
347
348 logger.error('Live transcoding error.', { err, stdout, stderr })
349
350 this.abortSession(sessionId)
351 })
352
353 ffmpegExec.on('end', () => onFFmpegEnded())
354 }
355
356 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
357 try {
358 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
359 if (!fullVideo) return
360
361 JobQueue.Instance.createJob({
362 type: 'video-live-ending',
363 payload: {
364 videoId: fullVideo.id
365 }
366 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
367
368 fullVideo.state = VideoState.LIVE_ENDED
369 await fullVideo.save()
370
371 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
372
373 await federateVideoIfNeeded(fullVideo, false)
374 } catch (err) {
375 logger.error('Cannot save/federate new video state of live streaming.', { err })
376 }
377 }
378
379 private async addSegmentSha (options: SegmentSha256QueueParam) {
380 const segmentName = basename(options.segmentPath)
381 logger.debug('Updating live sha segment %s.', options.segmentPath)
382
383 const shaResult = await buildSha256Segment(options.segmentPath)
384
385 if (!this.segmentsSha256.has(options.videoUUID)) {
386 this.segmentsSha256.set(options.videoUUID, new Map())
387 }
388
389 const filesMap = this.segmentsSha256.get(options.videoUUID)
390 filesMap.set(segmentName, shaResult)
391 }
392
393 private removeSegmentSha (options: SegmentSha256QueueParam) {
394 const segmentName = basename(options.segmentPath)
395
396 logger.debug('Removing live sha segment %s.', options.segmentPath)
397
398 const filesMap = this.segmentsSha256.get(options.videoUUID)
399 if (!filesMap) {
400 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
401 return
402 }
403
404 if (!filesMap.has(segmentName)) {
405 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
406 return
407 }
408
409 filesMap.delete(segmentName)
410 }
411
412 private isDurationConstraintValid (streamingStartTime: number) {
413 const maxDuration = CONFIG.LIVE.MAX_DURATION
414 // No limit
415 if (maxDuration === null) return true
416
417 const now = new Date().getTime()
418 const max = streamingStartTime + maxDuration
419
420 return now <= max
421 }
422
423 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
424 if (live.saveReplay !== true) return true
425
426 return this.isAbleToUploadVideoWithCache(user.id)
427 }
428
429 static get Instance () {
430 return this.instance || (this.instance = new this())
431 }
432 }
433
434 // ---------------------------------------------------------------------------
435
436 export {
437 LiveManager
438 }