]>
Commit | Line | Data |
---|---|---|
1 | ||
2 | import { readFile } from 'fs-extra' | |
3 | import { createServer, Server } from 'net' | |
4 | import { createServer as createServerTLS, Server as ServerTLS } from 'tls' | |
5 | import { | |
6 | computeResolutionsToTranscode, | |
7 | ffprobePromise, | |
8 | getVideoFileBitrate, | |
9 | getVideoFileFPS, | |
10 | getVideoFileResolution | |
11 | } from '@server/helpers/ffprobe-utils' | |
12 | import { logger, loggerTagsFactory } from '@server/helpers/logger' | |
13 | import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config' | |
14 | import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants' | |
15 | import { UserModel } from '@server/models/user/user' | |
16 | import { VideoModel } from '@server/models/video/video' | |
17 | import { VideoLiveModel } from '@server/models/video/video-live' | |
18 | import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' | |
19 | import { MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models' | |
20 | import { VideoState, VideoStreamingPlaylistType } from '@shared/models' | |
21 | import { federateVideoIfNeeded } from '../activitypub/videos' | |
22 | import { JobQueue } from '../job-queue' | |
23 | import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../paths' | |
24 | import { PeerTubeSocket } from '../peertube-socket' | |
25 | import { LiveQuotaStore } from './live-quota-store' | |
26 | import { LiveSegmentShaStore } from './live-segment-sha-store' | |
27 | import { cleanupLive } 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<number, 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) | |
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) | |
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 (videoId: number) { | |
175 | const sessionId = this.videoSessions.get(videoId) | |
176 | if (!sessionId) return | |
177 | ||
178 | this.videoSessions.delete(videoId) | |
179 | this.abortSession(sessionId) | |
180 | } | |
181 | ||
182 | private getContext () { | |
183 | return context | |
184 | } | |
185 | ||
186 | private abortSession (sessionId: string) { | |
187 | const session = this.getContext().sessions.get(sessionId) | |
188 | if (session) { | |
189 | session.stop() | |
190 | this.getContext().sessions.delete(sessionId) | |
191 | } | |
192 | ||
193 | const muxingSession = this.muxingSessions.get(sessionId) | |
194 | if (muxingSession) { | |
195 | // Muxing session will fire and event so we correctly cleanup the session | |
196 | muxingSession.abort() | |
197 | ||
198 | this.muxingSessions.delete(sessionId) | |
199 | } | |
200 | } | |
201 | ||
202 | private async handleSession (sessionId: string, inputUrl: string, streamKey: string) { | |
203 | const videoLive = await VideoLiveModel.loadByStreamKey(streamKey) | |
204 | if (!videoLive) { | |
205 | logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId)) | |
206 | return this.abortSession(sessionId) | |
207 | } | |
208 | ||
209 | const video = videoLive.Video | |
210 | if (video.isBlacklisted()) { | |
211 | logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid)) | |
212 | return this.abortSession(sessionId) | |
213 | } | |
214 | ||
215 | // Cleanup old potential live files (could happen with a permanent live) | |
216 | LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid) | |
217 | ||
218 | const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id) | |
219 | if (oldStreamingPlaylist) { | |
220 | await cleanupLive(video, oldStreamingPlaylist) | |
221 | } | |
222 | ||
223 | this.videoSessions.set(video.id, sessionId) | |
224 | ||
225 | const now = Date.now() | |
226 | const probe = await ffprobePromise(inputUrl) | |
227 | ||
228 | const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([ | |
229 | getVideoFileResolution(inputUrl, probe), | |
230 | getVideoFileFPS(inputUrl, probe), | |
231 | getVideoFileBitrate(inputUrl, probe) | |
232 | ]) | |
233 | ||
234 | logger.info( | |
235 | '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)', | |
236 | inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid) | |
237 | ) | |
238 | ||
239 | const allResolutions = this.buildAllResolutionsToTranscode(resolution) | |
240 | ||
241 | logger.info( | |
242 | 'Will mux/transcode live video of original resolution %d.', resolution, | |
243 | { allResolutions, ...lTags(sessionId, video.uuid) } | |
244 | ) | |
245 | ||
246 | const streamingPlaylist = await this.createLivePlaylist(video, allResolutions) | |
247 | ||
248 | return this.runMuxingSession({ | |
249 | sessionId, | |
250 | videoLive, | |
251 | streamingPlaylist, | |
252 | inputUrl, | |
253 | fps, | |
254 | bitrate, | |
255 | ratio, | |
256 | allResolutions | |
257 | }) | |
258 | } | |
259 | ||
260 | private async runMuxingSession (options: { | |
261 | sessionId: string | |
262 | videoLive: MVideoLiveVideo | |
263 | streamingPlaylist: MStreamingPlaylistVideo | |
264 | inputUrl: string | |
265 | fps: number | |
266 | bitrate: number | |
267 | ratio: number | |
268 | allResolutions: number[] | |
269 | }) { | |
270 | const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options | |
271 | const videoUUID = videoLive.Video.uuid | |
272 | const localLTags = lTags(sessionId, videoUUID) | |
273 | ||
274 | const user = await UserModel.loadByLiveId(videoLive.id) | |
275 | LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id) | |
276 | ||
277 | const muxingSession = new MuxingSession({ | |
278 | context: this.getContext(), | |
279 | user, | |
280 | sessionId, | |
281 | videoLive, | |
282 | streamingPlaylist, | |
283 | inputUrl, | |
284 | bitrate, | |
285 | ratio, | |
286 | fps, | |
287 | allResolutions | |
288 | }) | |
289 | ||
290 | muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags)) | |
291 | ||
292 | muxingSession.on('bad-socket-health', ({ videoId }) => { | |
293 | logger.error( | |
294 | 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' + | |
295 | ' Stopping session of video %s.', videoUUID, | |
296 | localLTags | |
297 | ) | |
298 | ||
299 | this.stopSessionOf(videoId) | |
300 | }) | |
301 | ||
302 | muxingSession.on('duration-exceeded', ({ videoId }) => { | |
303 | logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags) | |
304 | ||
305 | this.stopSessionOf(videoId) | |
306 | }) | |
307 | ||
308 | muxingSession.on('quota-exceeded', ({ videoId }) => { | |
309 | logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags) | |
310 | ||
311 | this.stopSessionOf(videoId) | |
312 | }) | |
313 | ||
314 | muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId)) | |
315 | muxingSession.on('ffmpeg-end', ({ videoId }) => { | |
316 | this.onMuxingFFmpegEnd(videoId) | |
317 | }) | |
318 | ||
319 | muxingSession.on('after-cleanup', ({ videoId }) => { | |
320 | this.muxingSessions.delete(sessionId) | |
321 | ||
322 | muxingSession.destroy() | |
323 | ||
324 | return this.onAfterMuxingCleanup(videoId) | |
325 | .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags })) | |
326 | }) | |
327 | ||
328 | this.muxingSessions.set(sessionId, muxingSession) | |
329 | ||
330 | muxingSession.runMuxing() | |
331 | .catch(err => { | |
332 | logger.error('Cannot run muxing.', { err, ...localLTags }) | |
333 | this.abortSession(sessionId) | |
334 | }) | |
335 | } | |
336 | ||
337 | private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) { | |
338 | const videoId = live.videoId | |
339 | ||
340 | try { | |
341 | const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) | |
342 | ||
343 | logger.info('Will publish and federate live %s.', video.url, localLTags) | |
344 | ||
345 | video.state = VideoState.PUBLISHED | |
346 | await video.save() | |
347 | ||
348 | live.Video = video | |
349 | ||
350 | setTimeout(() => { | |
351 | federateVideoIfNeeded(video, false) | |
352 | .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })) | |
353 | ||
354 | PeerTubeSocket.Instance.sendVideoLiveNewState(video) | |
355 | }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION) | |
356 | } catch (err) { | |
357 | logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags }) | |
358 | } | |
359 | } | |
360 | ||
361 | private onMuxingFFmpegEnd (videoId: number) { | |
362 | this.videoSessions.delete(videoId) | |
363 | } | |
364 | ||
365 | private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) { | |
366 | try { | |
367 | const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID) | |
368 | if (!fullVideo) return | |
369 | ||
370 | const live = await VideoLiveModel.loadByVideoId(fullVideo.id) | |
371 | ||
372 | if (!live.permanentLive) { | |
373 | JobQueue.Instance.createJob({ | |
374 | type: 'video-live-ending', | |
375 | payload: { | |
376 | videoId: fullVideo.id | |
377 | } | |
378 | }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY }) | |
379 | ||
380 | fullVideo.state = VideoState.LIVE_ENDED | |
381 | } else { | |
382 | fullVideo.state = VideoState.WAITING_FOR_LIVE | |
383 | } | |
384 | ||
385 | await fullVideo.save() | |
386 | ||
387 | PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) | |
388 | ||
389 | await federateVideoIfNeeded(fullVideo, false) | |
390 | } catch (err) { | |
391 | logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) }) | |
392 | } | |
393 | } | |
394 | ||
395 | private async handleBrokenLives () { | |
396 | const videoUUIDs = await VideoModel.listPublishedLiveUUIDs() | |
397 | ||
398 | for (const uuid of videoUUIDs) { | |
399 | await this.onAfterMuxingCleanup(uuid, true) | |
400 | } | |
401 | } | |
402 | ||
403 | private buildAllResolutionsToTranscode (originResolution: number) { | |
404 | const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED | |
405 | ? computeResolutionsToTranscode(originResolution, 'live') | |
406 | : [] | |
407 | ||
408 | return resolutionsEnabled.concat([ originResolution ]) | |
409 | } | |
410 | ||
411 | private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> { | |
412 | const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video) | |
413 | ||
414 | playlist.playlistFilename = generateHLSMasterPlaylistFilename(true) | |
415 | playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true) | |
416 | ||
417 | playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION | |
418 | playlist.type = VideoStreamingPlaylistType.HLS | |
419 | ||
420 | playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions) | |
421 | ||
422 | return playlist.save() | |
423 | } | |
424 | ||
425 | static get Instance () { | |
426 | return this.instance || (this.instance = new this()) | |
427 | } | |
428 | } | |
429 | ||
430 | // --------------------------------------------------------------------------- | |
431 | ||
432 | export { | |
433 | LiveManager | |
434 | } |