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