diff options
Diffstat (limited to 'server/lib/live-manager.ts')
-rw-r--r-- | server/lib/live-manager.ts | 310 |
1 files changed, 310 insertions, 0 deletions
diff --git a/server/lib/live-manager.ts b/server/lib/live-manager.ts new file mode 100644 index 000000000..f602bfb6d --- /dev/null +++ b/server/lib/live-manager.ts | |||
@@ -0,0 +1,310 @@ | |||
1 | |||
2 | import { AsyncQueue, queue } from 'async' | ||
3 | import * as chokidar from 'chokidar' | ||
4 | import { FfmpegCommand } from 'fluent-ffmpeg' | ||
5 | import { ensureDir, readdir, remove } from 'fs-extra' | ||
6 | import { basename, join } 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 { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants' | ||
11 | import { VideoFileModel } from '@server/models/video/video-file' | ||
12 | import { VideoLiveModel } from '@server/models/video/video-live' | ||
13 | import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' | ||
14 | import { MStreamingPlaylist, MVideo, MVideoLiveVideo } from '@server/types/models' | ||
15 | import { VideoState, VideoStreamingPlaylistType } from '@shared/models' | ||
16 | import { buildSha256Segment } from './hls' | ||
17 | import { getHLSDirectory } from './video-paths' | ||
18 | |||
19 | const NodeRtmpServer = require('node-media-server/node_rtmp_server') | ||
20 | const context = require('node-media-server/node_core_ctx') | ||
21 | const nodeMediaServerLogger = require('node-media-server/node_core_logger') | ||
22 | |||
23 | // Disable node media server logs | ||
24 | nodeMediaServerLogger.setLogType(0) | ||
25 | |||
26 | const config = { | ||
27 | rtmp: { | ||
28 | port: CONFIG.LIVE.RTMP.PORT, | ||
29 | chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE, | ||
30 | gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE, | ||
31 | ping: VIDEO_LIVE.RTMP.PING, | ||
32 | ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT | ||
33 | }, | ||
34 | transcoding: { | ||
35 | ffmpeg: 'ffmpeg' | ||
36 | } | ||
37 | } | ||
38 | |||
39 | type SegmentSha256QueueParam = { | ||
40 | operation: 'update' | 'delete' | ||
41 | videoUUID: string | ||
42 | segmentPath: string | ||
43 | } | ||
44 | |||
45 | class LiveManager { | ||
46 | |||
47 | private static instance: LiveManager | ||
48 | |||
49 | private readonly transSessions = new Map<string, FfmpegCommand>() | ||
50 | private readonly segmentsSha256 = new Map<string, Map<string, string>>() | ||
51 | |||
52 | private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam> | ||
53 | private rtmpServer: any | ||
54 | |||
55 | private constructor () { | ||
56 | } | ||
57 | |||
58 | init () { | ||
59 | this.getContext().nodeEvent.on('postPublish', (sessionId: string, streamPath: string) => { | ||
60 | logger.debug('RTMP received stream', { id: sessionId, streamPath }) | ||
61 | |||
62 | const splittedPath = streamPath.split('/') | ||
63 | if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) { | ||
64 | logger.warn('Live path is incorrect.', { streamPath }) | ||
65 | return this.abortSession(sessionId) | ||
66 | } | ||
67 | |||
68 | this.handleSession(sessionId, streamPath, splittedPath[2]) | ||
69 | .catch(err => logger.error('Cannot handle sessions.', { err })) | ||
70 | }) | ||
71 | |||
72 | this.getContext().nodeEvent.on('donePublish', sessionId => { | ||
73 | this.abortSession(sessionId) | ||
74 | }) | ||
75 | |||
76 | this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => { | ||
77 | const promise = options.operation === 'update' | ||
78 | ? this.addSegmentSha(options) | ||
79 | : Promise.resolve(this.removeSegmentSha(options)) | ||
80 | |||
81 | promise.then(() => cb()) | ||
82 | .catch(err => { | ||
83 | logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err }) | ||
84 | cb() | ||
85 | }) | ||
86 | }) | ||
87 | |||
88 | registerConfigChangedHandler(() => { | ||
89 | if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) { | ||
90 | this.run() | ||
91 | return | ||
92 | } | ||
93 | |||
94 | if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) { | ||
95 | this.stop() | ||
96 | } | ||
97 | }) | ||
98 | } | ||
99 | |||
100 | run () { | ||
101 | logger.info('Running RTMP server.') | ||
102 | |||
103 | this.rtmpServer = new NodeRtmpServer(config) | ||
104 | this.rtmpServer.run() | ||
105 | } | ||
106 | |||
107 | stop () { | ||
108 | logger.info('Stopping RTMP server.') | ||
109 | |||
110 | this.rtmpServer.stop() | ||
111 | this.rtmpServer = undefined | ||
112 | } | ||
113 | |||
114 | getSegmentsSha256 (videoUUID: string) { | ||
115 | return this.segmentsSha256.get(videoUUID) | ||
116 | } | ||
117 | |||
118 | private getContext () { | ||
119 | return context | ||
120 | } | ||
121 | |||
122 | private abortSession (id: string) { | ||
123 | const session = this.getContext().sessions.get(id) | ||
124 | if (session) session.stop() | ||
125 | |||
126 | const transSession = this.transSessions.get(id) | ||
127 | if (transSession) transSession.kill('SIGKILL') | ||
128 | } | ||
129 | |||
130 | private async handleSession (sessionId: string, streamPath: string, streamKey: string) { | ||
131 | const videoLive = await VideoLiveModel.loadByStreamKey(streamKey) | ||
132 | if (!videoLive) { | ||
133 | logger.warn('Unknown live video with stream key %s.', streamKey) | ||
134 | return this.abortSession(sessionId) | ||
135 | } | ||
136 | |||
137 | const video = videoLive.Video | ||
138 | const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid) | ||
139 | |||
140 | const session = this.getContext().sessions.get(sessionId) | ||
141 | const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED | ||
142 | ? computeResolutionsToTranscode(session.videoHeight, 'live') | ||
143 | : [] | ||
144 | |||
145 | logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled }) | ||
146 | |||
147 | const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({ | ||
148 | videoId: video.id, | ||
149 | playlistUrl, | ||
150 | segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive), | ||
151 | p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled), | ||
152 | p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, | ||
153 | |||
154 | type: VideoStreamingPlaylistType.HLS | ||
155 | }, { returning: true }) as [ MStreamingPlaylist, boolean ] | ||
156 | |||
157 | video.state = VideoState.PUBLISHED | ||
158 | await video.save() | ||
159 | |||
160 | // FIXME: federation? | ||
161 | |||
162 | return this.runMuxing({ | ||
163 | sessionId, | ||
164 | videoLive, | ||
165 | playlist: videoStreamingPlaylist, | ||
166 | streamPath, | ||
167 | originalResolution: session.videoHeight, | ||
168 | resolutionsEnabled | ||
169 | }) | ||
170 | } | ||
171 | |||
172 | private async runMuxing (options: { | ||
173 | sessionId: string | ||
174 | videoLive: MVideoLiveVideo | ||
175 | playlist: MStreamingPlaylist | ||
176 | streamPath: string | ||
177 | resolutionsEnabled: number[] | ||
178 | originalResolution: number | ||
179 | }) { | ||
180 | const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options | ||
181 | const allResolutions = resolutionsEnabled.concat([ originalResolution ]) | ||
182 | |||
183 | for (let i = 0; i < allResolutions.length; i++) { | ||
184 | const resolution = allResolutions[i] | ||
185 | |||
186 | VideoFileModel.upsert({ | ||
187 | resolution, | ||
188 | size: -1, | ||
189 | extname: '.ts', | ||
190 | infoHash: null, | ||
191 | fps: -1, | ||
192 | videoStreamingPlaylistId: playlist.id | ||
193 | }).catch(err => { | ||
194 | logger.error('Cannot create file for live streaming.', { err }) | ||
195 | }) | ||
196 | } | ||
197 | |||
198 | const outPath = getHLSDirectory(videoLive.Video) | ||
199 | await ensureDir(outPath) | ||
200 | |||
201 | const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath | ||
202 | const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED | ||
203 | ? runLiveTranscoding(rtmpUrl, outPath, allResolutions) | ||
204 | : runLiveMuxing(rtmpUrl, outPath) | ||
205 | |||
206 | logger.info('Running live muxing/transcoding.') | ||
207 | |||
208 | this.transSessions.set(sessionId, ffmpegExec) | ||
209 | |||
210 | const onFFmpegEnded = () => { | ||
211 | watcher.close() | ||
212 | .catch(err => logger.error('Cannot close watcher of %s.', outPath, { err })) | ||
213 | |||
214 | this.onEndTransmuxing(videoLive.Video, playlist, streamPath, outPath) | ||
215 | .catch(err => logger.error('Error in closed transmuxing.', { err })) | ||
216 | } | ||
217 | |||
218 | ffmpegExec.on('error', (err, stdout, stderr) => { | ||
219 | onFFmpegEnded() | ||
220 | |||
221 | // Don't care that we killed the ffmpeg process | ||
222 | if (err?.message?.includes('SIGKILL')) return | ||
223 | |||
224 | logger.error('Live transcoding error.', { err, stdout, stderr }) | ||
225 | }) | ||
226 | |||
227 | ffmpegExec.on('end', () => onFFmpegEnded()) | ||
228 | |||
229 | const videoUUID = videoLive.Video.uuid | ||
230 | const watcher = chokidar.watch(outPath + '/*.ts') | ||
231 | |||
232 | const updateHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID }) | ||
233 | const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID }) | ||
234 | |||
235 | watcher.on('add', p => updateHandler(p)) | ||
236 | watcher.on('change', p => updateHandler(p)) | ||
237 | watcher.on('unlink', p => deleteHandler(p)) | ||
238 | } | ||
239 | |||
240 | private async onEndTransmuxing (video: MVideo, playlist: MStreamingPlaylist, streamPath: string, outPath: string) { | ||
241 | logger.info('RTMP transmuxing for %s ended.', streamPath) | ||
242 | |||
243 | const files = await readdir(outPath) | ||
244 | |||
245 | for (const filename of files) { | ||
246 | if ( | ||
247 | filename.endsWith('.ts') || | ||
248 | filename.endsWith('.m3u8') || | ||
249 | filename.endsWith('.mpd') || | ||
250 | filename.endsWith('.m4s') || | ||
251 | filename.endsWith('.tmp') | ||
252 | ) { | ||
253 | const p = join(outPath, filename) | ||
254 | |||
255 | remove(p) | ||
256 | .catch(err => logger.error('Cannot remove %s.', p, { err })) | ||
257 | } | ||
258 | } | ||
259 | |||
260 | playlist.destroy() | ||
261 | .catch(err => logger.error('Cannot remove live streaming playlist.', { err })) | ||
262 | |||
263 | video.state = VideoState.LIVE_ENDED | ||
264 | video.save() | ||
265 | .catch(err => logger.error('Cannot save new video state of live streaming.', { err })) | ||
266 | } | ||
267 | |||
268 | private async addSegmentSha (options: SegmentSha256QueueParam) { | ||
269 | const segmentName = basename(options.segmentPath) | ||
270 | logger.debug('Updating live sha segment %s.', options.segmentPath) | ||
271 | |||
272 | const shaResult = await buildSha256Segment(options.segmentPath) | ||
273 | |||
274 | if (!this.segmentsSha256.has(options.videoUUID)) { | ||
275 | this.segmentsSha256.set(options.videoUUID, new Map()) | ||
276 | } | ||
277 | |||
278 | const filesMap = this.segmentsSha256.get(options.videoUUID) | ||
279 | filesMap.set(segmentName, shaResult) | ||
280 | } | ||
281 | |||
282 | private removeSegmentSha (options: SegmentSha256QueueParam) { | ||
283 | const segmentName = basename(options.segmentPath) | ||
284 | |||
285 | logger.debug('Removing live sha segment %s.', options.segmentPath) | ||
286 | |||
287 | const filesMap = this.segmentsSha256.get(options.videoUUID) | ||
288 | if (!filesMap) { | ||
289 | logger.warn('Unknown files map to remove sha for %s.', options.videoUUID) | ||
290 | return | ||
291 | } | ||
292 | |||
293 | if (!filesMap.has(segmentName)) { | ||
294 | logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath) | ||
295 | return | ||
296 | } | ||
297 | |||
298 | filesMap.delete(segmentName) | ||
299 | } | ||
300 | |||
301 | static get Instance () { | ||
302 | return this.instance || (this.instance = new this()) | ||
303 | } | ||
304 | } | ||
305 | |||
306 | // --------------------------------------------------------------------------- | ||
307 | |||
308 | export { | ||
309 | LiveManager | ||
310 | } | ||