]>
Commit | Line | Data |
---|---|---|
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 { | |
6 | computeResolutionsToTranscode, | |
7 | ffprobePromise, | |
8 | getLiveSegmentTime, | |
9 | getVideoStreamBitrate, | |
10 | getVideoStreamDimensionsInfo, | |
11 | getVideoStreamFPS, | |
12 | hasAudioStream | |
13 | } from '@server/helpers/ffmpeg' | |
14 | import { logger, loggerTagsFactory } from '@server/helpers/logger' | |
15 | import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config' | |
16 | import { VIDEO_LIVE } from '@server/initializers/constants' | |
17 | import { UserModel } from '@server/models/user/user' | |
18 | import { VideoModel } from '@server/models/video/video' | |
19 | import { VideoLiveModel } from '@server/models/video/video-live' | |
20 | import { VideoLiveSessionModel } from '@server/models/video/video-live-session' | |
21 | import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' | |
22 | import { MVideo, MVideoLiveSession, MVideoLiveVideo } from '@server/types/models' | |
23 | import { pick, wait } from '@shared/core-utils' | |
24 | import { LiveVideoError, VideoState } from '@shared/models' | |
25 | import { federateVideoIfNeeded } from '../activitypub/videos' | |
26 | import { JobQueue } from '../job-queue' | |
27 | import { getLiveReplayBaseDirectory } from '../paths' | |
28 | import { PeerTubeSocket } from '../peertube-socket' | |
29 | import { Hooks } from '../plugins/hooks' | |
30 | import { LiveQuotaStore } from './live-quota-store' | |
31 | import { cleanupAndDestroyPermanentLive } from './live-utils' | |
32 | import { MuxingSession } from './shared' | |
33 | ||
34 | const NodeRtmpSession = require('node-media-server/src/node_rtmp_session') | |
35 | const context = require('node-media-server/src/node_core_ctx') | |
36 | const nodeMediaServerLogger = require('node-media-server/src/node_core_logger') | |
37 | ||
38 | // Disable node media server logs | |
39 | nodeMediaServerLogger.setLogType(0) | |
40 | ||
41 | const 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 | |
48 | } | |
49 | } | |
50 | ||
51 | const lTags = loggerTagsFactory('live') | |
52 | ||
53 | class LiveManager { | |
54 | ||
55 | private static instance: LiveManager | |
56 | ||
57 | private readonly muxingSessions = new Map<string, MuxingSession>() | |
58 | private readonly videoSessions = new Map<number, string>() | |
59 | ||
60 | private rtmpServer: Server | |
61 | private rtmpsServer: ServerTLS | |
62 | ||
63 | private running = false | |
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 | ||
79 | const session = this.getContext().sessions.get(sessionId) | |
80 | ||
81 | this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2]) | |
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(() => { | |
90 | if (!this.running && CONFIG.LIVE.ENABLED === true) { | |
91 | this.run().catch(err => logger.error('Cannot run live server.', { err })) | |
92 | return | |
93 | } | |
94 | ||
95 | if (this.running && CONFIG.LIVE.ENABLED === false) { | |
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() })) | |
103 | } | |
104 | ||
105 | async run () { | |
106 | this.running = true | |
107 | ||
108 | if (CONFIG.LIVE.RTMP.ENABLED) { | |
109 | logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags()) | |
110 | ||
111 | this.rtmpServer = createServer(socket => { | |
112 | const session = new NodeRtmpSession(config, socket) | |
113 | ||
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 | ||
122 | this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME) | |
123 | } | |
124 | ||
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 | ||
145 | this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME) | |
146 | } | |
147 | } | |
148 | ||
149 | stop () { | |
150 | this.running = false | |
151 | ||
152 | if (this.rtmpServer) { | |
153 | logger.info('Stopping RTMP server.', lTags()) | |
154 | ||
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 | } | |
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 | ||
178 | stopSessionOf (videoId: number, error: LiveVideoError | null) { | |
179 | const sessionId = this.videoSessions.get(videoId) | |
180 | if (!sessionId) return | |
181 | ||
182 | this.saveEndingSession(videoId, error) | |
183 | .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) })) | |
184 | ||
185 | this.videoSessions.delete(videoId) | |
186 | this.abortSession(sessionId) | |
187 | } | |
188 | ||
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) | |
201 | if (muxingSession) { | |
202 | // Muxing session will fire and event so we correctly cleanup the session | |
203 | muxingSession.abort() | |
204 | ||
205 | this.muxingSessions.delete(sessionId) | |
206 | } | |
207 | } | |
208 | ||
209 | private async handleSession (sessionId: string, inputUrl: string, streamKey: string) { | |
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 | ||
222 | // Cleanup old potential live (could happen with a permanent live) | |
223 | const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id) | |
224 | if (oldStreamingPlaylist) { | |
225 | if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid) | |
226 | ||
227 | await cleanupAndDestroyPermanentLive(video, oldStreamingPlaylist) | |
228 | } | |
229 | ||
230 | this.videoSessions.set(video.id, sessionId) | |
231 | ||
232 | const now = Date.now() | |
233 | const probe = await ffprobePromise(inputUrl) | |
234 | ||
235 | const [ { resolution, ratio }, fps, bitrate, hasAudio ] = await Promise.all([ | |
236 | getVideoStreamDimensionsInfo(inputUrl, probe), | |
237 | getVideoStreamFPS(inputUrl, probe), | |
238 | getVideoStreamBitrate(inputUrl, probe), | |
239 | hasAudioStream(inputUrl, probe) | |
240 | ]) | |
241 | ||
242 | logger.info( | |
243 | '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)', | |
244 | inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid) | |
245 | ) | |
246 | ||
247 | const allResolutions = await Hooks.wrapObject( | |
248 | this.buildAllResolutionsToTranscode(resolution, hasAudio), | |
249 | 'filter:transcoding.auto.resolutions-to-transcode.result', | |
250 | { video } | |
251 | ) | |
252 | ||
253 | logger.info( | |
254 | 'Will mux/transcode live video of original resolution %d.', resolution, | |
255 | { allResolutions, ...lTags(sessionId, video.uuid) } | |
256 | ) | |
257 | ||
258 | return this.runMuxingSession({ | |
259 | sessionId, | |
260 | videoLive, | |
261 | ||
262 | inputUrl, | |
263 | fps, | |
264 | bitrate, | |
265 | ratio, | |
266 | allResolutions, | |
267 | hasAudio | |
268 | }) | |
269 | } | |
270 | ||
271 | private async runMuxingSession (options: { | |
272 | sessionId: string | |
273 | videoLive: MVideoLiveVideo | |
274 | ||
275 | inputUrl: string | |
276 | fps: number | |
277 | bitrate: number | |
278 | ratio: number | |
279 | allResolutions: number[] | |
280 | hasAudio: boolean | |
281 | }) { | |
282 | const { sessionId, videoLive } = options | |
283 | const videoUUID = videoLive.Video.uuid | |
284 | const localLTags = lTags(sessionId, videoUUID) | |
285 | ||
286 | const liveSession = await this.saveStartingSession(videoLive) | |
287 | ||
288 | const user = await UserModel.loadByLiveId(videoLive.id) | |
289 | LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id) | |
290 | ||
291 | const muxingSession = new MuxingSession({ | |
292 | context: this.getContext(), | |
293 | sessionId, | |
294 | videoLive, | |
295 | user, | |
296 | ||
297 | ...pick(options, [ 'inputUrl', 'bitrate', 'ratio', 'fps', 'allResolutions', 'hasAudio' ]) | |
298 | }) | |
299 | ||
300 | muxingSession.on('live-ready', () => this.publishAndFederateLive(videoLive, localLTags)) | |
301 | ||
302 | muxingSession.on('bad-socket-health', ({ videoId }) => { | |
303 | logger.error( | |
304 | 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' + | |
305 | ' Stopping session of video %s.', videoUUID, | |
306 | localLTags | |
307 | ) | |
308 | ||
309 | this.stopSessionOf(videoId, LiveVideoError.BAD_SOCKET_HEALTH) | |
310 | }) | |
311 | ||
312 | muxingSession.on('duration-exceeded', ({ videoId }) => { | |
313 | logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags) | |
314 | ||
315 | this.stopSessionOf(videoId, LiveVideoError.DURATION_EXCEEDED) | |
316 | }) | |
317 | ||
318 | muxingSession.on('quota-exceeded', ({ videoId }) => { | |
319 | logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags) | |
320 | ||
321 | this.stopSessionOf(videoId, LiveVideoError.QUOTA_EXCEEDED) | |
322 | }) | |
323 | ||
324 | muxingSession.on('ffmpeg-error', ({ videoId }) => { | |
325 | this.stopSessionOf(videoId, LiveVideoError.FFMPEG_ERROR) | |
326 | }) | |
327 | ||
328 | muxingSession.on('ffmpeg-end', ({ videoId }) => { | |
329 | this.onMuxingFFmpegEnd(videoId, sessionId) | |
330 | }) | |
331 | ||
332 | muxingSession.on('after-cleanup', ({ videoId }) => { | |
333 | this.muxingSessions.delete(sessionId) | |
334 | ||
335 | LiveQuotaStore.Instance.removeLive(user.id, videoLive.id) | |
336 | ||
337 | muxingSession.destroy() | |
338 | ||
339 | return this.onAfterMuxingCleanup({ videoId, liveSession }) | |
340 | .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags })) | |
341 | }) | |
342 | ||
343 | this.muxingSessions.set(sessionId, muxingSession) | |
344 | ||
345 | muxingSession.runMuxing() | |
346 | .catch(err => { | |
347 | logger.error('Cannot run muxing.', { err, ...localLTags }) | |
348 | this.abortSession(sessionId) | |
349 | }) | |
350 | } | |
351 | ||
352 | private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) { | |
353 | const videoId = live.videoId | |
354 | ||
355 | try { | |
356 | const video = await VideoModel.loadFull(videoId) | |
357 | ||
358 | logger.info('Will publish and federate live %s.', video.url, localLTags) | |
359 | ||
360 | video.state = VideoState.PUBLISHED | |
361 | video.publishedAt = new Date() | |
362 | await video.save() | |
363 | ||
364 | live.Video = video | |
365 | ||
366 | await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION) | |
367 | ||
368 | try { | |
369 | await federateVideoIfNeeded(video, false) | |
370 | } catch (err) { | |
371 | logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }) | |
372 | } | |
373 | ||
374 | PeerTubeSocket.Instance.sendVideoLiveNewState(video) | |
375 | } catch (err) { | |
376 | logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags }) | |
377 | } | |
378 | } | |
379 | ||
380 | private onMuxingFFmpegEnd (videoId: number, sessionId: string) { | |
381 | this.videoSessions.delete(videoId) | |
382 | ||
383 | this.saveEndingSession(videoId, null) | |
384 | .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) })) | |
385 | } | |
386 | ||
387 | private async onAfterMuxingCleanup (options: { | |
388 | videoId: number | string | |
389 | liveSession?: MVideoLiveSession | |
390 | cleanupNow?: boolean // Default false | |
391 | }) { | |
392 | const { videoId, liveSession: liveSessionArg, cleanupNow = false } = options | |
393 | ||
394 | try { | |
395 | const fullVideo = await VideoModel.loadFull(videoId) | |
396 | if (!fullVideo) return | |
397 | ||
398 | const live = await VideoLiveModel.loadByVideoId(fullVideo.id) | |
399 | ||
400 | const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id) | |
401 | ||
402 | // On server restart during a live | |
403 | if (!liveSession.endDate) { | |
404 | liveSession.endDate = new Date() | |
405 | await liveSession.save() | |
406 | } | |
407 | ||
408 | JobQueue.Instance.createJobAsync({ | |
409 | type: 'video-live-ending', | |
410 | payload: { | |
411 | videoId: fullVideo.id, | |
412 | ||
413 | replayDirectory: live.saveReplay | |
414 | ? await this.findReplayDirectory(fullVideo) | |
415 | : undefined, | |
416 | ||
417 | liveSessionId: liveSession.id, | |
418 | streamingPlaylistId: fullVideo.getHLSPlaylist()?.id, | |
419 | ||
420 | publishedAt: fullVideo.publishedAt.toISOString() | |
421 | }, | |
422 | ||
423 | delay: cleanupNow | |
424 | ? 0 | |
425 | : VIDEO_LIVE.CLEANUP_DELAY | |
426 | }) | |
427 | ||
428 | fullVideo.state = live.permanentLive | |
429 | ? VideoState.WAITING_FOR_LIVE | |
430 | : VideoState.LIVE_ENDED | |
431 | ||
432 | await fullVideo.save() | |
433 | ||
434 | PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) | |
435 | ||
436 | await federateVideoIfNeeded(fullVideo, false) | |
437 | } catch (err) { | |
438 | logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') }) | |
439 | } | |
440 | } | |
441 | ||
442 | private async handleBrokenLives () { | |
443 | const videoUUIDs = await VideoModel.listPublishedLiveUUIDs() | |
444 | ||
445 | for (const uuid of videoUUIDs) { | |
446 | await this.onAfterMuxingCleanup({ videoId: uuid, cleanupNow: true }) | |
447 | } | |
448 | } | |
449 | ||
450 | private async findReplayDirectory (video: MVideo) { | |
451 | const directory = getLiveReplayBaseDirectory(video) | |
452 | const files = await readdir(directory) | |
453 | ||
454 | if (files.length === 0) return undefined | |
455 | ||
456 | return join(directory, files.sort().reverse()[0]) | |
457 | } | |
458 | ||
459 | private buildAllResolutionsToTranscode (originResolution: number, hasAudio: boolean) { | |
460 | const includeInput = CONFIG.LIVE.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION | |
461 | ||
462 | const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED | |
463 | ? computeResolutionsToTranscode({ input: originResolution, type: 'live', includeInput, strictLower: false, hasAudio }) | |
464 | : [] | |
465 | ||
466 | if (resolutionsEnabled.length === 0) { | |
467 | return [ originResolution ] | |
468 | } | |
469 | ||
470 | return resolutionsEnabled | |
471 | } | |
472 | ||
473 | private saveStartingSession (videoLive: MVideoLiveVideo) { | |
474 | const liveSession = new VideoLiveSessionModel({ | |
475 | startDate: new Date(), | |
476 | liveVideoId: videoLive.videoId, | |
477 | saveReplay: videoLive.saveReplay, | |
478 | endingProcessed: false | |
479 | }) | |
480 | ||
481 | return liveSession.save() | |
482 | } | |
483 | ||
484 | private async saveEndingSession (videoId: number, error: LiveVideoError | null) { | |
485 | const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoId) | |
486 | if (!liveSession) return | |
487 | ||
488 | liveSession.endDate = new Date() | |
489 | liveSession.error = error | |
490 | ||
491 | return liveSession.save() | |
492 | } | |
493 | ||
494 | static get Instance () { | |
495 | return this.instance || (this.instance = new this()) | |
496 | } | |
497 | } | |
498 | ||
499 | // --------------------------------------------------------------------------- | |
500 | ||
501 | export { | |
502 | LiveManager | |
503 | } |