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