]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live/live-manager.ts
Add config file merging in upgrade script
[github/Chocobozzz/PeerTube.git] / server / lib / live / live-manager.ts
CommitLineData
4ec52d04 1import { readdir, readFile } from 'fs-extra'
8ebf2a5d 2import { createServer, Server } from 'net'
4ec52d04 3import { join } from 'path'
df1db951 4import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
8ebf2a5d
C
5import { logger, loggerTagsFactory } from '@server/helpers/logger'
6import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
afb371d9 7import { VIDEO_LIVE } from '@server/initializers/constants'
0c9668f7 8import { sequelizeTypescript } from '@server/initializers/database'
5a05c145 9import { RunnerJobModel } from '@server/models/runner/runner-job'
8ebf2a5d
C
10import { UserModel } from '@server/models/user/user'
11import { VideoModel } from '@server/models/video/video'
12import { VideoLiveModel } from '@server/models/video/video-live'
0c9668f7 13import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting'
26e3e98f 14import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
8ebf2a5d 15import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
05a60d85 16import { MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models'
1ce4256a 17import { pick, wait } from '@shared/core-utils'
0c9668f7 18import { ffprobePromise, getVideoStreamBitrate, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
afb371d9 19import { LiveVideoError, VideoState } from '@shared/models'
8ebf2a5d
C
20import { federateVideoIfNeeded } from '../activitypub/videos'
21import { JobQueue } from '../job-queue'
afb371d9 22import { getLiveReplayBaseDirectory } from '../paths'
df1db951 23import { PeerTubeSocket } from '../peertube-socket'
84cae54e 24import { Hooks } from '../plugins/hooks'
0c9668f7 25import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions'
8ebf2a5d 26import { LiveQuotaStore } from './live-quota-store'
0c9668f7 27import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } from './live-utils'
8ebf2a5d
C
28import { MuxingSession } from './shared'
29
7a397c7f
C
30const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
31const context = require('node-media-server/src/node_core_ctx')
32const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
8ebf2a5d
C
33
34// Disable node media server logs
35nodeMediaServerLogger.setLogType(0)
36
37const config = {
38 rtmp: {
39 port: CONFIG.LIVE.RTMP.PORT,
40 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
41 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
42 ping: VIDEO_LIVE.RTMP.PING,
43 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
8ebf2a5d
C
44 }
45}
46
47const lTags = loggerTagsFactory('live')
48
49class LiveManager {
50
51 private static instance: LiveManager
52
53 private readonly muxingSessions = new Map<string, MuxingSession>()
0c9668f7 54 private readonly videoSessions = new Map<string, string>()
8ebf2a5d
C
55
56 private rtmpServer: Server
df1db951
C
57 private rtmpsServer: ServerTLS
58
59 private running = false
8ebf2a5d
C
60
61 private constructor () {
62 }
63
64 init () {
65 const events = this.getContext().nodeEvent
66 events.on('postPublish', (sessionId: string, streamPath: string) => {
67 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
68
69 const splittedPath = streamPath.split('/')
70 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
71 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
72 return this.abortSession(sessionId)
73 }
74
df1db951
C
75 const session = this.getContext().sessions.get(sessionId)
76
77 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
8ebf2a5d
C
78 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
79 })
80
81 events.on('donePublish', sessionId => {
82 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
5a05c145
C
83
84 // Force session aborting, so we kill ffmpeg even if it still has data to process (slow CPU)
85 setTimeout(() => this.abortSession(sessionId), 2000)
8ebf2a5d
C
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
0c9668f7
C
177 stopSessionOf (videoUUID: string, error: LiveVideoError | null) {
178 const sessionId = this.videoSessions.get(videoUUID)
179 if (!sessionId) {
180 logger.debug('No live session to stop for video %s', videoUUID, lTags(sessionId, videoUUID))
181 return
182 }
8ebf2a5d 183
0c9668f7 184 logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })
26e3e98f 185
0c9668f7
C
186 this.saveEndingSession(videoUUID, error)
187 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))
188
189 this.videoSessions.delete(videoUUID)
8ebf2a5d
C
190 this.abortSession(sessionId)
191 }
192
8ebf2a5d
C
193 private getContext () {
194 return context
195 }
196
197 private abortSession (sessionId: string) {
198 const session = this.getContext().sessions.get(sessionId)
199 if (session) {
200 session.stop()
201 this.getContext().sessions.delete(sessionId)
202 }
203
204 const muxingSession = this.muxingSessions.get(sessionId)
609a4442 205 if (muxingSession) {
e466544f 206 // Muxing session will fire and event so we correctly cleanup the session
609a4442 207 muxingSession.abort()
609a4442
C
208
209 this.muxingSessions.delete(sessionId)
210 }
8ebf2a5d
C
211 }
212
df1db951 213 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
8ebf2a5d
C
214 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
215 if (!videoLive) {
216 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
217 return this.abortSession(sessionId)
218 }
219
220 const video = videoLive.Video
221 if (video.isBlacklisted()) {
222 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
223 return this.abortSession(sessionId)
224 }
225
0c9668f7
C
226 if (this.videoSessions.has(video.uuid)) {
227 logger.warn('Video %s has already a live session. Refusing stream %s.', video.uuid, streamKey, lTags(sessionId, video.uuid))
228 return this.abortSession(sessionId)
229 }
230
92083e42 231 // Cleanup old potential live (could happen with a permanent live)
8ebf2a5d
C
232 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
233 if (oldStreamingPlaylist) {
5333788c
C
234 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
235
cfd57d2c 236 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
8ebf2a5d
C
237 }
238
0c9668f7 239 this.videoSessions.set(video.uuid, sessionId)
8ebf2a5d 240
c826f34a 241 const now = Date.now()
df1db951 242 const probe = await ffprobePromise(inputUrl)
c826f34a 243
1ce4256a 244 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
c729caf6
C
245 getVideoStreamDimensionsInfo(inputUrl, probe),
246 getVideoStreamFPS(inputUrl, probe),
1ce4256a
C
247 getVideoStreamBitrate(inputUrl, probe),
248 hasAudioStream(inputUrl, probe)
8ebf2a5d
C
249 ])
250
c826f34a
C
251 logger.info(
252 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
df1db951 253 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
c826f34a
C
254 )
255
ebb9e53a 256 const allResolutions = await Hooks.wrapObject(
a32bf8cd 257 this.buildAllResolutionsToTranscode(resolution, hasAudio),
64fd6158 258 'filter:transcoding.auto.resolutions-to-transcode.result',
ebb9e53a
C
259 { video }
260 )
8ebf2a5d
C
261
262 logger.info(
0c9668f7 263 'Handling live video of original resolution %d.', resolution,
8ebf2a5d
C
264 { allResolutions, ...lTags(sessionId, video.uuid) }
265 )
266
8ebf2a5d
C
267 return this.runMuxingSession({
268 sessionId,
269 videoLive,
1ce4256a 270
df1db951 271 inputUrl,
8ebf2a5d 272 fps,
c826f34a 273 bitrate,
679c12e6 274 ratio,
1ce4256a
C
275 allResolutions,
276 hasAudio
8ebf2a5d
C
277 })
278 }
279
280 private async runMuxingSession (options: {
281 sessionId: string
05a60d85 282 videoLive: MVideoLiveVideoWithSetting
1ce4256a 283
df1db951 284 inputUrl: string
8ebf2a5d 285 fps: number
c826f34a 286 bitrate: number
679c12e6 287 ratio: number
8ebf2a5d 288 allResolutions: number[]
1ce4256a 289 hasAudio: boolean
8ebf2a5d 290 }) {
1ce4256a 291 const { sessionId, videoLive } = options
8ebf2a5d
C
292 const videoUUID = videoLive.Video.uuid
293 const localLTags = lTags(sessionId, videoUUID)
294
26e3e98f
C
295 const liveSession = await this.saveStartingSession(videoLive)
296
8ebf2a5d
C
297 const user = await UserModel.loadByLiveId(videoLive.id)
298 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
299
300 const muxingSession = new MuxingSession({
301 context: this.getContext(),
8ebf2a5d
C
302 sessionId,
303 videoLive,
1ce4256a
C
304 user,
305
afb371d9 306 ...pick(options, [ 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
8ebf2a5d
C
307 })
308
cfd57d2c 309 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
8ebf2a5d 310
0c9668f7 311 muxingSession.on('bad-socket-health', ({ videoUUID }) => {
8ebf2a5d
C
312 logger.error(
313 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
314 ' Stopping session of video %s.', videoUUID,
315 localLTags
316 )
317
0c9668f7 318 this.stopSessionOf(videoUUID, LiveVideoError.BAD_SOCKET_HEALTH)
8ebf2a5d
C
319 })
320
0c9668f7 321 muxingSession.on('duration-exceeded', ({ videoUUID }) => {
8ebf2a5d
C
322 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
323
0c9668f7 324 this.stopSessionOf(videoUUID, LiveVideoError.DURATION_EXCEEDED)
8ebf2a5d
C
325 })
326
0c9668f7 327 muxingSession.on('quota-exceeded', ({ videoUUID }) => {
8ebf2a5d
C
328 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
329
0c9668f7 330 this.stopSessionOf(videoUUID, LiveVideoError.QUOTA_EXCEEDED)
26e3e98f
C
331 })
332
0c9668f7
C
333 muxingSession.on('transcoding-error', ({ videoUUID }) => {
334 this.stopSessionOf(videoUUID, LiveVideoError.FFMPEG_ERROR)
8ebf2a5d
C
335 })
336
0c9668f7
C
337 muxingSession.on('transcoding-end', ({ videoUUID }) => {
338 this.onMuxingFFmpegEnd(videoUUID, sessionId)
8ebf2a5d
C
339 })
340
0c9668f7 341 muxingSession.on('after-cleanup', ({ videoUUID }) => {
8ebf2a5d
C
342 this.muxingSessions.delete(sessionId)
343
9a82ce24
C
344 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
345
609a4442
C
346 muxingSession.destroy()
347
0c9668f7 348 return this.onAfterMuxingCleanup({ videoUUID, liveSession })
8ebf2a5d
C
349 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
350 })
351
352 this.muxingSessions.set(sessionId, muxingSession)
353
354 muxingSession.runMuxing()
355 .catch(err => {
356 logger.error('Cannot run muxing.', { err, ...localLTags })
357 this.abortSession(sessionId)
358 })
359 }
360
361 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
362 const videoId = live.videoId
363
364 try {
4fae2b1f 365 const video = await VideoModel.loadFull(videoId)
8ebf2a5d
C
366
367 logger.info('Will publish and federate live %s.', video.url, localLTags)
368
369 video.state = VideoState.PUBLISHED
7137377d 370 video.publishedAt = new Date()
8ebf2a5d
C
371 await video.save()
372
373 live.Video = video
374
4ec52d04 375 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
8ebf2a5d 376
4ec52d04
C
377 try {
378 await federateVideoIfNeeded(video, false)
379 } catch (err) {
380 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
381 }
382
383 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
8ebf2a5d
C
384 } catch (err) {
385 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
386 }
387 }
388
0c9668f7 389 private onMuxingFFmpegEnd (videoUUID: string, sessionId: string) {
c08a7f16
C
390 // Session already cleaned up
391 if (!this.videoSessions.has(videoUUID)) return
392
0c9668f7 393 this.videoSessions.delete(videoUUID)
26e3e98f 394
0c9668f7 395 this.saveEndingSession(videoUUID, null)
26e3e98f 396 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
8ebf2a5d
C
397 }
398
4ec52d04 399 private async onAfterMuxingCleanup (options: {
0c9668f7 400 videoUUID: string
26e3e98f 401 liveSession?: MVideoLiveSession
4ec52d04
C
402 cleanupNow?: boolean // Default false
403 }) {
0c9668f7
C
404 const { videoUUID, liveSession: liveSessionArg, cleanupNow = false } = options
405
406 logger.debug('Live of video %s has been cleaned up. Moving to its next state.', videoUUID, lTags(videoUUID))
4ec52d04 407
8ebf2a5d 408 try {
0c9668f7 409 const fullVideo = await VideoModel.loadFull(videoUUID)
8ebf2a5d
C
410 if (!fullVideo) return
411
412 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
413
46f7cd68 414 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
26e3e98f
C
415
416 // On server restart during a live
417 if (!liveSession.endDate) {
418 liveSession.endDate = new Date()
419 await liveSession.save()
420 }
421
bd911b54 422 JobQueue.Instance.createJobAsync({
4ec52d04
C
423 type: 'video-live-ending',
424 payload: {
425 videoId: fullVideo.id,
26e3e98f 426
4ec52d04
C
427 replayDirectory: live.saveReplay
428 ? await this.findReplayDirectory(fullVideo)
429 : undefined,
26e3e98f
C
430
431 liveSessionId: liveSession.id,
cdd83816 432 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
26e3e98f 433
4ec52d04 434 publishedAt: fullVideo.publishedAt.toISOString()
bd911b54
C
435 },
436
437 delay: cleanupNow
438 ? 0
439 : VIDEO_LIVE.CLEANUP_DELAY
440 })
4ec52d04
C
441
442 fullVideo.state = live.permanentLive
443 ? VideoState.WAITING_FOR_LIVE
444 : VideoState.LIVE_ENDED
8ebf2a5d
C
445
446 await fullVideo.save()
447
448 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
449
450 await federateVideoIfNeeded(fullVideo, false)
451 } catch (err) {
0c9668f7 452 logger.error('Cannot save/federate new video state of live streaming of video %s.', videoUUID, { err, ...lTags(videoUUID) })
8ebf2a5d
C
453 }
454 }
455
8ebf2a5d 456 private async handleBrokenLives () {
0c9668f7
C
457 await RunnerJobModel.cancelAllJobs({ type: 'live-rtmp-hls-transcoding' })
458
8ebf2a5d
C
459 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
460
461 for (const uuid of videoUUIDs) {
0c9668f7 462 await this.onAfterMuxingCleanup({ videoUUID: uuid, cleanupNow: true })
8ebf2a5d
C
463 }
464 }
465
4ec52d04
C
466 private async findReplayDirectory (video: MVideo) {
467 const directory = getLiveReplayBaseDirectory(video)
468 const files = await readdir(directory)
469
470 if (files.length === 0) return undefined
471
472 return join(directory, files.sort().reverse()[0])
473 }
474
a32bf8cd 475 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
5e2afe42 476 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
84cae54e 477
8ebf2a5d 478 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
a32bf8cd 479 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
8ebf2a5d
C
480 : []
481
84cae54e
C
482 if (resolutionsEnabled.length === 0) {
483 return [ originResolution ]
484 }
485
486 return resolutionsEnabled
8ebf2a5d
C
487 }
488
05a60d85
W
489 private async saveStartingSession (videoLive: MVideoLiveVideoWithSetting) {
490 const replaySettings = videoLive.saveReplay
491 ? new VideoLiveReplaySettingModel({
492 privacy: videoLive.ReplaySetting.privacy
493 })
494 : null
26e3e98f 495
05a60d85
W
496 return sequelizeTypescript.transaction(async t => {
497 if (videoLive.saveReplay) {
498 await replaySettings.save({ transaction: t })
499 }
500
501 return VideoLiveSessionModel.create({
502 startDate: new Date(),
503 liveVideoId: videoLive.videoId,
504 saveReplay: videoLive.saveReplay,
505 replaySettingId: videoLive.saveReplay ? replaySettings.id : null,
506 endingProcessed: false
507 }, { transaction: t })
508 })
26e3e98f
C
509 }
510
0c9668f7
C
511 private async saveEndingSession (videoUUID: string, error: LiveVideoError | null) {
512 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoUUID)
0755cb89
C
513 if (!liveSession) return
514
26e3e98f
C
515 liveSession.endDate = new Date()
516 liveSession.error = error
517
518 return liveSession.save()
519 }
520
8ebf2a5d
C
521 static get Instance () {
522 return this.instance || (this.instance = new this())
523 }
524}
525
526// ---------------------------------------------------------------------------
527
528export {
529 LiveManager
530}