]>
Commit | Line | Data |
---|---|---|
1 | ||
2 | import { AsyncQueue, queue } from 'async' | |
3 | import * as chokidar from 'chokidar' | |
4 | import { FfmpegCommand } from 'fluent-ffmpeg' | |
5 | import { ensureDir, stat } from 'fs-extra' | |
6 | import { basename } from 'path' | |
7 | import { computeResolutionsToTranscode, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils' | |
8 | import { logger } from '@server/helpers/logger' | |
9 | import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config' | |
10 | import { MEMOIZE_TTL, P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants' | |
11 | import { UserModel } from '@server/models/account/user' | |
12 | import { VideoModel } from '@server/models/video/video' | |
13 | import { VideoFileModel } from '@server/models/video/video-file' | |
14 | import { VideoLiveModel } from '@server/models/video/video-live' | |
15 | import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' | |
16 | import { MStreamingPlaylist, MUserId, MVideoLive, MVideoLiveVideo } from '@server/types/models' | |
17 | import { VideoState, VideoStreamingPlaylistType } from '@shared/models' | |
18 | import { federateVideoIfNeeded } from './activitypub/videos' | |
19 | import { buildSha256Segment } from './hls' | |
20 | import { JobQueue } from './job-queue' | |
21 | import { PeerTubeSocket } from './peertube-socket' | |
22 | import { isAbleToUploadVideo } from './user' | |
23 | import { getHLSDirectory } from './video-paths' | |
24 | ||
25 | import memoizee = require('memoizee') | |
26 | const NodeRtmpServer = require('node-media-server/node_rtmp_server') | |
27 | const context = require('node-media-server/node_core_ctx') | |
28 | const nodeMediaServerLogger = require('node-media-server/node_core_logger') | |
29 | ||
30 | // Disable node media server logs | |
31 | nodeMediaServerLogger.setLogType(0) | |
32 | ||
33 | const config = { | |
34 | rtmp: { | |
35 | port: CONFIG.LIVE.RTMP.PORT, | |
36 | chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE, | |
37 | gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE, | |
38 | ping: VIDEO_LIVE.RTMP.PING, | |
39 | ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT | |
40 | }, | |
41 | transcoding: { | |
42 | ffmpeg: 'ffmpeg' | |
43 | } | |
44 | } | |
45 | ||
46 | type SegmentSha256QueueParam = { | |
47 | operation: 'update' | 'delete' | |
48 | videoUUID: string | |
49 | segmentPath: string | |
50 | } | |
51 | ||
52 | class LiveManager { | |
53 | ||
54 | private static instance: LiveManager | |
55 | ||
56 | private readonly transSessions = new Map<string, FfmpegCommand>() | |
57 | private readonly videoSessions = new Map<number, string>() | |
58 | private readonly segmentsSha256 = new Map<string, Map<string, string>>() | |
59 | private readonly livesPerUser = new Map<number, { liveId: number, videoId: number, size: number }[]>() | |
60 | ||
61 | private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => { | |
62 | return isAbleToUploadVideo(userId, 1000) | |
63 | }, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD }) | |
64 | ||
65 | private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam> | |
66 | private rtmpServer: any | |
67 | ||
68 | private constructor () { | |
69 | } | |
70 | ||
71 | init () { | |
72 | const events = this.getContext().nodeEvent | |
73 | events.on('postPublish', (sessionId: string, streamPath: string) => { | |
74 | logger.debug('RTMP received stream', { id: sessionId, streamPath }) | |
75 | ||
76 | const splittedPath = streamPath.split('/') | |
77 | if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) { | |
78 | logger.warn('Live path is incorrect.', { streamPath }) | |
79 | return this.abortSession(sessionId) | |
80 | } | |
81 | ||
82 | this.handleSession(sessionId, streamPath, splittedPath[2]) | |
83 | .catch(err => logger.error('Cannot handle sessions.', { err })) | |
84 | }) | |
85 | ||
86 | events.on('donePublish', sessionId => { | |
87 | logger.info('Live session ended.', { sessionId }) | |
88 | }) | |
89 | ||
90 | this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => { | |
91 | const promise = options.operation === 'update' | |
92 | ? this.addSegmentSha(options) | |
93 | : Promise.resolve(this.removeSegmentSha(options)) | |
94 | ||
95 | promise.then(() => cb()) | |
96 | .catch(err => { | |
97 | logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err }) | |
98 | cb() | |
99 | }) | |
100 | }) | |
101 | ||
102 | registerConfigChangedHandler(() => { | |
103 | if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) { | |
104 | this.run() | |
105 | return | |
106 | } | |
107 | ||
108 | if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) { | |
109 | this.stop() | |
110 | } | |
111 | }) | |
112 | } | |
113 | ||
114 | run () { | |
115 | logger.info('Running RTMP server.') | |
116 | ||
117 | this.rtmpServer = new NodeRtmpServer(config) | |
118 | this.rtmpServer.run() | |
119 | } | |
120 | ||
121 | stop () { | |
122 | logger.info('Stopping RTMP server.') | |
123 | ||
124 | this.rtmpServer.stop() | |
125 | this.rtmpServer = undefined | |
126 | } | |
127 | ||
128 | getSegmentsSha256 (videoUUID: string) { | |
129 | return this.segmentsSha256.get(videoUUID) | |
130 | } | |
131 | ||
132 | stopSessionOf (videoId: number) { | |
133 | const sessionId = this.videoSessions.get(videoId) | |
134 | if (!sessionId) return | |
135 | ||
136 | this.abortSession(sessionId) | |
137 | ||
138 | this.onEndTransmuxing(videoId, true) | |
139 | .catch(err => logger.error('Cannot end transmuxing of video %d.', videoId, { err })) | |
140 | } | |
141 | ||
142 | private getContext () { | |
143 | return context | |
144 | } | |
145 | ||
146 | private abortSession (id: string) { | |
147 | const session = this.getContext().sessions.get(id) | |
148 | if (session) { | |
149 | session.stop() | |
150 | this.getContext().sessions.delete(id) | |
151 | } | |
152 | ||
153 | const transSession = this.transSessions.get(id) | |
154 | if (transSession) { | |
155 | transSession.kill('SIGINT') | |
156 | this.transSessions.delete(id) | |
157 | } | |
158 | } | |
159 | ||
160 | private async handleSession (sessionId: string, streamPath: string, streamKey: string) { | |
161 | const videoLive = await VideoLiveModel.loadByStreamKey(streamKey) | |
162 | if (!videoLive) { | |
163 | logger.warn('Unknown live video with stream key %s.', streamKey) | |
164 | return this.abortSession(sessionId) | |
165 | } | |
166 | ||
167 | const video = videoLive.Video | |
168 | if (video.isBlacklisted()) { | |
169 | logger.warn('Video is blacklisted. Refusing stream %s.', streamKey) | |
170 | return this.abortSession(sessionId) | |
171 | } | |
172 | ||
173 | this.videoSessions.set(video.id, sessionId) | |
174 | ||
175 | const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid) | |
176 | ||
177 | const session = this.getContext().sessions.get(sessionId) | |
178 | const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED | |
179 | ? computeResolutionsToTranscode(session.videoHeight, 'live') | |
180 | : [] | |
181 | ||
182 | logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled }) | |
183 | ||
184 | const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({ | |
185 | videoId: video.id, | |
186 | playlistUrl, | |
187 | segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive), | |
188 | p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled), | |
189 | p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, | |
190 | ||
191 | type: VideoStreamingPlaylistType.HLS | |
192 | }, { returning: true }) as [ MStreamingPlaylist, boolean ] | |
193 | ||
194 | return this.runMuxing({ | |
195 | sessionId, | |
196 | videoLive, | |
197 | playlist: videoStreamingPlaylist, | |
198 | streamPath, | |
199 | originalResolution: session.videoHeight, | |
200 | resolutionsEnabled | |
201 | }) | |
202 | } | |
203 | ||
204 | private async runMuxing (options: { | |
205 | sessionId: string | |
206 | videoLive: MVideoLiveVideo | |
207 | playlist: MStreamingPlaylist | |
208 | streamPath: string | |
209 | resolutionsEnabled: number[] | |
210 | originalResolution: number | |
211 | }) { | |
212 | const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options | |
213 | const startStreamDateTime = new Date().getTime() | |
214 | const allResolutions = resolutionsEnabled.concat([ originalResolution ]) | |
215 | ||
216 | const user = await UserModel.loadByLiveId(videoLive.id) | |
217 | if (!this.livesPerUser.has(user.id)) { | |
218 | this.livesPerUser.set(user.id, []) | |
219 | } | |
220 | ||
221 | const currentUserLive = { liveId: videoLive.id, videoId: videoLive.videoId, size: 0 } | |
222 | const livesOfUser = this.livesPerUser.get(user.id) | |
223 | livesOfUser.push(currentUserLive) | |
224 | ||
225 | for (let i = 0; i < allResolutions.length; i++) { | |
226 | const resolution = allResolutions[i] | |
227 | ||
228 | VideoFileModel.upsert({ | |
229 | resolution, | |
230 | size: -1, | |
231 | extname: '.ts', | |
232 | infoHash: null, | |
233 | fps: -1, | |
234 | videoStreamingPlaylistId: playlist.id | |
235 | }).catch(err => { | |
236 | logger.error('Cannot create file for live streaming.', { err }) | |
237 | }) | |
238 | } | |
239 | ||
240 | const outPath = getHLSDirectory(videoLive.Video) | |
241 | await ensureDir(outPath) | |
242 | ||
243 | const deleteSegments = videoLive.saveReplay === false | |
244 | ||
245 | const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath | |
246 | const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED | |
247 | ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, deleteSegments) | |
248 | : runLiveMuxing(rtmpUrl, outPath, deleteSegments) | |
249 | ||
250 | logger.info('Running live muxing/transcoding.') | |
251 | this.transSessions.set(sessionId, ffmpegExec) | |
252 | ||
253 | const videoUUID = videoLive.Video.uuid | |
254 | const tsWatcher = chokidar.watch(outPath + '/*.ts') | |
255 | ||
256 | const updateSegment = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID }) | |
257 | ||
258 | const addHandler = segmentPath => { | |
259 | updateSegment(segmentPath) | |
260 | ||
261 | if (this.isDurationConstraintValid(startStreamDateTime) !== true) { | |
262 | this.stopSessionOf(videoLive.videoId) | |
263 | } | |
264 | ||
265 | if (videoLive.saveReplay === true) { | |
266 | stat(segmentPath) | |
267 | .then(segmentStat => { | |
268 | currentUserLive.size += segmentStat.size | |
269 | }) | |
270 | .then(() => this.isQuotaConstraintValid(user, videoLive)) | |
271 | .then(quotaValid => { | |
272 | if (quotaValid !== true) { | |
273 | this.stopSessionOf(videoLive.videoId) | |
274 | } | |
275 | }) | |
276 | .catch(err => logger.error('Cannot stat %s or check quota of %d.', segmentPath, user.id, { err })) | |
277 | } | |
278 | } | |
279 | ||
280 | const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID }) | |
281 | ||
282 | tsWatcher.on('add', p => addHandler(p)) | |
283 | tsWatcher.on('change', p => updateSegment(p)) | |
284 | tsWatcher.on('unlink', p => deleteHandler(p)) | |
285 | ||
286 | const masterWatcher = chokidar.watch(outPath + '/master.m3u8') | |
287 | masterWatcher.on('add', async () => { | |
288 | try { | |
289 | const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId) | |
290 | ||
291 | video.state = VideoState.PUBLISHED | |
292 | await video.save() | |
293 | videoLive.Video = video | |
294 | ||
295 | await federateVideoIfNeeded(video, false) | |
296 | ||
297 | PeerTubeSocket.Instance.sendVideoLiveNewState(video) | |
298 | } catch (err) { | |
299 | logger.error('Cannot federate video %d.', videoLive.videoId, { err }) | |
300 | } finally { | |
301 | masterWatcher.close() | |
302 | .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err })) | |
303 | } | |
304 | }) | |
305 | ||
306 | const onFFmpegEnded = () => { | |
307 | logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', streamPath) | |
308 | ||
309 | this.transSessions.delete(sessionId) | |
310 | ||
311 | Promise.all([ tsWatcher.close(), masterWatcher.close() ]) | |
312 | .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err })) | |
313 | ||
314 | this.onEndTransmuxing(videoLive.Video.id) | |
315 | .catch(err => logger.error('Error in closed transmuxing.', { err })) | |
316 | } | |
317 | ||
318 | ffmpegExec.on('error', (err, stdout, stderr) => { | |
319 | onFFmpegEnded() | |
320 | ||
321 | // Don't care that we killed the ffmpeg process | |
322 | if (err?.message?.includes('SIGINT')) return | |
323 | ||
324 | logger.error('Live transcoding error.', { err, stdout, stderr }) | |
325 | }) | |
326 | ||
327 | ffmpegExec.on('end', () => onFFmpegEnded()) | |
328 | } | |
329 | ||
330 | getLiveQuotaUsedByUser (userId: number) { | |
331 | const currentLives = this.livesPerUser.get(userId) | |
332 | if (!currentLives) return 0 | |
333 | ||
334 | return currentLives.reduce((sum, obj) => sum + obj.size, 0) | |
335 | } | |
336 | ||
337 | private async onEndTransmuxing (videoId: number, cleanupNow = false) { | |
338 | try { | |
339 | const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) | |
340 | if (!fullVideo) return | |
341 | ||
342 | JobQueue.Instance.createJob({ | |
343 | type: 'video-live-ending', | |
344 | payload: { | |
345 | videoId: fullVideo.id | |
346 | } | |
347 | }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY }) | |
348 | ||
349 | // FIXME: use end | |
350 | fullVideo.state = VideoState.WAITING_FOR_LIVE | |
351 | await fullVideo.save() | |
352 | ||
353 | PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) | |
354 | ||
355 | await federateVideoIfNeeded(fullVideo, false) | |
356 | } catch (err) { | |
357 | logger.error('Cannot save/federate new video state of live streaming.', { err }) | |
358 | } | |
359 | } | |
360 | ||
361 | private async addSegmentSha (options: SegmentSha256QueueParam) { | |
362 | const segmentName = basename(options.segmentPath) | |
363 | logger.debug('Updating live sha segment %s.', options.segmentPath) | |
364 | ||
365 | const shaResult = await buildSha256Segment(options.segmentPath) | |
366 | ||
367 | if (!this.segmentsSha256.has(options.videoUUID)) { | |
368 | this.segmentsSha256.set(options.videoUUID, new Map()) | |
369 | } | |
370 | ||
371 | const filesMap = this.segmentsSha256.get(options.videoUUID) | |
372 | filesMap.set(segmentName, shaResult) | |
373 | } | |
374 | ||
375 | private removeSegmentSha (options: SegmentSha256QueueParam) { | |
376 | const segmentName = basename(options.segmentPath) | |
377 | ||
378 | logger.debug('Removing live sha segment %s.', options.segmentPath) | |
379 | ||
380 | const filesMap = this.segmentsSha256.get(options.videoUUID) | |
381 | if (!filesMap) { | |
382 | logger.warn('Unknown files map to remove sha for %s.', options.videoUUID) | |
383 | return | |
384 | } | |
385 | ||
386 | if (!filesMap.has(segmentName)) { | |
387 | logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath) | |
388 | return | |
389 | } | |
390 | ||
391 | filesMap.delete(segmentName) | |
392 | } | |
393 | ||
394 | private isDurationConstraintValid (streamingStartTime: number) { | |
395 | const maxDuration = CONFIG.LIVE.MAX_DURATION | |
396 | // No limit | |
397 | if (maxDuration === null) return true | |
398 | ||
399 | const now = new Date().getTime() | |
400 | const max = streamingStartTime + maxDuration | |
401 | ||
402 | return now <= max | |
403 | } | |
404 | ||
405 | private async isQuotaConstraintValid (user: MUserId, live: MVideoLive) { | |
406 | if (live.saveReplay !== true) return true | |
407 | ||
408 | return this.isAbleToUploadVideoWithCache(user.id) | |
409 | } | |
410 | ||
411 | static get Instance () { | |
412 | return this.instance || (this.instance = new this()) | |
413 | } | |
414 | } | |
415 | ||
416 | // --------------------------------------------------------------------------- | |
417 | ||
418 | export { | |
419 | LiveManager | |
420 | } |