]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/live-manager.ts
Don't save the session twice
[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 { UserModel } from '@server/models/user/user'
10 import { VideoModel } from '@server/models/video/video'
11 import { VideoLiveModel } from '@server/models/video/video-live'
12 import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting'
13 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
14 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
15 import { MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models'
16 import { pick, wait } from '@shared/core-utils'
17 import { ffprobePromise, getVideoStreamBitrate, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
18 import { LiveVideoError, VideoState } from '@shared/models'
19 import { federateVideoIfNeeded } from '../activitypub/videos'
20 import { JobQueue } from '../job-queue'
21 import { getLiveReplayBaseDirectory } from '../paths'
22 import { PeerTubeSocket } from '../peertube-socket'
23 import { Hooks } from '../plugins/hooks'
24 import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions'
25 import { LiveQuotaStore } from './live-quota-store'
26 import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } from './live-utils'
27 import { MuxingSession } from './shared'
28 import { RunnerJobModel } from '@server/models/runner/runner-job'
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
85 registerConfigChangedHandler(() => {
86 if (!this.running && CONFIG.LIVE.ENABLED === true) {
87 this.run().catch(err => logger.error('Cannot run live server.', { err }))
88 return
89 }
90
91 if (this.running && CONFIG.LIVE.ENABLED === false) {
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() }))
99 }
100
101 async run () {
102 this.running = true
103
104 if (CONFIG.LIVE.RTMP.ENABLED) {
105 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
106
107 this.rtmpServer = createServer(socket => {
108 const session = new NodeRtmpSession(config, socket)
109
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
118 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
119 }
120
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
141 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
142 }
143 }
144
145 stop () {
146 this.running = false
147
148 if (this.rtmpServer) {
149 logger.info('Stopping RTMP server.', lTags())
150
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 }
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
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 }
180
181 logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })
182
183 this.saveEndingSession(videoUUID, error)
184 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))
185
186 this.videoSessions.delete(videoUUID)
187 this.abortSession(sessionId)
188 }
189
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)
202 if (muxingSession) {
203 // Muxing session will fire and event so we correctly cleanup the session
204 muxingSession.abort()
205
206 this.muxingSessions.delete(sessionId)
207 }
208 }
209
210 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
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
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
228 // Cleanup old potential live (could happen with a permanent live)
229 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
230 if (oldStreamingPlaylist) {
231 if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid)
232
233 await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist)
234 }
235
236 this.videoSessions.set(video.uuid, sessionId)
237
238 const now = Date.now()
239 const probe = await ffprobePromise(inputUrl)
240
241 const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([
242 getVideoStreamDimensionsInfo(inputUrl, probe),
243 getVideoStreamFPS(inputUrl, probe),
244 getVideoStreamBitrate(inputUrl, probe),
245 hasAudioStream(inputUrl, probe)
246 ])
247
248 logger.info(
249 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
250 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
251 )
252
253 const allResolutions = await Hooks.wrapObject(
254 this.buildAllResolutionsToTranscode(resolution, hasAudio),
255 'filter:transcoding.auto.resolutions-to-transcode.result',
256 { video }
257 )
258
259 logger.info(
260 'Handling live video of original resolution %d.', resolution,
261 { allResolutions, ...lTags(sessionId, video.uuid) }
262 )
263
264 return this.runMuxingSession({
265 sessionId,
266 videoLive,
267
268 inputUrl,
269 fps,
270 bitrate,
271 ratio,
272 allResolutions,
273 hasAudio
274 })
275 }
276
277 private async runMuxingSession (options: {
278 sessionId: string
279 videoLive: MVideoLiveVideoWithSetting
280
281 inputUrl: string
282 fps: number
283 bitrate: number
284 ratio: number
285 allResolutions: number[]
286 hasAudio: boolean
287 }) {
288 const { sessionId, videoLive } = options
289 const videoUUID = videoLive.Video.uuid
290 const localLTags = lTags(sessionId, videoUUID)
291
292 const liveSession = await this.saveStartingSession(videoLive)
293
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(),
299 sessionId,
300 videoLive,
301 user,
302
303 ...pick(options, [ 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ])
304 })
305
306 muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags))
307
308 muxingSession.on('bad-socket-health', ({ videoUUID }) => {
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
315 this.stopSessionOf(videoUUID, LiveVideoError.BAD_SOCKET_HEALTH)
316 })
317
318 muxingSession.on('duration-exceeded', ({ videoUUID }) => {
319 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
320
321 this.stopSessionOf(videoUUID, LiveVideoError.DURATION_EXCEEDED)
322 })
323
324 muxingSession.on('quota-exceeded', ({ videoUUID }) => {
325 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
326
327 this.stopSessionOf(videoUUID, LiveVideoError.QUOTA_EXCEEDED)
328 })
329
330 muxingSession.on('transcoding-error', ({ videoUUID }) => {
331 this.stopSessionOf(videoUUID, LiveVideoError.FFMPEG_ERROR)
332 })
333
334 muxingSession.on('transcoding-end', ({ videoUUID }) => {
335 this.onMuxingFFmpegEnd(videoUUID, sessionId)
336 })
337
338 muxingSession.on('after-cleanup', ({ videoUUID }) => {
339 this.muxingSessions.delete(sessionId)
340
341 LiveQuotaStore.Instance.removeLive(user.id, videoLive.id)
342
343 muxingSession.destroy()
344
345 return this.onAfterMuxingCleanup({ videoUUID, liveSession })
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 {
362 const video = await VideoModel.loadFull(videoId)
363
364 logger.info('Will publish and federate live %s.', video.url, localLTags)
365
366 video.state = VideoState.PUBLISHED
367 video.publishedAt = new Date()
368 await video.save()
369
370 live.Video = video
371
372 await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
373
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)
381 } catch (err) {
382 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
383 }
384 }
385
386 private onMuxingFFmpegEnd (videoUUID: string, sessionId: string) {
387 // Session already cleaned up
388 if (!this.videoSessions.has(videoUUID)) return
389
390 this.videoSessions.delete(videoUUID)
391
392 this.saveEndingSession(videoUUID, null)
393 .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) }))
394 }
395
396 private async onAfterMuxingCleanup (options: {
397 videoUUID: string
398 liveSession?: MVideoLiveSession
399 cleanupNow?: boolean // Default false
400 }) {
401 const { videoUUID, liveSession: liveSessionArg, cleanupNow = false } = options
402
403 logger.debug('Live of video %s has been cleaned up. Moving to its next state.', videoUUID, lTags(videoUUID))
404
405 try {
406 const fullVideo = await VideoModel.loadFull(videoUUID)
407 if (!fullVideo) return
408
409 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
410
411 const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)
412
413 // On server restart during a live
414 if (!liveSession.endDate) {
415 liveSession.endDate = new Date()
416 await liveSession.save()
417 }
418
419 JobQueue.Instance.createJobAsync({
420 type: 'video-live-ending',
421 payload: {
422 videoId: fullVideo.id,
423
424 replayDirectory: live.saveReplay
425 ? await this.findReplayDirectory(fullVideo)
426 : undefined,
427
428 liveSessionId: liveSession.id,
429 streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
430
431 publishedAt: fullVideo.publishedAt.toISOString()
432 },
433
434 delay: cleanupNow
435 ? 0
436 : VIDEO_LIVE.CLEANUP_DELAY
437 })
438
439 fullVideo.state = live.permanentLive
440 ? VideoState.WAITING_FOR_LIVE
441 : VideoState.LIVE_ENDED
442
443 await fullVideo.save()
444
445 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
446
447 await federateVideoIfNeeded(fullVideo, false)
448 } catch (err) {
449 logger.error('Cannot save/federate new video state of live streaming of video %s.', videoUUID, { err, ...lTags(videoUUID) })
450 }
451 }
452
453 private async handleBrokenLives () {
454 await RunnerJobModel.cancelAllJobs({ type: 'live-rtmp-hls-transcoding' })
455
456 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
457
458 for (const uuid of videoUUIDs) {
459 await this.onAfterMuxingCleanup({ videoUUID: uuid, cleanupNow: true })
460 }
461 }
462
463 private async findReplayDirectory (video: MVideo) {
464 const directory = getLiveReplayBaseDirectory(video)
465 const files = await readdir(directory)
466
467 if (files.length === 0) return undefined
468
469 return join(directory, files.sort().reverse()[0])
470 }
471
472 private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) {
473 const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
474
475 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
476 ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio })
477 : []
478
479 if (resolutionsEnabled.length === 0) {
480 return [ originResolution ]
481 }
482
483 return resolutionsEnabled
484 }
485
486 private async saveStartingSession (videoLive: MVideoLiveVideoWithSetting) {
487 const replaySettings = videoLive.saveReplay
488 ? new VideoLiveReplaySettingModel({
489 privacy: videoLive.ReplaySetting.privacy
490 })
491 : null
492
493 return sequelizeTypescript.transaction(async t => {
494 if (videoLive.saveReplay) {
495 await replaySettings.save({ transaction: t })
496 }
497
498 return VideoLiveSessionModel.create({
499 startDate: new Date(),
500 liveVideoId: videoLive.videoId,
501 saveReplay: videoLive.saveReplay,
502 replaySettingId: videoLive.saveReplay ? replaySettings.id : null,
503 endingProcessed: false
504 }, { transaction: t })
505 })
506 }
507
508 private async saveEndingSession (videoUUID: string, error: LiveVideoError | null) {
509 const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoUUID)
510 if (!liveSession) return
511
512 liveSession.endDate = new Date()
513 liveSession.error = error
514
515 return liveSession.save()
516 }
517
518 static get Instance () {
519 return this.instance || (this.instance = new this())
520 }
521 }
522
523 // ---------------------------------------------------------------------------
524
525 export {
526 LiveManager
527 }