]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live/live-manager.ts
Limit live bitrate
[github/Chocobozzz/PeerTube.git] / server / lib / live / live-manager.ts
CommitLineData
8ebf2a5d
C
1
2import { createServer, Server } from 'net'
3import { isTestInstance } from '@server/helpers/core-utils'
c826f34a
C
4import {
5 computeResolutionsToTranscode,
6 ffprobePromise,
7 getVideoFileBitrate,
8 getVideoFileFPS,
9 getVideoFileResolution
10} from '@server/helpers/ffprobe-utils'
8ebf2a5d
C
11import { logger, loggerTagsFactory } from '@server/helpers/logger'
12import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
764b1a14 13import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME } from '@server/initializers/constants'
8ebf2a5d
C
14import { UserModel } from '@server/models/user/user'
15import { VideoModel } from '@server/models/video/video'
16import { VideoLiveModel } from '@server/models/video/video-live'
17import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
764b1a14 18import { MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models'
8ebf2a5d
C
19import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
20import { federateVideoIfNeeded } from '../activitypub/videos'
21import { JobQueue } from '../job-queue'
22import { PeerTubeSocket } from '../peertube-socket'
764b1a14 23import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../video-paths'
8ebf2a5d
C
24import { LiveQuotaStore } from './live-quota-store'
25import { LiveSegmentShaStore } from './live-segment-sha-store'
26import { cleanupLive } from './live-utils'
27import { MuxingSession } from './shared'
28
7a397c7f
C
29const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
30const context = require('node-media-server/src/node_core_ctx')
31const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
8ebf2a5d
C
32
33// Disable node media server logs
34nodeMediaServerLogger.setLogType(0)
35
36const config = {
37 rtmp: {
38 port: CONFIG.LIVE.RTMP.PORT,
39 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
40 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
41 ping: VIDEO_LIVE.RTMP.PING,
42 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
43 },
44 transcoding: {
45 ffmpeg: 'ffmpeg'
46 }
47}
48
49const lTags = loggerTagsFactory('live')
50
51class LiveManager {
52
53 private static instance: LiveManager
54
55 private readonly muxingSessions = new Map<string, MuxingSession>()
56 private readonly videoSessions = new Map<number, string>()
57 // Values are Date().getTime()
58 private readonly watchersPerVideo = new Map<number, number[]>()
59
60 private rtmpServer: Server
61
62 private constructor () {
63 }
64
65 init () {
66 const events = this.getContext().nodeEvent
67 events.on('postPublish', (sessionId: string, streamPath: string) => {
68 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
69
70 const splittedPath = streamPath.split('/')
71 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
72 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
73 return this.abortSession(sessionId)
74 }
75
76 this.handleSession(sessionId, streamPath, splittedPath[2])
77 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
78 })
79
80 events.on('donePublish', sessionId => {
81 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
82 })
83
84 registerConfigChangedHandler(() => {
85 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
86 this.run()
87 return
88 }
89
90 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
91 this.stop()
92 }
93 })
94
95 // Cleanup broken lives, that were terminated by a server restart for example
96 this.handleBrokenLives()
97 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
98
99 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
100 }
101
102 run () {
103 logger.info('Running RTMP server on port %d', config.rtmp.port, lTags())
104
105 this.rtmpServer = createServer(socket => {
106 const session = new NodeRtmpSession(config, socket)
107
108 session.run()
109 })
110
111 this.rtmpServer.on('error', err => {
112 logger.error('Cannot run RTMP server.', { err, ...lTags() })
113 })
114
115 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
116 }
117
118 stop () {
119 logger.info('Stopping RTMP server.', lTags())
120
121 this.rtmpServer.close()
122 this.rtmpServer = undefined
123
124 // Sessions is an object
125 this.getContext().sessions.forEach((session: any) => {
126 if (session instanceof NodeRtmpSession) {
127 session.stop()
128 }
129 })
130 }
131
132 isRunning () {
133 return !!this.rtmpServer
134 }
135
136 stopSessionOf (videoId: number) {
137 const sessionId = this.videoSessions.get(videoId)
138 if (!sessionId) return
139
140 this.videoSessions.delete(videoId)
141 this.abortSession(sessionId)
142 }
143
144 addViewTo (videoId: number) {
145 if (this.videoSessions.has(videoId) === false) return
146
147 let watchers = this.watchersPerVideo.get(videoId)
148
149 if (!watchers) {
150 watchers = []
151 this.watchersPerVideo.set(videoId, watchers)
152 }
153
154 watchers.push(new Date().getTime())
155 }
156
157 private getContext () {
158 return context
159 }
160
161 private abortSession (sessionId: string) {
162 const session = this.getContext().sessions.get(sessionId)
163 if (session) {
164 session.stop()
165 this.getContext().sessions.delete(sessionId)
166 }
167
168 const muxingSession = this.muxingSessions.get(sessionId)
609a4442 169 if (muxingSession) {
e466544f 170 // Muxing session will fire and event so we correctly cleanup the session
609a4442 171 muxingSession.abort()
609a4442
C
172
173 this.muxingSessions.delete(sessionId)
174 }
8ebf2a5d
C
175 }
176
177 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
178 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
179 if (!videoLive) {
180 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
181 return this.abortSession(sessionId)
182 }
183
184 const video = videoLive.Video
185 if (video.isBlacklisted()) {
186 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
187 return this.abortSession(sessionId)
188 }
189
190 // Cleanup old potential live files (could happen with a permanent live)
191 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
192
193 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
194 if (oldStreamingPlaylist) {
195 await cleanupLive(video, oldStreamingPlaylist)
196 }
197
198 this.videoSessions.set(video.id, sessionId)
199
200 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
201
c826f34a
C
202 const now = Date.now()
203 const probe = await ffprobePromise(rtmpUrl)
204
205 const [ { videoFileResolution }, fps, bitrate ] = await Promise.all([
206 getVideoFileResolution(rtmpUrl, probe),
207 getVideoFileFPS(rtmpUrl, probe),
208 getVideoFileBitrate(rtmpUrl, probe)
8ebf2a5d
C
209 ])
210
c826f34a
C
211 logger.info(
212 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
213 rtmpUrl, Date.now() - now, bitrate, fps, videoFileResolution, lTags(sessionId, video.uuid)
214 )
215
8ebf2a5d
C
216 const allResolutions = this.buildAllResolutionsToTranscode(videoFileResolution)
217
218 logger.info(
219 'Will mux/transcode live video of original resolution %d.', videoFileResolution,
220 { allResolutions, ...lTags(sessionId, video.uuid) }
221 )
222
223 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
224
225 return this.runMuxingSession({
226 sessionId,
227 videoLive,
228 streamingPlaylist,
229 rtmpUrl,
230 fps,
c826f34a 231 bitrate,
8ebf2a5d
C
232 allResolutions
233 })
234 }
235
236 private async runMuxingSession (options: {
237 sessionId: string
238 videoLive: MVideoLiveVideo
239 streamingPlaylist: MStreamingPlaylistVideo
240 rtmpUrl: string
241 fps: number
c826f34a 242 bitrate: number
8ebf2a5d
C
243 allResolutions: number[]
244 }) {
c826f34a 245 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, rtmpUrl } = options
8ebf2a5d
C
246 const videoUUID = videoLive.Video.uuid
247 const localLTags = lTags(sessionId, videoUUID)
248
249 const user = await UserModel.loadByLiveId(videoLive.id)
250 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
251
252 const muxingSession = new MuxingSession({
253 context: this.getContext(),
254 user,
255 sessionId,
256 videoLive,
257 streamingPlaylist,
258 rtmpUrl,
c826f34a 259 bitrate,
8ebf2a5d
C
260 fps,
261 allResolutions
262 })
263
264 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
265
266 muxingSession.on('bad-socket-health', ({ videoId }) => {
267 logger.error(
268 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
269 ' Stopping session of video %s.', videoUUID,
270 localLTags
271 )
272
273 this.stopSessionOf(videoId)
274 })
275
276 muxingSession.on('duration-exceeded', ({ videoId }) => {
277 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
278
279 this.stopSessionOf(videoId)
280 })
281
282 muxingSession.on('quota-exceeded', ({ videoId }) => {
283 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
284
285 this.stopSessionOf(videoId)
286 })
287
288 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
289 muxingSession.on('ffmpeg-end', ({ videoId }) => {
290 this.onMuxingFFmpegEnd(videoId)
291 })
292
293 muxingSession.on('after-cleanup', ({ videoId }) => {
294 this.muxingSessions.delete(sessionId)
295
609a4442
C
296 muxingSession.destroy()
297
8ebf2a5d
C
298 return this.onAfterMuxingCleanup(videoId)
299 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
300 })
301
302 this.muxingSessions.set(sessionId, muxingSession)
303
304 muxingSession.runMuxing()
305 .catch(err => {
306 logger.error('Cannot run muxing.', { err, ...localLTags })
307 this.abortSession(sessionId)
308 })
309 }
310
311 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
312 const videoId = live.videoId
313
314 try {
315 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
316
317 logger.info('Will publish and federate live %s.', video.url, localLTags)
318
319 video.state = VideoState.PUBLISHED
320 await video.save()
321
322 live.Video = video
323
324 setTimeout(() => {
325 federateVideoIfNeeded(video, false)
326 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }))
327
328 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
329 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
330 } catch (err) {
331 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
332 }
333 }
334
335 private onMuxingFFmpegEnd (videoId: number) {
336 this.watchersPerVideo.delete(videoId)
337 this.videoSessions.delete(videoId)
338 }
339
340 private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) {
341 try {
342 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
343 if (!fullVideo) return
344
345 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
346
347 if (!live.permanentLive) {
348 JobQueue.Instance.createJob({
349 type: 'video-live-ending',
350 payload: {
351 videoId: fullVideo.id
352 }
353 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
354
355 fullVideo.state = VideoState.LIVE_ENDED
356 } else {
357 fullVideo.state = VideoState.WAITING_FOR_LIVE
358 }
359
360 await fullVideo.save()
361
362 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
363
364 await federateVideoIfNeeded(fullVideo, false)
365 } catch (err) {
366 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
367 }
368 }
369
370 private async updateLiveViews () {
371 if (!this.isRunning()) return
372
373 if (!isTestInstance()) logger.info('Updating live video views.', lTags())
374
375 for (const videoId of this.watchersPerVideo.keys()) {
376 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
377
378 const watchers = this.watchersPerVideo.get(videoId)
379
380 const numWatchers = watchers.length
381
382 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
383 video.views = numWatchers
384 await video.save()
385
386 await federateVideoIfNeeded(video, false)
387
388 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
389
390 // Only keep not expired watchers
391 const newWatchers = watchers.filter(w => w > notBefore)
392 this.watchersPerVideo.set(videoId, newWatchers)
393
394 logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags())
395 }
396 }
397
398 private async handleBrokenLives () {
399 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
400
401 for (const uuid of videoUUIDs) {
402 await this.onAfterMuxingCleanup(uuid, true)
403 }
404 }
405
406 private buildAllResolutionsToTranscode (originResolution: number) {
407 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
408 ? computeResolutionsToTranscode(originResolution, 'live')
409 : []
410
411 return resolutionsEnabled.concat([ originResolution ])
412 }
413
764b1a14
C
414 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
415 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
8ebf2a5d 416
764b1a14
C
417 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
418 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
8ebf2a5d 419
764b1a14
C
420 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
421 playlist.type = VideoStreamingPlaylistType.HLS
422
423 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
424
425 return playlist.save()
8ebf2a5d
C
426 }
427
428 static get Instance () {
429 return this.instance || (this.instance = new this())
430 }
431}
432
433// ---------------------------------------------------------------------------
434
435export {
436 LiveManager
437}