]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live/live-manager.ts
Live supports object storage
[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'
c826f34a 5import {
84cae54e 6 computeResolutionsToTranscode,
c826f34a 7 ffprobePromise,
f443a746 8 getLiveSegmentTime,
c729caf6 9 getVideoStreamBitrate,
f443a746 10 getVideoStreamDimensionsInfo,
1ce4256a
C
11 getVideoStreamFPS,
12 hasAudioStream
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'
1ce4256a 23import { pick, wait } from '@shared/core-utils'
cfd57d2c 24import { LiveVideoError, VideoState, VideoStorage, 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'
84cae54e 29import { Hooks } from '../plugins/hooks'
8ebf2a5d 30import { LiveQuotaStore } from './live-quota-store'
cfd57d2c 31import { cleanupAndDestroyPermanentLive } 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
92083e42 222 // Cleanup old potential live (could happen with a permanent live)
8ebf2a5d
C
223 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
224 if (oldStreamingPlaylist) {
5333788c
C
225 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
226
cfd57d2c 227 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
8ebf2a5d
C
228 }
229
230 this.videoSessions.set(video.id, sessionId)
231
c826f34a 232 const now = Date.now()
df1db951 233 const probe = await ffprobePromise(inputUrl)
c826f34a 234
1ce4256a 235 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
c729caf6
C
236 getVideoStreamDimensionsInfo(inputUrl, probe),
237 getVideoStreamFPS(inputUrl, probe),
1ce4256a
C
238 getVideoStreamBitrate(inputUrl, probe),
239 hasAudioStream(inputUrl, probe)
8ebf2a5d
C
240 ])
241
c826f34a
C
242 logger.info(
243 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
df1db951 244 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
c826f34a
C
245 )
246
ebb9e53a
C
247 const allResolutions = await Hooks.wrapObject(
248 this.buildAllResolutionsToTranscode(resolution),
64fd6158 249 'filter:transcoding.auto.resolutions-to-transcode.result',
ebb9e53a
C
250 { video }
251 )
8ebf2a5d
C
252
253 logger.info(
679c12e6 254 'Will mux/transcode live video of original resolution %d.', resolution,
8ebf2a5d
C
255 { allResolutions, ...lTags(sessionId, video.uuid) }
256 )
257
258 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
259
260 return this.runMuxingSession({
261 sessionId,
262 videoLive,
1ce4256a 263
8ebf2a5d 264 streamingPlaylist,
df1db951 265 inputUrl,
8ebf2a5d 266 fps,
c826f34a 267 bitrate,
679c12e6 268 ratio,
1ce4256a
C
269 allResolutions,
270 hasAudio
8ebf2a5d
C
271 })
272 }
273
274 private async runMuxingSession (options: {
275 sessionId: string
276 videoLive: MVideoLiveVideo
1ce4256a 277
8ebf2a5d 278 streamingPlaylist: MStreamingPlaylistVideo
df1db951 279 inputUrl: string
8ebf2a5d 280 fps: number
c826f34a 281 bitrate: number
679c12e6 282 ratio: number
8ebf2a5d 283 allResolutions: number[]
1ce4256a 284 hasAudio: boolean
8ebf2a5d 285 }) {
1ce4256a 286 const { sessionId, videoLive } = options
8ebf2a5d
C
287 const videoUUID = videoLive.Video.uuid
288 const localLTags = lTags(sessionId, videoUUID)
289
26e3e98f
C
290 const liveSession = await this.saveStartingSession(videoLive)
291
8ebf2a5d
C
292 const user = await UserModel.loadByLiveId(videoLive.id)
293 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
294
295 const muxingSession = new MuxingSession({
296 context: this.getContext(),
8ebf2a5d
C
297 sessionId,
298 videoLive,
1ce4256a
C
299 user,
300
301 ...pick(options, [ 'streamingPlaylist', 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
8ebf2a5d
C
302 })
303
cfd57d2c 304 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
8ebf2a5d
C
305
306 muxingSession.on('bad-socket-health', ({ videoId }) => {
307 logger.error(
308 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
309 ' Stopping session of video %s.', videoUUID,
310 localLTags
311 )
312
26e3e98f 313 this.stopSessionOf(videoId, LiveVideoError.BAD_SOCKET_HEALTH)
8ebf2a5d
C
314 })
315
316 muxingSession.on('duration-exceeded', ({ videoId }) => {
317 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
318
26e3e98f 319 this.stopSessionOf(videoId, LiveVideoError.DURATION_EXCEEDED)
8ebf2a5d
C
320 })
321
322 muxingSession.on('quota-exceeded', ({ videoId }) => {
323 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
324
26e3e98f
C
325 this.stopSessionOf(videoId, LiveVideoError.QUOTA_EXCEEDED)
326 })
327
328 muxingSession.on('ffmpeg-error', ({ videoId }) => {
329 this.stopSessionOf(videoId, LiveVideoError.FFMPEG_ERROR)
8ebf2a5d
C
330 })
331
8ebf2a5d 332 muxingSession.on('ffmpeg-end', ({ videoId }) => {
26e3e98f 333 this.onMuxingFFmpegEnd(videoId, sessionId)
8ebf2a5d
C
334 })
335
336 muxingSession.on('after-cleanup', ({ videoId }) => {
337 this.muxingSessions.delete(sessionId)
338
9a82ce24
C
339 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
340
609a4442
C
341 muxingSession.destroy()
342
26e3e98f 343 return this.onAfterMuxingCleanup({ videoId, liveSession })
8ebf2a5d
C
344 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
345 })
346
347 this.muxingSessions.set(sessionId, muxingSession)
348
349 muxingSession.runMuxing()
350 .catch(err => {
351 logger.error('Cannot run muxing.', { err, ...localLTags })
352 this.abortSession(sessionId)
353 })
354 }
355
356 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
357 const videoId = live.videoId
358
359 try {
4fae2b1f 360 const video = await VideoModel.loadFull(videoId)
8ebf2a5d
C
361
362 logger.info('Will publish and federate live %s.', video.url, localLTags)
363
364 video.state = VideoState.PUBLISHED
7137377d 365 video.publishedAt = new Date()
8ebf2a5d
C
366 await video.save()
367
368 live.Video = video
369
4ec52d04 370 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
8ebf2a5d 371
4ec52d04
C
372 try {
373 await federateVideoIfNeeded(video, false)
374 } catch (err) {
375 logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })
376 }
377
378 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
8ebf2a5d
C
379 } catch (err) {
380 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
381 }
382 }
383
26e3e98f 384 private onMuxingFFmpegEnd (videoId: number, sessionId: string) {
8ebf2a5d 385 this.videoSessions.delete(videoId)
26e3e98f
C
386
387 this.saveEndingSession(videoId, null)
388 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
8ebf2a5d
C
389 }
390
4ec52d04
C
391 private async onAfterMuxingCleanup (options: {
392 videoId: number | string
26e3e98f 393 liveSession?: MVideoLiveSession
4ec52d04
C
394 cleanupNow?: boolean // Default false
395 }) {
26e3e98f 396 const { videoId, liveSession: liveSessionArg, cleanupNow = false } = options
4ec52d04 397
8ebf2a5d 398 try {
4fae2b1f 399 const fullVideo = await VideoModel.loadFull(videoId)
8ebf2a5d
C
400 if (!fullVideo) return
401
402 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
403
46f7cd68 404 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
26e3e98f
C
405
406 // On server restart during a live
407 if (!liveSession.endDate) {
408 liveSession.endDate = new Date()
409 await liveSession.save()
410 }
411
bd911b54 412 JobQueue.Instance.createJobAsync({
4ec52d04
C
413 type: 'video-live-ending',
414 payload: {
415 videoId: fullVideo.id,
26e3e98f 416
4ec52d04
C
417 replayDirectory: live.saveReplay
418 ? await this.findReplayDirectory(fullVideo)
419 : undefined,
26e3e98f
C
420
421 liveSessionId: liveSession.id,
cdd83816 422 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
26e3e98f 423
4ec52d04 424 publishedAt: fullVideo.publishedAt.toISOString()
bd911b54
C
425 },
426
427 delay: cleanupNow
428 ? 0
429 : VIDEO_LIVE.CLEANUP_DELAY
430 })
4ec52d04
C
431
432 fullVideo.state = live.permanentLive
433 ? VideoState.WAITING_FOR_LIVE
434 : VideoState.LIVE_ENDED
8ebf2a5d
C
435
436 await fullVideo.save()
437
438 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
439
440 await federateVideoIfNeeded(fullVideo, false)
441 } catch (err) {
4ec52d04 442 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') })
8ebf2a5d
C
443 }
444 }
445
8ebf2a5d
C
446 private async handleBrokenLives () {
447 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
448
449 for (const uuid of videoUUIDs) {
4ec52d04 450 await this.onAfterMuxingCleanup({ videoId: uuid, cleanupNow: true })
8ebf2a5d
C
451 }
452 }
453
4ec52d04
C
454 private async findReplayDirectory (video: MVideo) {
455 const directory = getLiveReplayBaseDirectory(video)
456 const files = await readdir(directory)
457
458 if (files.length === 0) return undefined
459
460 return join(directory, files.sort().reverse()[0])
461 }
462
8ebf2a5d 463 private buildAllResolutionsToTranscode (originResolution: number) {
5e2afe42 464 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
84cae54e 465
8ebf2a5d 466 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
5e2afe42 467 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false })
8ebf2a5d
C
468 : []
469
84cae54e
C
470 if (resolutionsEnabled.length === 0) {
471 return [ originResolution ]
472 }
473
474 return resolutionsEnabled
8ebf2a5d
C
475 }
476
764b1a14
C
477 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
478 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
8ebf2a5d 479
764b1a14
C
480 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
481 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
8ebf2a5d 482
764b1a14
C
483 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
484 playlist.type = VideoStreamingPlaylistType.HLS
485
486 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
487
cfd57d2c
C
488 playlist.storage = CONFIG.OBJECT_STORAGE.ENABLED
489 ? VideoStorage.OBJECT_STORAGE
490 : VideoStorage.FILE_SYSTEM
491
764b1a14 492 return playlist.save()
8ebf2a5d
C
493 }
494
26e3e98f
C
495 private saveStartingSession (videoLive: MVideoLiveVideo) {
496 const liveSession = new VideoLiveSessionModel({
497 startDate: new Date(),
c8fa571f
C
498 liveVideoId: videoLive.videoId,
499 saveReplay: videoLive.saveReplay,
500 endingProcessed: false
26e3e98f
C
501 })
502
503 return liveSession.save()
504 }
505
506 private async saveEndingSession (videoId: number, error: LiveVideoError | null) {
507 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoId)
0755cb89
C
508 if (!liveSession) return
509
26e3e98f
C
510 liveSession.endDate = new Date()
511 liveSession.error = error
512
513 return liveSession.save()
514 }
515
8ebf2a5d
C
516 static get Instance () {
517 return this.instance || (this.instance = new this())
518 }
519}
520
521// ---------------------------------------------------------------------------
522
523export {
524 LiveManager
525}