]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live-manager.ts
Revert some mistakes
[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'
053aed43
C
7import {
8 computeResolutionsToTranscode,
9 getVideoFileFPS,
10 getVideoFileResolution,
11 runLiveMuxing,
12 runLiveTranscoding
13} from '@server/helpers/ffmpeg-utils'
c6c0fa6c
C
14import { logger } from '@server/helpers/logger'
15import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
fb719404
C
16import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
17import { UserModel } from '@server/models/account/user'
a5cf76af 18import { VideoModel } from '@server/models/video/video'
c6c0fa6c
C
19import { VideoFileModel } from '@server/models/video/video-file'
20import { VideoLiveModel } from '@server/models/video/video-live'
21import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
b5b68755 22import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models'
c6c0fa6c 23import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
a5cf76af 24import { federateVideoIfNeeded } from './activitypub/videos'
c6c0fa6c 25import { buildSha256Segment } from './hls'
a5cf76af
C
26import { JobQueue } from './job-queue'
27import { PeerTubeSocket } from './peertube-socket'
fb719404 28import { isAbleToUploadVideo } from './user'
c6c0fa6c
C
29import { getHLSDirectory } from './video-paths'
30
fb719404 31import memoizee = require('memoizee')
c6c0fa6c
C
32const NodeRtmpServer = require('node-media-server/node_rtmp_server')
33const context = require('node-media-server/node_core_ctx')
34const nodeMediaServerLogger = require('node-media-server/node_core_logger')
35
36// Disable node media server logs
37nodeMediaServerLogger.setLogType(0)
38
39const 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
52type SegmentSha256QueueParam = {
53 operation: 'update' | 'delete'
54 videoUUID: string
55 segmentPath: string
56}
57
58class LiveManager {
59
60 private static instance: LiveManager
61
62 private readonly transSessions = new Map<string, FfmpegCommand>()
a5cf76af 63 private readonly videoSessions = new Map<number, string>()
c6c0fa6c 64 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
fb719404
C
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 })
c6c0fa6c
C
70
71 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
72 private rtmpServer: any
73
74 private constructor () {
75 }
76
77 init () {
a5cf76af
C
78 const events = this.getContext().nodeEvent
79 events.on('postPublish', (sessionId: string, streamPath: string) => {
c6c0fa6c
C
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
a5cf76af 92 events.on('donePublish', sessionId => {
284ef529 93 logger.info('Live session ended.', { sessionId })
c6c0fa6c
C
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 () {
3cabf353 121 logger.info('Running RTMP server on port %d', config.rtmp.port)
c6c0fa6c
C
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
a5cf76af
C
138 stopSessionOf (videoId: number) {
139 const sessionId = this.videoSessions.get(videoId)
140 if (!sessionId) return
141
97969c4e 142 this.videoSessions.delete(videoId)
a5cf76af 143 this.abortSession(sessionId)
a5cf76af
C
144 }
145
68e70a74
C
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
c6c0fa6c
C
153 private getContext () {
154 return context
155 }
156
157 private abortSession (id: string) {
158 const session = this.getContext().sessions.get(id)
284ef529
C
159 if (session) {
160 session.stop()
161 this.getContext().sessions.delete(id)
162 }
c6c0fa6c
C
163
164 const transSession = this.transSessions.get(id)
284ef529
C
165 if (transSession) {
166 transSession.kill('SIGINT')
167 this.transSessions.delete(id)
168 }
c6c0fa6c
C
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
a5cf76af
C
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
c6c0fa6c
C
186 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
187
188 const session = this.getContext().sessions.get(sessionId)
68e70a74
C
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
c6c0fa6c 196 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
68e70a74 197 ? computeResolutionsToTranscode(resolutionResult.videoFileResolution, 'live')
c6c0fa6c
C
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
c6c0fa6c
C
212 return this.runMuxing({
213 sessionId,
214 videoLive,
215 playlist: videoStreamingPlaylist,
c6c0fa6c 216 originalResolution: session.videoHeight,
68e70a74
C
217 rtmpUrl,
218 fps,
c6c0fa6c
C
219 resolutionsEnabled
220 })
221 }
222
223 private async runMuxing (options: {
224 sessionId: string
225 videoLive: MVideoLiveVideo
226 playlist: MStreamingPlaylist
68e70a74
C
227 rtmpUrl: string
228 fps: number
c6c0fa6c
C
229 resolutionsEnabled: number[]
230 originalResolution: number
231 }) {
68e70a74 232 const { sessionId, videoLive, playlist, resolutionsEnabled, originalResolution, fps, rtmpUrl } = options
fb719404 233 const startStreamDateTime = new Date().getTime()
c6c0fa6c
C
234 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
235
fb719404
C
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
c6c0fa6c
C
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,
bd54ad19 253 fps,
c6c0fa6c
C
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
68e70a74 263 const videoUUID = videoLive.Video.uuid
fb719404
C
264 const deleteSegments = videoLive.saveReplay === false
265
c6c0fa6c 266 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
68e70a74 267 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments)
fb719404 268 : runLiveMuxing(rtmpUrl, outPath, deleteSegments)
c6c0fa6c 269
68e70a74 270 logger.info('Running live muxing/transcoding for %s.', videoUUID)
c6c0fa6c
C
271 this.transSessions.set(sessionId, ffmpegExec)
272
a5cf76af
C
273 const tsWatcher = chokidar.watch(outPath + '/*.ts')
274
fb719404
C
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) {
97969c4e
C
281 logger.info('Stopping session of %s: max duration exceeded.', videoUUID)
282
fb719404
C
283 this.stopSessionOf(videoLive.videoId)
284 }
285
97969c4e 286 // Check user quota if the user enabled replay saving
fb719404
C
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) {
97969c4e
C
295 logger.info('Stopping session of %s: user quota exceeded.', videoUUID)
296
fb719404
C
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 }
a5cf76af
C
302 }
303
304 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
305
fb719404
C
306 tsWatcher.on('add', p => addHandler(p))
307 tsWatcher.on('change', p => updateSegment(p))
a5cf76af
C
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
c6c0fa6c 330 const onFFmpegEnded = () => {
68e70a74 331 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', rtmpUrl)
c6c0fa6c 332
284ef529
C
333 this.transSessions.delete(sessionId)
334
a5cf76af
C
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)
c6c0fa6c
C
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
97969c4e 346 if (err?.message?.includes('Exiting normally')) return
c6c0fa6c
C
347
348 logger.error('Live transcoding error.', { err, stdout, stderr })
77e9f859
C
349
350 this.abortSession(sessionId)
c6c0fa6c
C
351 })
352
353 ffmpegExec.on('end', () => onFFmpegEnded())
c6c0fa6c
C
354 }
355
fb719404 356 private async onEndTransmuxing (videoId: number, cleanupNow = false) {
a5cf76af
C
357 try {
358 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
359 if (!fullVideo) return
c6c0fa6c 360
a5cf76af
C
361 JobQueue.Instance.createJob({
362 type: 'video-live-ending',
363 payload: {
364 videoId: fullVideo.id
365 }
fb719404 366 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
c6c0fa6c 367
97969c4e 368 fullVideo.state = VideoState.LIVE_ENDED
a5cf76af 369 await fullVideo.save()
c6c0fa6c 370
a5cf76af 371 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
c6c0fa6c 372
a5cf76af
C
373 await federateVideoIfNeeded(fullVideo, false)
374 } catch (err) {
375 logger.error('Cannot save/federate new video state of live streaming.', { err })
376 }
c6c0fa6c
C
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
fb719404
C
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
c6c0fa6c
C
429 static get Instance () {
430 return this.instance || (this.instance = new this())
431 }
432}
433
434// ---------------------------------------------------------------------------
435
436export {
437 LiveManager
438}