]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/live-manager.ts
6d51f4de7c005385094298ffeb947ceeb8616dd1
[github/Chocobozzz/PeerTube.git] / server / lib / live / live-manager.ts
1 import { readdir, readFile } from 'fs-extra'
2 import { createServer, Server } from 'net'
3 import { join } from 'path'
4 import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
5 import { logger, loggerTagsFactory } from '@server/helpers/logger'
6 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
7 import { VIDEO_LIVE } from '@server/initializers/constants'
8 import { sequelizeTypescript } from '@server/initializers/database'
9 import { RunnerJobModel } from '@server/models/runner/runner-job'
10 import { UserModel } from '@server/models/user/user'
11 import { VideoModel } from '@server/models/video/video'
12 import { VideoLiveModel } from '@server/models/video/video-live'
13 import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting'
14 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
15 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
16 import { MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models'
17 import { pick, wait } from '@shared/core-utils'
18 import { ffprobePromise, getVideoStreamBitrate, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
19 import { LiveVideoError, VideoState } from '@shared/models'
20 import { federateVideoIfNeeded } from '../activitypub/videos'
21 import { JobQueue } from '../job-queue'
22 import { getLiveReplayBaseDirectory } from '../paths'
23 import { PeerTubeSocket } from '../peertube-socket'
24 import { Hooks } from '../plugins/hooks'
25 import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions'
26 import { LiveQuotaStore } from './live-quota-store'
27 import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } from './live-utils'
28 import { MuxingSession } from './shared'
29
30 const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
31 const context = require('node-media-server/src/node_core_ctx')
32 const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
33
34 // Disable node media server logs
35 nodeMediaServerLogger.setLogType(0)
36
37 const 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
44 }
45 }
46
47 const lTags = loggerTagsFactory('live')
48
49 class LiveManager {
50
51 private static instance: LiveManager
52
53 private readonly muxingSessions = new Map<string, MuxingSession>()
54 private readonly videoSessions = new Map<string, string>()
55
56 private rtmpServer: Server
57 private rtmpsServer: ServerTLS
58
59 private running = false
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
75 const session = this.getContext().sessions.get(sessionId)
76
77 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
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 // Force session aborting, so we kill ffmpeg even if it still has data to process (slow CPU)
85 setTimeout(() => this.abortSession(sessionId), 2000)
86 })
87
88 registerConfigChangedHandler(() => {
89 if (!this.running && CONFIG.LIVE.ENABLED === true) {
90 this.run().catch(err => logger.error('Cannot run live server.', { err }))
91 return
92 }
93
94 if (this.running && CONFIG.LIVE.ENABLED === false) {
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() }))
102 }
103
104 async run () {
105 this.running = true
106
107 if (CONFIG.LIVE.RTMP.ENABLED) {
108 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
109
110 this.rtmpServer = createServer(socket => {
111 const session = new NodeRtmpSession(config, socket)
112
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
121 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
122 }
123
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
144 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
145 }
146 }
147
148 stop () {
149 this.running = false
150
151 if (this.rtmpServer) {
152 logger.info('Stopping RTMP server.', lTags())
153
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 }
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
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 }
183
184 logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })
185
186 this.saveEndingSession(videoUUID, error)
187 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))
188
189 this.videoSessions.delete(videoUUID)
190 this.abortSession(sessionId)
191 }
192
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)
205 if (muxingSession) {
206 // Muxing session will fire and event so we correctly cleanup the session
207 muxingSession.abort()
208
209 this.muxingSessions.delete(sessionId)
210 }
211 }
212
213 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
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
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
231 // Cleanup old potential live (could happen with a permanent live)
232 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
233 if (oldStreamingPlaylist) {
234 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
235
236 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
237 }
238
239 this.videoSessions.set(video.uuid, sessionId)
240
241 const now = Date.now()
242 const probe = await ffprobePromise(inputUrl)
243
244 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
245 getVideoStreamDimensionsInfo(inputUrl, probe),
246 getVideoStreamFPS(inputUrl, probe),
247 getVideoStreamBitrate(inputUrl, probe),
248 hasAudioStream(inputUrl, probe)
249 ])
250
251 logger.info(
252 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
253 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
254 )
255
256 const allResolutions = await Hooks.wrapObject(
257 this.buildAllResolutionsToTranscode(resolution, hasAudio),
258 'filter:transcoding.auto.resolutions-to-transcode.result',
259 { video }
260 )
261
262 logger.info(
263 'Handling live video of original resolution %d.', resolution,
264 { allResolutions, ...lTags(sessionId, video.uuid) }
265 )
266
267 return this.runMuxingSession({
268 sessionId,
269 videoLive,
270
271 inputUrl,
272 fps,
273 bitrate,
274 ratio,
275 allResolutions,
276 hasAudio
277 })
278 }
279
280 private async runMuxingSession (options: {
281 sessionId: string
282 videoLive: MVideoLiveVideoWithSetting
283
284 inputUrl: string
285 fps: number
286 bitrate: number
287 ratio: number
288 allResolutions: number[]
289 hasAudio: boolean
290 }) {
291 const { sessionId, videoLive } = options
292 const videoUUID = videoLive.Video.uuid
293 const localLTags = lTags(sessionId, videoUUID)
294
295 const liveSession = await this.saveStartingSession(videoLive)
296
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(),
302 sessionId,
303 videoLive,
304 user,
305
306 ...pick(options, [ 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
307 })
308
309 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
310
311 muxingSession.on('bad-socket-health', ({ videoUUID }) => {
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
318 this.stopSessionOf(videoUUID, LiveVideoError.BAD_SOCKET_HEALTH)
319 })
320
321 muxingSession.on('duration-exceeded', ({ videoUUID }) => {
322 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
323
324 this.stopSessionOf(videoUUID, LiveVideoError.DURATION_EXCEEDED)
325 })
326
327 muxingSession.on('quota-exceeded', ({ videoUUID }) => {
328 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
329
330 this.stopSessionOf(videoUUID, LiveVideoError.QUOTA_EXCEEDED)
331 })
332
333 muxingSession.on('transcoding-error', ({ videoUUID }) => {
334 this.stopSessionOf(videoUUID, LiveVideoError.FFMPEG_ERROR)
335 })
336
337 muxingSession.on('transcoding-end', ({ videoUUID }) => {
338 this.onMuxingFFmpegEnd(videoUUID, sessionId)
339 })
340
341 muxingSession.on('after-cleanup', ({ videoUUID }) => {
342 this.muxingSessions.delete(sessionId)
343
344 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
345
346 muxingSession.destroy()
347
348 return this.onAfterMuxingCleanup({ videoUUID, liveSession })
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 {
365 const video = await VideoModel.loadFull(videoId)
366
367 logger.info('Will publish and federate live %s.', video.url, localLTags)
368
369 video.state = VideoState.PUBLISHED
370 video.publishedAt = new Date()
371 await video.save()
372
373 live.Video = video
374
375 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
376
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)
384 } catch (err) {
385 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
386 }
387 }
388
389 private onMuxingFFmpegEnd (videoUUID: string, sessionId: string) {
390 // Session already cleaned up
391 if (!this.videoSessions.has(videoUUID)) return
392
393 this.videoSessions.delete(videoUUID)
394
395 this.saveEndingSession(videoUUID, null)
396 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
397 }
398
399 private async onAfterMuxingCleanup (options: {
400 videoUUID: string
401 liveSession?: MVideoLiveSession
402 cleanupNow?: boolean // Default false
403 }) {
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))
407
408 try {
409 const fullVideo = await VideoModel.loadFull(videoUUID)
410 if (!fullVideo) return
411
412 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
413
414 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
415
416 // On server restart during a live
417 if (!liveSession.endDate) {
418 liveSession.endDate = new Date()
419 await liveSession.save()
420 }
421
422 JobQueue.Instance.createJobAsync({
423 type: 'video-live-ending',
424 payload: {
425 videoId: fullVideo.id,
426
427 replayDirectory: live.saveReplay
428 ? await this.findReplayDirectory(fullVideo)
429 : undefined,
430
431 liveSessionId: liveSession.id,
432 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
433
434 publishedAt: fullVideo.publishedAt.toISOString()
435 },
436
437 delay: cleanupNow
438 ? 0
439 : VIDEO_LIVE.CLEANUP_DELAY
440 })
441
442 fullVideo.state = live.permanentLive
443 ? VideoState.WAITING_FOR_LIVE
444 : VideoState.LIVE_ENDED
445
446 await fullVideo.save()
447
448 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
449
450 await federateVideoIfNeeded(fullVideo, false)
451 } catch (err) {
452 logger.error('Cannot save/federate new video state of live streaming of video %s.', videoUUID, { err, ...lTags(videoUUID) })
453 }
454 }
455
456 private async handleBrokenLives () {
457 await RunnerJobModel.cancelAllJobs({ type: 'live-rtmp-hls-transcoding' })
458
459 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
460
461 for (const uuid of videoUUIDs) {
462 await this.onAfterMuxingCleanup({ videoUUID: uuid, cleanupNow: true })
463 }
464 }
465
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
475 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
476 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
477
478 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
479 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
480 : []
481
482 if (resolutionsEnabled.length === 0) {
483 return [ originResolution ]
484 }
485
486 return resolutionsEnabled
487 }
488
489 private async saveStartingSession (videoLive: MVideoLiveVideoWithSetting) {
490 const replaySettings = videoLive.saveReplay
491 ? new VideoLiveReplaySettingModel({
492 privacy: videoLive.ReplaySetting.privacy
493 })
494 : null
495
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 })
509 }
510
511 private async saveEndingSession (videoUUID: string, error: LiveVideoError | null) {
512 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoUUID)
513 if (!liveSession) return
514
515 liveSession.endDate = new Date()
516 liveSession.error = error
517
518 return liveSession.save()
519 }
520
521 static get Instance () {
522 return this.instance || (this.instance = new this())
523 }
524 }
525
526 // ---------------------------------------------------------------------------
527
528 export {
529 LiveManager
530 }