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