diff options
Diffstat (limited to 'server/lib/live/live-manager.ts')
-rw-r--r-- | server/lib/live/live-manager.ts | 412 |
1 files changed, 412 insertions, 0 deletions
diff --git a/server/lib/live/live-manager.ts b/server/lib/live/live-manager.ts new file mode 100644 index 000000000..d7199cc89 --- /dev/null +++ b/server/lib/live/live-manager.ts | |||
@@ -0,0 +1,412 @@ | |||
1 | |||
2 | import { createServer, Server } from 'net' | ||
3 | import { isTestInstance } from '@server/helpers/core-utils' | ||
4 | import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils' | ||
5 | import { logger, loggerTagsFactory } from '@server/helpers/logger' | ||
6 | import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config' | ||
7 | import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants' | ||
8 | import { UserModel } from '@server/models/user/user' | ||
9 | import { VideoModel } from '@server/models/video/video' | ||
10 | import { VideoLiveModel } from '@server/models/video/video-live' | ||
11 | import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' | ||
12 | import { MStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models' | ||
13 | import { VideoState, VideoStreamingPlaylistType } from '@shared/models' | ||
14 | import { federateVideoIfNeeded } from '../activitypub/videos' | ||
15 | import { JobQueue } from '../job-queue' | ||
16 | import { PeerTubeSocket } from '../peertube-socket' | ||
17 | import { LiveQuotaStore } from './live-quota-store' | ||
18 | import { LiveSegmentShaStore } from './live-segment-sha-store' | ||
19 | import { cleanupLive } from './live-utils' | ||
20 | import { MuxingSession } from './shared' | ||
21 | |||
22 | const NodeRtmpSession = require('node-media-server/node_rtmp_session') | ||
23 | const context = require('node-media-server/node_core_ctx') | ||
24 | const nodeMediaServerLogger = require('node-media-server/node_core_logger') | ||
25 | |||
26 | // Disable node media server logs | ||
27 | nodeMediaServerLogger.setLogType(0) | ||
28 | |||
29 | const config = { | ||
30 | rtmp: { | ||
31 | port: CONFIG.LIVE.RTMP.PORT, | ||
32 | chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE, | ||
33 | gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE, | ||
34 | ping: VIDEO_LIVE.RTMP.PING, | ||
35 | ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT | ||
36 | }, | ||
37 | transcoding: { | ||
38 | ffmpeg: 'ffmpeg' | ||
39 | } | ||
40 | } | ||
41 | |||
42 | const lTags = loggerTagsFactory('live') | ||
43 | |||
44 | class LiveManager { | ||
45 | |||
46 | private static instance: LiveManager | ||
47 | |||
48 | private readonly muxingSessions = new Map<string, MuxingSession>() | ||
49 | private readonly videoSessions = new Map<number, string>() | ||
50 | // Values are Date().getTime() | ||
51 | private readonly watchersPerVideo = new Map<number, number[]>() | ||
52 | |||
53 | private rtmpServer: Server | ||
54 | |||
55 | private constructor () { | ||
56 | } | ||
57 | |||
58 | init () { | ||
59 | const events = this.getContext().nodeEvent | ||
60 | events.on('postPublish', (sessionId: string, streamPath: string) => { | ||
61 | logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) }) | ||
62 | |||
63 | const splittedPath = streamPath.split('/') | ||
64 | if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) { | ||
65 | logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) }) | ||
66 | return this.abortSession(sessionId) | ||
67 | } | ||
68 | |||
69 | this.handleSession(sessionId, streamPath, splittedPath[2]) | ||
70 | .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) })) | ||
71 | }) | ||
72 | |||
73 | events.on('donePublish', sessionId => { | ||
74 | logger.info('Live session ended.', { sessionId, ...lTags(sessionId) }) | ||
75 | }) | ||
76 | |||
77 | registerConfigChangedHandler(() => { | ||
78 | if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) { | ||
79 | this.run() | ||
80 | return | ||
81 | } | ||
82 | |||
83 | if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) { | ||
84 | this.stop() | ||
85 | } | ||
86 | }) | ||
87 | |||
88 | // Cleanup broken lives, that were terminated by a server restart for example | ||
89 | this.handleBrokenLives() | ||
90 | .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() })) | ||
91 | |||
92 | setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE) | ||
93 | } | ||
94 | |||
95 | run () { | ||
96 | logger.info('Running RTMP server on port %d', config.rtmp.port, lTags()) | ||
97 | |||
98 | this.rtmpServer = createServer(socket => { | ||
99 | const session = new NodeRtmpSession(config, socket) | ||
100 | |||
101 | session.run() | ||
102 | }) | ||
103 | |||
104 | this.rtmpServer.on('error', err => { | ||
105 | logger.error('Cannot run RTMP server.', { err, ...lTags() }) | ||
106 | }) | ||
107 | |||
108 | this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT) | ||
109 | } | ||
110 | |||
111 | stop () { | ||
112 | logger.info('Stopping RTMP server.', lTags()) | ||
113 | |||
114 | this.rtmpServer.close() | ||
115 | this.rtmpServer = undefined | ||
116 | |||
117 | // Sessions is an object | ||
118 | this.getContext().sessions.forEach((session: any) => { | ||
119 | if (session instanceof NodeRtmpSession) { | ||
120 | session.stop() | ||
121 | } | ||
122 | }) | ||
123 | } | ||
124 | |||
125 | isRunning () { | ||
126 | return !!this.rtmpServer | ||
127 | } | ||
128 | |||
129 | stopSessionOf (videoId: number) { | ||
130 | const sessionId = this.videoSessions.get(videoId) | ||
131 | if (!sessionId) return | ||
132 | |||
133 | this.videoSessions.delete(videoId) | ||
134 | this.abortSession(sessionId) | ||
135 | } | ||
136 | |||
137 | addViewTo (videoId: number) { | ||
138 | if (this.videoSessions.has(videoId) === false) return | ||
139 | |||
140 | let watchers = this.watchersPerVideo.get(videoId) | ||
141 | |||
142 | if (!watchers) { | ||
143 | watchers = [] | ||
144 | this.watchersPerVideo.set(videoId, watchers) | ||
145 | } | ||
146 | |||
147 | watchers.push(new Date().getTime()) | ||
148 | } | ||
149 | |||
150 | private getContext () { | ||
151 | return context | ||
152 | } | ||
153 | |||
154 | private abortSession (sessionId: string) { | ||
155 | const session = this.getContext().sessions.get(sessionId) | ||
156 | if (session) { | ||
157 | session.stop() | ||
158 | this.getContext().sessions.delete(sessionId) | ||
159 | } | ||
160 | |||
161 | const muxingSession = this.muxingSessions.get(sessionId) | ||
162 | if (muxingSession) muxingSession.abort() | ||
163 | } | ||
164 | |||
165 | private async handleSession (sessionId: string, streamPath: string, streamKey: string) { | ||
166 | const videoLive = await VideoLiveModel.loadByStreamKey(streamKey) | ||
167 | if (!videoLive) { | ||
168 | logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId)) | ||
169 | return this.abortSession(sessionId) | ||
170 | } | ||
171 | |||
172 | const video = videoLive.Video | ||
173 | if (video.isBlacklisted()) { | ||
174 | logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid)) | ||
175 | return this.abortSession(sessionId) | ||
176 | } | ||
177 | |||
178 | // Cleanup old potential live files (could happen with a permanent live) | ||
179 | LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid) | ||
180 | |||
181 | const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id) | ||
182 | if (oldStreamingPlaylist) { | ||
183 | await cleanupLive(video, oldStreamingPlaylist) | ||
184 | } | ||
185 | |||
186 | this.videoSessions.set(video.id, sessionId) | ||
187 | |||
188 | const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath | ||
189 | |||
190 | const [ { videoFileResolution }, fps ] = await Promise.all([ | ||
191 | getVideoFileResolution(rtmpUrl), | ||
192 | getVideoFileFPS(rtmpUrl) | ||
193 | ]) | ||
194 | |||
195 | const allResolutions = this.buildAllResolutionsToTranscode(videoFileResolution) | ||
196 | |||
197 | logger.info( | ||
198 | 'Will mux/transcode live video of original resolution %d.', videoFileResolution, | ||
199 | { allResolutions, ...lTags(sessionId, video.uuid) } | ||
200 | ) | ||
201 | |||
202 | const streamingPlaylist = await this.createLivePlaylist(video, allResolutions) | ||
203 | |||
204 | return this.runMuxingSession({ | ||
205 | sessionId, | ||
206 | videoLive, | ||
207 | streamingPlaylist, | ||
208 | rtmpUrl, | ||
209 | fps, | ||
210 | allResolutions | ||
211 | }) | ||
212 | } | ||
213 | |||
214 | private async runMuxingSession (options: { | ||
215 | sessionId: string | ||
216 | videoLive: MVideoLiveVideo | ||
217 | streamingPlaylist: MStreamingPlaylistVideo | ||
218 | rtmpUrl: string | ||
219 | fps: number | ||
220 | allResolutions: number[] | ||
221 | }) { | ||
222 | const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, rtmpUrl } = options | ||
223 | const videoUUID = videoLive.Video.uuid | ||
224 | const localLTags = lTags(sessionId, videoUUID) | ||
225 | |||
226 | const user = await UserModel.loadByLiveId(videoLive.id) | ||
227 | LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id) | ||
228 | |||
229 | const muxingSession = new MuxingSession({ | ||
230 | context: this.getContext(), | ||
231 | user, | ||
232 | sessionId, | ||
233 | videoLive, | ||
234 | streamingPlaylist, | ||
235 | rtmpUrl, | ||
236 | fps, | ||
237 | allResolutions | ||
238 | }) | ||
239 | |||
240 | muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags)) | ||
241 | |||
242 | muxingSession.on('bad-socket-health', ({ videoId }) => { | ||
243 | logger.error( | ||
244 | 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' + | ||
245 | ' Stopping session of video %s.', videoUUID, | ||
246 | localLTags | ||
247 | ) | ||
248 | |||
249 | this.stopSessionOf(videoId) | ||
250 | }) | ||
251 | |||
252 | muxingSession.on('duration-exceeded', ({ videoId }) => { | ||
253 | logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags) | ||
254 | |||
255 | this.stopSessionOf(videoId) | ||
256 | }) | ||
257 | |||
258 | muxingSession.on('quota-exceeded', ({ videoId }) => { | ||
259 | logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags) | ||
260 | |||
261 | this.stopSessionOf(videoId) | ||
262 | }) | ||
263 | |||
264 | muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId)) | ||
265 | muxingSession.on('ffmpeg-end', ({ videoId }) => { | ||
266 | this.onMuxingFFmpegEnd(videoId) | ||
267 | }) | ||
268 | |||
269 | muxingSession.on('after-cleanup', ({ videoId }) => { | ||
270 | this.muxingSessions.delete(sessionId) | ||
271 | |||
272 | return this.onAfterMuxingCleanup(videoId) | ||
273 | .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags })) | ||
274 | }) | ||
275 | |||
276 | this.muxingSessions.set(sessionId, muxingSession) | ||
277 | |||
278 | muxingSession.runMuxing() | ||
279 | .catch(err => { | ||
280 | logger.error('Cannot run muxing.', { err, ...localLTags }) | ||
281 | this.abortSession(sessionId) | ||
282 | }) | ||
283 | } | ||
284 | |||
285 | private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) { | ||
286 | const videoId = live.videoId | ||
287 | |||
288 | try { | ||
289 | const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) | ||
290 | |||
291 | logger.info('Will publish and federate live %s.', video.url, localLTags) | ||
292 | |||
293 | video.state = VideoState.PUBLISHED | ||
294 | await video.save() | ||
295 | |||
296 | live.Video = video | ||
297 | |||
298 | setTimeout(() => { | ||
299 | federateVideoIfNeeded(video, false) | ||
300 | .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })) | ||
301 | |||
302 | PeerTubeSocket.Instance.sendVideoLiveNewState(video) | ||
303 | }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION) | ||
304 | } catch (err) { | ||
305 | logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags }) | ||
306 | } | ||
307 | } | ||
308 | |||
309 | private onMuxingFFmpegEnd (videoId: number) { | ||
310 | this.watchersPerVideo.delete(videoId) | ||
311 | this.videoSessions.delete(videoId) | ||
312 | } | ||
313 | |||
314 | private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) { | ||
315 | try { | ||
316 | const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID) | ||
317 | if (!fullVideo) return | ||
318 | |||
319 | const live = await VideoLiveModel.loadByVideoId(fullVideo.id) | ||
320 | |||
321 | if (!live.permanentLive) { | ||
322 | JobQueue.Instance.createJob({ | ||
323 | type: 'video-live-ending', | ||
324 | payload: { | ||
325 | videoId: fullVideo.id | ||
326 | } | ||
327 | }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY }) | ||
328 | |||
329 | fullVideo.state = VideoState.LIVE_ENDED | ||
330 | } else { | ||
331 | fullVideo.state = VideoState.WAITING_FOR_LIVE | ||
332 | } | ||
333 | |||
334 | await fullVideo.save() | ||
335 | |||
336 | PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) | ||
337 | |||
338 | await federateVideoIfNeeded(fullVideo, false) | ||
339 | } catch (err) { | ||
340 | logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) }) | ||
341 | } | ||
342 | } | ||
343 | |||
344 | private async updateLiveViews () { | ||
345 | if (!this.isRunning()) return | ||
346 | |||
347 | if (!isTestInstance()) logger.info('Updating live video views.', lTags()) | ||
348 | |||
349 | for (const videoId of this.watchersPerVideo.keys()) { | ||
350 | const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE | ||
351 | |||
352 | const watchers = this.watchersPerVideo.get(videoId) | ||
353 | |||
354 | const numWatchers = watchers.length | ||
355 | |||
356 | const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) | ||
357 | video.views = numWatchers | ||
358 | await video.save() | ||
359 | |||
360 | await federateVideoIfNeeded(video, false) | ||
361 | |||
362 | PeerTubeSocket.Instance.sendVideoViewsUpdate(video) | ||
363 | |||
364 | // Only keep not expired watchers | ||
365 | const newWatchers = watchers.filter(w => w > notBefore) | ||
366 | this.watchersPerVideo.set(videoId, newWatchers) | ||
367 | |||
368 | logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags()) | ||
369 | } | ||
370 | } | ||
371 | |||
372 | private async handleBrokenLives () { | ||
373 | const videoUUIDs = await VideoModel.listPublishedLiveUUIDs() | ||
374 | |||
375 | for (const uuid of videoUUIDs) { | ||
376 | await this.onAfterMuxingCleanup(uuid, true) | ||
377 | } | ||
378 | } | ||
379 | |||
380 | private buildAllResolutionsToTranscode (originResolution: number) { | ||
381 | const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED | ||
382 | ? computeResolutionsToTranscode(originResolution, 'live') | ||
383 | : [] | ||
384 | |||
385 | return resolutionsEnabled.concat([ originResolution ]) | ||
386 | } | ||
387 | |||
388 | private async createLivePlaylist (video: MVideo, allResolutions: number[]) { | ||
389 | const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid) | ||
390 | const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({ | ||
391 | videoId: video.id, | ||
392 | playlistUrl, | ||
393 | segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive), | ||
394 | p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions), | ||
395 | p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, | ||
396 | |||
397 | type: VideoStreamingPlaylistType.HLS | ||
398 | }, { returning: true }) as [ MStreamingPlaylist, boolean ] | ||
399 | |||
400 | return Object.assign(videoStreamingPlaylist, { Video: video }) | ||
401 | } | ||
402 | |||
403 | static get Instance () { | ||
404 | return this.instance || (this.instance = new this()) | ||
405 | } | ||
406 | } | ||
407 | |||
408 | // --------------------------------------------------------------------------- | ||
409 | |||
410 | export { | ||
411 | LiveManager | ||
412 | } | ||