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