]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live-manager.ts
Add check constraints 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'
c6c0fa6c
C
7import { computeResolutionsToTranscode, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
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
c6c0fa6c
C
140 private getContext () {
141 return context
142 }
143
144 private abortSession (id: string) {
145 const session = this.getContext().sessions.get(id)
284ef529
C
146 if (session) {
147 session.stop()
148 this.getContext().sessions.delete(id)
149 }
c6c0fa6c
C
150
151 const transSession = this.transSessions.get(id)
284ef529
C
152 if (transSession) {
153 transSession.kill('SIGINT')
154 this.transSessions.delete(id)
155 }
c6c0fa6c
C
156 }
157
158 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
159 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
160 if (!videoLive) {
161 logger.warn('Unknown live video with stream key %s.', streamKey)
162 return this.abortSession(sessionId)
163 }
164
165 const video = videoLive.Video
a5cf76af
C
166 if (video.isBlacklisted()) {
167 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
168 return this.abortSession(sessionId)
169 }
170
171 this.videoSessions.set(video.id, sessionId)
172
c6c0fa6c
C
173 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
174
175 const session = this.getContext().sessions.get(sessionId)
176 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
177 ? computeResolutionsToTranscode(session.videoHeight, 'live')
178 : []
179
180 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
181
182 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
183 videoId: video.id,
184 playlistUrl,
185 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
186 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
187 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
188
189 type: VideoStreamingPlaylistType.HLS
190 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
191
c6c0fa6c
C
192 return this.runMuxing({
193 sessionId,
194 videoLive,
195 playlist: videoStreamingPlaylist,
196 streamPath,
197 originalResolution: session.videoHeight,
198 resolutionsEnabled
199 })
200 }
201
202 private async runMuxing (options: {
203 sessionId: string
204 videoLive: MVideoLiveVideo
205 playlist: MStreamingPlaylist
206 streamPath: string
207 resolutionsEnabled: number[]
208 originalResolution: number
209 }) {
210 const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options
fb719404 211 const startStreamDateTime = new Date().getTime()
c6c0fa6c
C
212 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
213
fb719404
C
214 const user = await UserModel.loadByLiveId(videoLive.id)
215 if (!this.livesPerUser.has(user.id)) {
216 this.livesPerUser.set(user.id, [])
217 }
218
219 const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 }
220 const livesOfUser = this.livesPerUser.get(user.id)
221 livesOfUser.push(currentUserLive)
222
c6c0fa6c
C
223 for (let i = 0; i < allResolutions.length; i++) {
224 const resolution = allResolutions[i]
225
226 VideoFileModel.upsert({
227 resolution,
228 size: -1,
229 extname: '.ts',
230 infoHash: null,
231 fps: -1,
232 videoStreamingPlaylistId: playlist.id
233 }).catch(err => {
234 logger.error('Cannot create file for live streaming.', { err })
235 })
236 }
237
238 const outPath = getHLSDirectory(videoLive.Video)
239 await ensureDir(outPath)
240
fb719404
C
241 const deleteSegments = videoLive.saveReplay === false
242
c6c0fa6c
C
243 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
244 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
fb719404
C
245 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, deleteSegments)
246 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
c6c0fa6c
C
247
248 logger.info('Running live muxing/transcoding.')
c6c0fa6c
C
249 this.transSessions.set(sessionId, ffmpegExec)
250
a5cf76af
C
251 const videoUUID = videoLive.Video.uuid
252 const tsWatcher = chokidar.watch(outPath + '/*.ts')
253
fb719404
C
254 const updateSegment = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
255
256 const addHandler = segmentPath => {
257 updateSegment(segmentPath)
258
259 if (this.isDurationConstraintValid(startStreamDateTime) !== true) {
97969c4e
C
260 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
261
fb719404
C
262 this.stopSessionOf(videoLive.videoId)
263 }
264
97969c4e 265 // Check user quota if the user enabled replay saving
fb719404
C
266 if (videoLive.saveReplay === true) {
267 stat(segmentPath)
268 .then(segmentStat => {
269 currentUserLive.size += segmentStat.size
270 })
271 .then(() => this.isQuotaConstraintValid(user, videoLive))
272 .then(quotaValid => {
273 if (quotaValid !== true) {
97969c4e
C
274 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
275
fb719404
C
276 this.stopSessionOf(videoLive.videoId)
277 }
278 })
279 .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err }))
280 }
a5cf76af
C
281 }
282
283 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
284
fb719404
C
285 tsWatcher.on('add', p => addHandler(p))
286 tsWatcher.on('change', p => updateSegment(p))
a5cf76af
C
287 tsWatcher.on('unlink', p => deleteHandler(p))
288
289 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
290 masterWatcher.on('add', async () => {
291 try {
292 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
293
294 video.state = VideoState.PUBLISHED
295 await video.save()
296 videoLive.Video = video
297
298 await federateVideoIfNeeded(video, false)
299
300 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
301 } catch (err) {
302 logger.error('Cannot federate video %d.', videoLive.videoId, { err })
303 } finally {
304 masterWatcher.close()
305 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
306 }
307 })
308
c6c0fa6c 309 const onFFmpegEnded = () => {
a5cf76af 310 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', streamPath)
c6c0fa6c 311
284ef529
C
312 this.transSessions.delete(sessionId)
313
a5cf76af
C
314 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
315 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
316
317 this.onEndTransmuxing(videoLive.Video.id)
c6c0fa6c
C
318 .catch(err => logger.error('Error in closed transmuxing.', { err }))
319 }
320
321 ffmpegExec.on('error', (err, stdout, stderr) => {
322 onFFmpegEnded()
323
324 // Don't care that we killed the ffmpeg process
97969c4e 325 if (err?.message?.includes('Exiting normally')) return
c6c0fa6c
C
326
327 logger.error('Live transcoding error.', { err, stdout, stderr })
77e9f859
C
328
329 this.abortSession(sessionId)
c6c0fa6c
C
330 })
331
332 ffmpegExec.on('end', () => onFFmpegEnded())
c6c0fa6c
C
333 }
334
fb719404
C
335 getLiveQuotaUsedByUser (userId: number) {
336 const currentLives = this.livesPerUser.get(userId)
337 if (!currentLives) return 0
338
339 return currentLives.reduce((sum, obj) => sum + obj.size, 0)
340 }
341
342 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
a5cf76af
C
343 try {
344 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
345 if (!fullVideo) return
c6c0fa6c 346
a5cf76af
C
347 JobQueue.Instance.createJob({
348 type: 'video-live-ending',
349 payload: {
350 videoId: fullVideo.id
351 }
fb719404 352 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
c6c0fa6c 353
97969c4e 354 fullVideo.state = VideoState.LIVE_ENDED
a5cf76af 355 await fullVideo.save()
c6c0fa6c 356
a5cf76af 357 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
c6c0fa6c 358
a5cf76af
C
359 await federateVideoIfNeeded(fullVideo, false)
360 } catch (err) {
361 logger.error('Cannot save/federate new video state of live streaming.', { err })
362 }
c6c0fa6c
C
363 }
364
365 private async addSegmentSha (options: SegmentSha256QueueParam) {
366 const segmentName = basename(options.segmentPath)
367 logger.debug('Updating live sha segment %s.', options.segmentPath)
368
369 const shaResult = await buildSha256Segment(options.segmentPath)
370
371 if (!this.segmentsSha256.has(options.videoUUID)) {
372 this.segmentsSha256.set(options.videoUUID, new Map())
373 }
374
375 const filesMap = this.segmentsSha256.get(options.videoUUID)
376 filesMap.set(segmentName, shaResult)
377 }
378
379 private removeSegmentSha (options: SegmentSha256QueueParam) {
380 const segmentName = basename(options.segmentPath)
381
382 logger.debug('Removing live sha segment %s.', options.segmentPath)
383
384 const filesMap = this.segmentsSha256.get(options.videoUUID)
385 if (!filesMap) {
386 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
387 return
388 }
389
390 if (!filesMap.has(segmentName)) {
391 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
392 return
393 }
394
395 filesMap.delete(segmentName)
396 }
397
fb719404
C
398 private isDurationConstraintValid (streamingStartTime: number) {
399 const maxDuration = CONFIG.LIVE.MAX_DURATION
400 // No limit
401 if (maxDuration === null) return true
402
403 const now = new Date().getTime()
404 const max = streamingStartTime + maxDuration
405
406 return now <= max
407 }
408
409 private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) {
410 if (live.saveReplay !== true) return true
411
412 return this.isAbleToUploadVideoWithCache(user.id)
413 }
414
c6c0fa6c
C
415 static get Instance () {
416 return this.instance || (this.instance = new this())
417 }
418}
419
420// ---------------------------------------------------------------------------
421
422export {
423 LiveManager
424}