]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live/live-manager.ts
Increase test timeouts
[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'
8ebf2a5d
C
9import { UserModel } from '@server/models/user/user'
10import { VideoModel } from '@server/models/video/video'
11import { VideoLiveModel } from '@server/models/video/video-live'
0c9668f7 12import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting'
26e3e98f 13import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
8ebf2a5d 14import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
05a60d85 15import { MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models'
1ce4256a 16import { pick, wait } from '@shared/core-utils'
0c9668f7 17import { ffprobePromise, getVideoStreamBitrate, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
afb371d9 18import { LiveVideoError, VideoState } from '@shared/models'
8ebf2a5d
C
19import { federateVideoIfNeeded } from '../activitypub/videos'
20import { JobQueue } from '../job-queue'
afb371d9 21import { getLiveReplayBaseDirectory } from '../paths'
df1db951 22import { PeerTubeSocket } from '../peertube-socket'
84cae54e 23import { Hooks } from '../plugins/hooks'
0c9668f7 24import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions'
8ebf2a5d 25import { LiveQuotaStore } from './live-quota-store'
0c9668f7 26import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } from './live-utils'
8ebf2a5d 27import { MuxingSession } from './shared'
0c9668f7 28import { RunnerJobModel } from '@server/models/runner/runner-job'
8ebf2a5d 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) })
83 })
84
85 registerConfigChangedHandler(() => {
df1db951
C
86 if (!this.running && CONFIG.LIVE.ENABLED === true) {
87 this.run().catch(err => logger.error('Cannot run live server.', { err }))
8ebf2a5d
C
88 return
89 }
90
df1db951 91 if (this.running && CONFIG.LIVE.ENABLED === false) {
8ebf2a5d
C
92 this.stop()
93 }
94 })
95
96 // Cleanup broken lives, that were terminated by a server restart for example
97 this.handleBrokenLives()
98 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
8ebf2a5d
C
99 }
100
df1db951
C
101 async run () {
102 this.running = true
8ebf2a5d 103
df1db951
C
104 if (CONFIG.LIVE.RTMP.ENABLED) {
105 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
8ebf2a5d 106
df1db951
C
107 this.rtmpServer = createServer(socket => {
108 const session = new NodeRtmpSession(config, socket)
8ebf2a5d 109
df1db951
C
110 session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
111 session.run()
112 })
113
114 this.rtmpServer.on('error', err => {
115 logger.error('Cannot run RTMP server.', { err, ...lTags() })
116 })
117
cfbe6be5 118 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
df1db951 119 }
8ebf2a5d 120
df1db951
C
121 if (CONFIG.LIVE.RTMPS.ENABLED) {
122 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
123
124 const [ key, cert ] = await Promise.all([
125 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
126 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
127 ])
128 const serverOptions = { key, cert }
129
130 this.rtmpsServer = createServerTLS(serverOptions, socket => {
131 const session = new NodeRtmpSession(config, socket)
132
133 session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
134 session.run()
135 })
136
137 this.rtmpsServer.on('error', err => {
138 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
139 })
140
cfbe6be5 141 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
df1db951 142 }
8ebf2a5d
C
143 }
144
145 stop () {
df1db951
C
146 this.running = false
147
5037e0e4
C
148 if (this.rtmpServer) {
149 logger.info('Stopping RTMP server.', lTags())
8ebf2a5d 150
5037e0e4
C
151 this.rtmpServer.close()
152 this.rtmpServer = undefined
153 }
154
155 if (this.rtmpsServer) {
156 logger.info('Stopping RTMPS server.', lTags())
157
158 this.rtmpsServer.close()
159 this.rtmpsServer = undefined
160 }
8ebf2a5d
C
161
162 // Sessions is an object
163 this.getContext().sessions.forEach((session: any) => {
164 if (session instanceof NodeRtmpSession) {
165 session.stop()
166 }
167 })
168 }
169
170 isRunning () {
171 return !!this.rtmpServer
172 }
173
0c9668f7
C
174 stopSessionOf (videoUUID: string, error: LiveVideoError | null) {
175 const sessionId = this.videoSessions.get(videoUUID)
176 if (!sessionId) {
177 logger.debug('No live session to stop for video %s', videoUUID, lTags(sessionId, videoUUID))
178 return
179 }
8ebf2a5d 180
0c9668f7 181 logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })
26e3e98f 182
0c9668f7
C
183 this.saveEndingSession(videoUUID, error)
184 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))
185
186 this.videoSessions.delete(videoUUID)
8ebf2a5d
C
187 this.abortSession(sessionId)
188 }
189
8ebf2a5d
C
190 private getContext () {
191 return context
192 }
193
194 private abortSession (sessionId: string) {
195 const session = this.getContext().sessions.get(sessionId)
196 if (session) {
197 session.stop()
198 this.getContext().sessions.delete(sessionId)
199 }
200
201 const muxingSession = this.muxingSessions.get(sessionId)
609a4442 202 if (muxingSession) {
e466544f 203 // Muxing session will fire and event so we correctly cleanup the session
609a4442 204 muxingSession.abort()
609a4442
C
205
206 this.muxingSessions.delete(sessionId)
207 }
8ebf2a5d
C
208 }
209
df1db951 210 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
8ebf2a5d
C
211 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
212 if (!videoLive) {
213 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
214 return this.abortSession(sessionId)
215 }
216
217 const video = videoLive.Video
218 if (video.isBlacklisted()) {
219 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
220 return this.abortSession(sessionId)
221 }
222
0c9668f7
C
223 if (this.videoSessions.has(video.uuid)) {
224 logger.warn('Video %s has already a live session. Refusing stream %s.', video.uuid, streamKey, lTags(sessionId, video.uuid))
225 return this.abortSession(sessionId)
226 }
227
92083e42 228 // Cleanup old potential live (could happen with a permanent live)
8ebf2a5d
C
229 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
230 if (oldStreamingPlaylist) {
5333788c
C
231 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
232
cfd57d2c 233 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
8ebf2a5d
C
234 }
235
0c9668f7 236 this.videoSessions.set(video.uuid, sessionId)
8ebf2a5d 237
c826f34a 238 const now = Date.now()
df1db951 239 const probe = await ffprobePromise(inputUrl)
c826f34a 240
1ce4256a 241 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
c729caf6
C
242 getVideoStreamDimensionsInfo(inputUrl, probe),
243 getVideoStreamFPS(inputUrl, probe),
1ce4256a
C
244 getVideoStreamBitrate(inputUrl, probe),
245 hasAudioStream(inputUrl, probe)
8ebf2a5d
C
246 ])
247
c826f34a
C
248 logger.info(
249 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
df1db951 250 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
c826f34a
C
251 )
252
ebb9e53a 253 const allResolutions = await Hooks.wrapObject(
a32bf8cd 254 this.buildAllResolutionsToTranscode(resolution, hasAudio),
64fd6158 255 'filter:transcoding.auto.resolutions-to-transcode.result',
ebb9e53a
C
256 { video }
257 )
8ebf2a5d
C
258
259 logger.info(
0c9668f7 260 'Handling live video of original resolution %d.', resolution,
8ebf2a5d
C
261 { allResolutions, ...lTags(sessionId, video.uuid) }
262 )
263
8ebf2a5d
C
264 return this.runMuxingSession({
265 sessionId,
266 videoLive,
1ce4256a 267
df1db951 268 inputUrl,
8ebf2a5d 269 fps,
c826f34a 270 bitrate,
679c12e6 271 ratio,
1ce4256a
C
272 allResolutions,
273 hasAudio
8ebf2a5d
C
274 })
275 }
276
277 private async runMuxingSession (options: {
278 sessionId: string
05a60d85 279 videoLive: MVideoLiveVideoWithSetting
1ce4256a 280
df1db951 281 inputUrl: string
8ebf2a5d 282 fps: number
c826f34a 283 bitrate: number
679c12e6 284 ratio: number
8ebf2a5d 285 allResolutions: number[]
1ce4256a 286 hasAudio: boolean
8ebf2a5d 287 }) {
1ce4256a 288 const { sessionId, videoLive } = options
8ebf2a5d
C
289 const videoUUID = videoLive.Video.uuid
290 const localLTags = lTags(sessionId, videoUUID)
291
26e3e98f
C
292 const liveSession = await this.saveStartingSession(videoLive)
293
8ebf2a5d
C
294 const user = await UserModel.loadByLiveId(videoLive.id)
295 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
296
297 const muxingSession = new MuxingSession({
298 context: this.getContext(),
8ebf2a5d
C
299 sessionId,
300 videoLive,
1ce4256a
C
301 user,
302
afb371d9 303 ...pick(options, [ 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
8ebf2a5d
C
304 })
305
cfd57d2c 306 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
8ebf2a5d 307
0c9668f7 308 muxingSession.on('bad-socket-health', ({ videoUUID }) => {
8ebf2a5d
C
309 logger.error(
310 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
311 ' Stopping session of video %s.', videoUUID,
312 localLTags
313 )
314
0c9668f7 315 this.stopSessionOf(videoUUID, LiveVideoError.BAD_SOCKET_HEALTH)
8ebf2a5d
C
316 })
317
0c9668f7 318 muxingSession.on('duration-exceeded', ({ videoUUID }) => {
8ebf2a5d
C
319 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
320
0c9668f7 321 this.stopSessionOf(videoUUID, LiveVideoError.DURATION_EXCEEDED)
8ebf2a5d
C
322 })
323
0c9668f7 324 muxingSession.on('quota-exceeded', ({ videoUUID }) => {
8ebf2a5d
C
325 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
326
0c9668f7 327 this.stopSessionOf(videoUUID, LiveVideoError.QUOTA_EXCEEDED)
26e3e98f
C
328 })
329
0c9668f7
C
330 muxingSession.on('transcoding-error', ({ videoUUID }) => {
331 this.stopSessionOf(videoUUID, LiveVideoError.FFMPEG_ERROR)
8ebf2a5d
C
332 })
333
0c9668f7
C
334 muxingSession.on('transcoding-end', ({ videoUUID }) => {
335 this.onMuxingFFmpegEnd(videoUUID, sessionId)
8ebf2a5d
C
336 })
337
0c9668f7 338 muxingSession.on('after-cleanup', ({ videoUUID }) => {
8ebf2a5d
C
339 this.muxingSessions.delete(sessionId)
340
9a82ce24
C
341 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
342
609a4442
C
343 muxingSession.destroy()
344
0c9668f7 345 return this.onAfterMuxingCleanup({ videoUUID, liveSession })
8ebf2a5d
C
346 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
347 })
348
349 this.muxingSessions.set(sessionId, muxingSession)
350
351 muxingSession.runMuxing()
352 .catch(err => {
353 logger.error('Cannot run muxing.', { err, ...localLTags })
354 this.abortSession(sessionId)
355 })
356 }
357
358 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
359 const videoId = live.videoId
360
361 try {
4fae2b1f 362 const video = await VideoModel.loadFull(videoId)
8ebf2a5d
C
363
364 logger.info('Will publish and federate live %s.', video.url, localLTags)
365
366 video.state = VideoState.PUBLISHED
7137377d 367 video.publishedAt = new Date()
8ebf2a5d
C
368 await video.save()
369
370 live.Video = video
371
4ec52d04 372 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
8ebf2a5d 373
4ec52d04
C
374 try {
375 await federateVideoIfNeeded(video, false)
376 } catch (err) {
377 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
378 }
379
380 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
8ebf2a5d
C
381 } catch (err) {
382 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
383 }
384 }
385
0c9668f7
C
386 private onMuxingFFmpegEnd (videoUUID: string, sessionId: string) {
387 this.videoSessions.delete(videoUUID)
26e3e98f 388
0c9668f7 389 this.saveEndingSession(videoUUID, null)
26e3e98f 390 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
8ebf2a5d
C
391 }
392
4ec52d04 393 private async onAfterMuxingCleanup (options: {
0c9668f7 394 videoUUID: string
26e3e98f 395 liveSession?: MVideoLiveSession
4ec52d04
C
396 cleanupNow?: boolean // Default false
397 }) {
0c9668f7
C
398 const { videoUUID, liveSession: liveSessionArg, cleanupNow = false } = options
399
400 logger.debug('Live of video %s has been cleaned up. Moving to its next state.', videoUUID, lTags(videoUUID))
4ec52d04 401
8ebf2a5d 402 try {
0c9668f7 403 const fullVideo = await VideoModel.loadFull(videoUUID)
8ebf2a5d
C
404 if (!fullVideo) return
405
406 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
407
46f7cd68 408 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
26e3e98f
C
409
410 // On server restart during a live
411 if (!liveSession.endDate) {
412 liveSession.endDate = new Date()
413 await liveSession.save()
414 }
415
bd911b54 416 JobQueue.Instance.createJobAsync({
4ec52d04
C
417 type: 'video-live-ending',
418 payload: {
419 videoId: fullVideo.id,
26e3e98f 420
4ec52d04
C
421 replayDirectory: live.saveReplay
422 ? await this.findReplayDirectory(fullVideo)
423 : undefined,
26e3e98f
C
424
425 liveSessionId: liveSession.id,
cdd83816 426 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
26e3e98f 427
4ec52d04 428 publishedAt: fullVideo.publishedAt.toISOString()
bd911b54
C
429 },
430
431 delay: cleanupNow
432 ? 0
433 : VIDEO_LIVE.CLEANUP_DELAY
434 })
4ec52d04
C
435
436 fullVideo.state = live.permanentLive
437 ? VideoState.WAITING_FOR_LIVE
438 : VideoState.LIVE_ENDED
8ebf2a5d
C
439
440 await fullVideo.save()
441
442 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
443
444 await federateVideoIfNeeded(fullVideo, false)
445 } catch (err) {
0c9668f7 446 logger.error('Cannot save/federate new video state of live streaming of video %s.', videoUUID, { err, ...lTags(videoUUID) })
8ebf2a5d
C
447 }
448 }
449
8ebf2a5d 450 private async handleBrokenLives () {
0c9668f7
C
451 await RunnerJobModel.cancelAllJobs({ type: 'live-rtmp-hls-transcoding' })
452
8ebf2a5d
C
453 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
454
455 for (const uuid of videoUUIDs) {
0c9668f7 456 await this.onAfterMuxingCleanup({ videoUUID: uuid, cleanupNow: true })
8ebf2a5d
C
457 }
458 }
459
4ec52d04
C
460 private async findReplayDirectory (video: MVideo) {
461 const directory = getLiveReplayBaseDirectory(video)
462 const files = await readdir(directory)
463
464 if (files.length === 0) return undefined
465
466 return join(directory, files.sort().reverse()[0])
467 }
468
a32bf8cd 469 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
5e2afe42 470 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
84cae54e 471
8ebf2a5d 472 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
a32bf8cd 473 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
8ebf2a5d
C
474 : []
475
84cae54e
C
476 if (resolutionsEnabled.length === 0) {
477 return [ originResolution ]
478 }
479
480 return resolutionsEnabled
8ebf2a5d
C
481 }
482
05a60d85
W
483 private async saveStartingSession (videoLive: MVideoLiveVideoWithSetting) {
484 const replaySettings = videoLive.saveReplay
485 ? new VideoLiveReplaySettingModel({
486 privacy: videoLive.ReplaySetting.privacy
487 })
488 : null
26e3e98f 489
05a60d85
W
490 return sequelizeTypescript.transaction(async t => {
491 if (videoLive.saveReplay) {
492 await replaySettings.save({ transaction: t })
493 }
494
495 return VideoLiveSessionModel.create({
496 startDate: new Date(),
497 liveVideoId: videoLive.videoId,
498 saveReplay: videoLive.saveReplay,
499 replaySettingId: videoLive.saveReplay ? replaySettings.id : null,
500 endingProcessed: false
501 }, { transaction: t })
502 })
26e3e98f
C
503 }
504
0c9668f7
C
505 private async saveEndingSession (videoUUID: string, error: LiveVideoError | null) {
506 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoUUID)
0755cb89
C
507 if (!liveSession) return
508
26e3e98f
C
509 liveSession.endDate = new Date()
510 liveSession.error = error
511
512 return liveSession.save()
513 }
514
8ebf2a5d
C
515 static get Instance () {
516 return this.instance || (this.instance = new this())
517 }
518}
519
520// ---------------------------------------------------------------------------
521
522export {
523 LiveManager
524}