]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live-manager.ts
Add save replay live tests
[github/Chocobozzz/PeerTube.git] / server / lib / live-manager.ts
CommitLineData
c6c0fa6c
C
1
2import { AsyncQueue, queue } from 'async'
3import * as chokidar from 'chokidar'
4import { FfmpegCommand } from 'fluent-ffmpeg'
fb719404 5import { ensureDir, stat } from 'fs-extra'
a5cf76af 6import { basename } from 'path'
68e70a74 7import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution, getVideoStreamCodec, getVideoStreamSize, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
c6c0fa6c
C
8import { logger } from '@server/helpers/logger'
9import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
fb719404
C
10import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
11import { UserModel } from '@server/models/account/user'
a5cf76af 12import { VideoModel } from '@server/models/video/video'
c6c0fa6c
C
13import { VideoFileModel } from '@server/models/video/video-file'
14import { VideoLiveModel } from '@server/models/video/video-live'
15import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
b5b68755 16import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
c6c0fa6c 17import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
a5cf76af 18import { federateVideoIfNeeded } from './activitypub/videos'
c6c0fa6c 19import { buildSha256Segment } from './hls'
a5cf76af
C
20import { JobQueue } from './job-queue'
21import { PeerTubeSocket } from './peertube-socket'
fb719404 22import { isAbleToUploadVideo } from './user'
c6c0fa6c
C
23import { getHLSDirectory } from './video-paths'
24
fb719404 25import memoizee = require('memoizee')
c6c0fa6c
C
26const NodeRtmpServer = require('node-media-server/node_rtmp_server')
27const context = require('node-media-server/node_core_ctx')
28const nodeMediaServerLogger = require('node-media-server/node_core_logger')
29
30// Disable node media server logs
31nodeMediaServerLogger.setLogType(0)
32
33const 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
46type SegmentSha256QueueParam = {
47 operation: 'update' | 'delete'
48 videoUUID: string
49 segmentPath: string
50}
51
52class LiveManager {
53
54 private static instance: LiveManager
55
56 private readonly transSessions = new Map<string, FfmpegCommand>()
a5cf76af 57 private readonly videoSessions = new Map<number, string>()
c6c0fa6c 58 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
fb719404
C
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 })
c6c0fa6c
C
64
65 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
66 private rtmpServer: any
67
68 private constructor () {
69 }
70
71 init () {
a5cf76af
C
72 const events = this.getContext().nodeEvent
73 events.on('postPublish', (sessionId: string, streamPath: string) => {
c6c0fa6c
C
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
a5cf76af 86 events.on('donePublish', sessionId => {
284ef529 87 logger.info('Live session ended.', { sessionId })
c6c0fa6c
C
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
a5cf76af
C
132 stopSessionOf (videoId: number) {
133 const sessionId = this.videoSessions.get(videoId)
134 if (!sessionId) return
135
97969c4e 136 this.videoSessions.delete(videoId)
a5cf76af 137 this.abortSession(sessionId)
a5cf76af
C
138 }
139
68e70a74
C
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
c6c0fa6c
C
147 private getContext () {
148 return context
149 }
150
151 private abortSession (id: string) {
152 const session = this.getContext().sessions.get(id)
284ef529
C
153 if (session) {
154 session.stop()
155 this.getContext().sessions.delete(id)
156 }
c6c0fa6c
C
157
158 const transSession = this.transSessions.get(id)
284ef529
C
159 if (transSession) {
160 transSession.kill('SIGINT')
161 this.transSessions.delete(id)
162 }
c6c0fa6c
C
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
a5cf76af
C
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
c6c0fa6c
C
180 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
181
182 const session = this.getContext().sessions.get(sessionId)
68e70a74
C
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
c6c0fa6c 190 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
68e70a74 191 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
c6c0fa6c
C
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
c6c0fa6c
C
206 return this.runMuxing({
207 sessionId,
208 videoLive,
209 playlist: videoStreamingPlaylist,
c6c0fa6c 210 originalResolution: session.videoHeight,
68e70a74
C
211 rtmpUrl,
212 fps,
c6c0fa6c
C
213 resolutionsEnabled
214 })
215 }
216
217 private async runMuxing (options: {
218 sessionId: string
219 videoLive: MVideoLiveVideo
220 playlist: MStreamingPlaylist
68e70a74
C
221 rtmpUrl: string
222 fps: number
c6c0fa6c
C
223 resolutionsEnabled: number[]
224 originalResolution: number
225 }) {
68e70a74 226 const { sessionId, videoLive, playlist, resolutionsEnabled, originalResolution, fps, rtmpUrl } = options
fb719404 227 const startStreamDateTime = new Date().getTime()
c6c0fa6c
C
228 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
229
fb719404
C
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
c6c0fa6c
C
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
68e70a74 257 const videoUUID = videoLive.Video.uuid
fb719404
C
258 const deleteSegments = videoLive.saveReplay === false
259
c6c0fa6c 260 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
68e70a74 261 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
fb719404 262 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
c6c0fa6c 263
68e70a74 264 logger.info('Running live muxing/transcoding for %s.', videoUUID)
c6c0fa6c
C
265 this.transSessions.set(sessionId, ffmpegExec)
266
a5cf76af
C
267 const tsWatcher = chokidar.watch(outPath + '/*.ts')
268
fb719404
C
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) {
97969c4e
C
275 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
276
fb719404
C
277 this.stopSessionOf(videoLive.videoId)
278 }
279
97969c4e 280 // Check user quota if the user enabled replay saving
fb719404
C
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) {
97969c4e
C
289 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
290
fb719404
C
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 }
a5cf76af
C
296 }
297
298 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
299
fb719404
C
300 tsWatcher.on('add', p => addHandler(p))
301 tsWatcher.on('change', p => updateSegment(p))
a5cf76af
C
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
c6c0fa6c 324 const onFFmpegEnded = () => {
68e70a74 325 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
c6c0fa6c 326
284ef529
C
327 this.transSessions.delete(sessionId)
328
a5cf76af
C
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)
c6c0fa6c
C
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
97969c4e 340 if (err?.message?.includes('Exiting normally')) return
c6c0fa6c
C
341
342 logger.error('Live transcoding error.', { err, stdout, stderr })
77e9f859
C
343
344 this.abortSession(sessionId)
c6c0fa6c
C
345 })
346
347 ffmpegExec.on('end', () => onFFmpegEnded())
c6c0fa6c
C
348 }
349
fb719404 350 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
a5cf76af
C
351 try {
352 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
353 if (!fullVideo) return
c6c0fa6c 354
a5cf76af
C
355 JobQueue.Instance.createJob({
356 type: 'video-live-ending',
357 payload: {
358 videoId: fullVideo.id
359 }
fb719404 360 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
c6c0fa6c 361
97969c4e 362 fullVideo.state = VideoState.LIVE_ENDED
a5cf76af 363 await fullVideo.save()
c6c0fa6c 364
a5cf76af 365 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
c6c0fa6c 366
a5cf76af
C
367 await federateVideoIfNeeded(fullVideo, false)
368 } catch (err) {
369 logger.error('Cannot save/federate new video state of live streaming.', { err })
370 }
c6c0fa6c
C
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
fb719404
C
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
c6c0fa6c
C
423 static get Instance () {
424 return this.instance || (this.instance = new this())
425 }
426}
427
428// ---------------------------------------------------------------------------
429
430export {
431 LiveManager
432}