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