BlueGit

timfa filemanager

Files

filemanager / server / video-stream.js

video-stream.js

video-stream.js 11.6 KiB Download Raw
1'use strict';
2
3const { spawn } = require('child_process');
4const crypto = require('crypto');
5const fs = require('fs');
6const os = require('os');
7const path = require('path');
8
9const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');
10const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;
11const STREAM_READY_TIMEOUT_MS = 20 * 1000;
12const sessions = new Map();
13
14function hasAnyFiles (dirPath)
15{
16 try
17 {
18 const entries = fs.readdirSync(dirPath, { withFileTypes: true });
19 for (const entry of entries)
20 {
21 const fullPath = path.join(dirPath, entry.name);
22 if (entry.isFile()) return true;
23 if (entry.isDirectory() && hasAnyFiles(fullPath)) return true;
24 }
25 return false;
26 } catch
27 {
28 return false;
29 }
30}
31
32function makeHttpError (status, message)
33{
34 const err = new Error(message);
35 err.status = status;
36 return err;
37}
38
39function ensureStreamRootDir ()
40{
41 fs.mkdirSync(STREAM_ROOT_DIR, { recursive: true });
42}
43
44function ffmpegPath ()
45{
46 return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
47}
48
49function ffprobePath ()
50{
51 return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe';
52}
53
54function pruneExpiredSessions ()
55{
56 const now = Date.now();
57 for (const [sessionId, session] of sessions)
58 {
59 if (session.expiresAt > now) continue;
60 try
61 {
62 if (session.process) session.process.kill('SIGTERM');
63 } catch
64 {
65 // Ignore process cleanup failures.
66 }
67 sessions.delete(sessionId);
68 fs.rmSync(session.outputDir, { recursive: true, force: true });
69 }
70}
71
72function refreshSession (session)
73{
74 session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;
75}
76
77function runCommand (command, args)
78{
79 return new Promise((resolve, reject) =>
80 {
81 const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
82 let stdout = '';
83 let stderr = '';
84
85 child.stdout.on('data', (chunk) =>
86 {
87 stdout += chunk.toString();
88 });
89
90 child.stderr.on('data', (chunk) =>
91 {
92 stderr += chunk.toString();
93 });
94
95 child.on('error', (err) =>
96 {
97 if (err && err.code === 'ENOENT')
98 {
99 reject(makeHttpError(503, `${command} is not installed or not available in PATH.`));
100 return;
101 }
102 reject(err);
103 });
104
105 child.on('close', (code) =>
106 {
107 if (code === 0)
108 {
109 resolve({ stdout, stderr });
110 return;
111 }
112 reject(makeHttpError(500, stderr.trim() || `${command} exited with code ${code}.`));
113 });
114 });
115}
116
117async function probeInput (sourcePath)
118{
119 const { stdout } = await runCommand(ffprobePath(), [
120 '-v', 'error',
121 '-print_format', 'json',
122 '-show_streams',
123 '-show_format',
124 sourcePath,
125 ]);
126
127 let payload;
128 try
129 {
130 payload = JSON.parse(stdout || '{}');
131 } catch
132 {
133 throw makeHttpError(500, 'ffprobe returned invalid stream metadata.');
134 }
135
136 const typedIndexes = { video: 0, audio: 0, subtitle: 0 };
137 const streams = Array.isArray(payload.streams) ? payload.streams.map((stream) =>
138 {
139 const codecType = String(stream.codec_type || '').toLowerCase();
140 const relativeIndex = Object.prototype.hasOwnProperty.call(typedIndexes, codecType)
141 ? typedIndexes[codecType]++
142 : null;
143 return {
144 ...stream,
145 codecType,
146 relativeIndex,
147 tags: stream.tags || {},
148 disposition: stream.disposition || {},
149 };
150 }) : [];
151
152 return {
153 raw: payload,
154 video: streams.filter((stream) => stream.codecType === 'video'),
155 audio: streams.filter((stream) => stream.codecType === 'audio'),
156 subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),
157 };
158}
159
160function sanitiseTrackValue (value, fallback)
161{
162 const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
163 return cleaned || fallback;
164}
165
166function trackLanguage (stream)
167{
168 return sanitiseTrackValue(stream.tags.language || stream.tags.LANGUAGE || 'und', 'und').slice(0, 8);
169}
170
171function trackLabel (stream, fallback)
172{
173 const title = String(stream.tags.title || stream.tags.handler_name || '').trim();
174 if (title) return title;
175 const language = trackLanguage(stream);
176 if (language && language !== 'und') return `${fallback} (${language})`;
177 return fallback;
178}
179
180async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams)
181{
182 const extractedTracks = [];
183 let skippedCount = 0;
184 let trackNumber = 0;
185
186 for (const stream of subtitleStreams)
187 {
188 const fileName = `subtitle-${trackNumber}.vtt`;
189 const targetPath = path.join(outputDir, fileName);
190
191 try
192 {
193 await runCommand(ffmpegPath(), [
194 '-hide_banner',
195 '-loglevel', 'error',
196 '-nostdin',
197 '-y',
198 '-i', sourcePath,
199 '-map', `0:s:${stream.relativeIndex}`,
200 '-c:s', 'webvtt',
201 targetPath,
202 ]);
203 } catch
204 {
205 skippedCount += 1;
206 continue;
207 }
208
209 extractedTracks.push({
210 fileName,
211 label: trackLabel(stream, `Subtitle ${trackNumber + 1}`),
212 language: trackLanguage(stream),
213 isDefault: !!stream.disposition.default,
214 });
215 trackNumber += 1;
216 }
217
218 return {
219 tracks: extractedTracks,
220 skippedCount,
221 };
222}
223
224function buildHlsArgs (sourcePath, outputDir, streamInfo)
225{
226 const args = [
227 '-hide_banner',
228 '-loglevel', 'error',
229 '-nostdin',
230 '-y',
231 '-i', sourcePath,
232 '-map', '0:v:0',
233 ];
234
235 for (const audioStream of streamInfo.audio)
236 {
237 args.push('-map', `0:a:${audioStream.relativeIndex}`);
238 }
239
240 args.push(
241 '-c:v', 'libx264',
242 '-preset', 'veryfast',
243 '-crf', '23',
244 '-pix_fmt', 'yuv420p',
245 '-g', '48',
246 '-sc_threshold', '0',
247 );
248
249 if (streamInfo.audio.length)
250 {
251 args.push('-c:a', 'aac', '-b:a', '160k', '-ac', '2');
252 } else
253 {
254 args.push('-an');
255 }
256
257 const variantMap = [];
258 if (streamInfo.audio.length)
259 {
260 variantMap.push('v:0,agroup:audio,name:video');
261 streamInfo.audio.forEach((audioStream, index) =>
262 {
263 let entry = `a:${index},agroup:audio,name:${sanitiseTrackValue(trackLabel(audioStream, `Audio ${index + 1}`), `audio-${index + 1}`)},language:${trackLanguage(audioStream)}`;
264 if (audioStream.disposition.default) entry += ',default:yes';
265 variantMap.push(entry);
266 });
267 } else
268 {
269 variantMap.push('v:0,name:video');
270 }
271
272 args.push(
273 '-f', 'hls',
274 '-hls_time', '4',
275 '-hls_list_size', '0',
276 '-hls_flags', 'independent_segments+temp_file',
277 '-master_pl_name', 'master.m3u8',
278 '-hls_segment_filename', path.join(outputDir, 'stream_%v_segment_%06d.ts'),
279 '-var_stream_map', variantMap.join(' '),
280 path.join(outputDir, 'stream_%v.m3u8'),
281 );
282
283 return args;
284}
285
286function startHlsTranscode (session, streamInfo)
287{
288 const args = buildHlsArgs(session.sourcePath, session.outputDir, streamInfo);
289 const child = spawn(ffmpegPath(), args, { stdio: ['ignore', 'ignore', 'pipe'] });
290 let stderr = '';
291
292 child.stderr.on('data', (chunk) =>
293 {
294 stderr += chunk.toString();
295 if (stderr.length > 16000) stderr = stderr.slice(-16000);
296 });
297
298 child.on('error', (err) =>
299 {
300 if (err && err.code === 'ENOENT')
301 {
302 session.error = makeHttpError(503, 'ffmpeg is not installed or not available in PATH.');
303 return;
304 }
305 session.error = err;
306 });
307
308 child.on('close', (code) =>
309 {
310 session.process = null;
311 if (code === 0 || session.error) return;
312 session.error = makeHttpError(500, stderr.trim() || `ffmpeg exited with code ${code}.`);
313 });
314
315 session.process = child;
316}
317
318function waitForFile (targetPath, session, timeoutMs = STREAM_READY_TIMEOUT_MS)
319{
320 const startedAt = Date.now();
321
322 return new Promise((resolve, reject) =>
323 {
324 const check = () =>
325 {
326 if (fs.existsSync(targetPath))
327 {
328 resolve();
329 return;
330 }
331
332 if (session.error)
333 {
334 reject(session.error);
335 return;
336 }
337
338 if (Date.now() - startedAt >= timeoutMs)
339 {
340 reject(makeHttpError(504, 'Timed out while preparing the video stream.'));
341 return;
342 }
343
344 setTimeout(check, 120);
345 };
346
347 check();
348 });
349}
350
351function waitForStreamStart (session, timeoutMs = STREAM_READY_TIMEOUT_MS)
352{
353 const startedAt = Date.now();
354
355 return new Promise((resolve, reject) =>
356 {
357 const check = () =>
358 {
359 if (fs.existsSync(path.join(session.outputDir, 'master.m3u8')) || hasAnyFiles(session.outputDir))
360 {
361 resolve();
362 return;
363 }
364
365 if (session.error)
366 {
367 reject(session.error);
368 return;
369 }
370
371 if (!session.process)
372 {
373 reject(makeHttpError(500, 'Video stream preparation stopped unexpectedly.'));
374 return;
375 }
376
377 if (Date.now() - startedAt >= timeoutMs)
378 {
379 reject(makeHttpError(504, 'Timed out while preparing the video stream.'));
380 return;
381 }
382
383 setTimeout(check, 120);
384 };
385
386 check();
387 });
388}
389
390async function initialiseSession (session)
391{
392 const streamInfo = await probeInput(session.sourcePath);
393 if (!streamInfo.video.length)
394 {
395 throw makeHttpError(400, 'File does not contain a video stream.');
396 }
397
398 const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles);
399 session.subtitleTracks = subtitleResult.tracks;
400 session.subtitleSummary = {
401 total: streamInfo.subtitles.length,
402 converted: subtitleResult.tracks.length,
403 skipped: subtitleResult.skippedCount,
404 };
405 startHlsTranscode(session, streamInfo);
406 await waitForStreamStart(session);
407}
408
409async function createVideoStreamSession (sourcePath)
410{
411 pruneExpiredSessions();
412 ensureStreamRootDir();
413
414 const sessionId = crypto.randomBytes(18).toString('hex');
415 const outputDir = path.join(STREAM_ROOT_DIR, sessionId);
416 fs.mkdirSync(outputDir, { recursive: true });
417
418 const session = {
419 id: sessionId,
420 sourcePath,
421 outputDir,
422 expiresAt: Date.now() + STREAM_SESSION_TTL_MS,
423 process: null,
424 error: null,
425 subtitleTracks: [],
426 subtitleSummary: { total: 0, converted: 0, skipped: 0 },
427 readyPromise: null,
428 };
429
430 session.readyPromise = initialiseSession(session).catch((err) =>
431 {
432 session.error = err;
433 throw err;
434 });
435
436 sessions.set(sessionId, session);
437 await session.readyPromise;
438
439 return {
440 sessionId,
441 subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),
442 subtitleSummary: {
443 total: Number(session.subtitleSummary.total || 0),
444 converted: Number(session.subtitleSummary.converted || 0),
445 skipped: Number(session.subtitleSummary.skipped || 0),
446 },
447 };
448}
449
450function contentTypeForAsset (assetPath)
451{
452 const ext = path.extname(assetPath).toLowerCase();
453 if (ext === '.m3u8') return 'application/vnd.apple.mpegurl';
454 if (ext === '.ts') return 'video/mp2t';
455 if (ext === '.vtt') return 'text/vtt; charset=utf-8';
456 if (ext === '.aac') return 'audio/aac';
457 if (ext === '.mp4' || ext === '.m4s') return 'video/mp4';
458 return 'application/octet-stream';
459}
460
461async function sendVideoStreamAsset (sessionId, assetPath, res)
462{
463 pruneExpiredSessions();
464 const session = sessions.get(sessionId);
465 if (!session) throw makeHttpError(404, 'Video stream session not found.');
466
467 refreshSession(session);
468 await session.readyPromise;
469
470 const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');
471 const resolvedPath = path.resolve(session.outputDir, relativeAssetPath);
472 const resolvedRoot = path.resolve(session.outputDir);
473 if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(resolvedRoot + path.sep))
474 {
475 throw makeHttpError(404, 'Stream asset not found.');
476 }
477
478 await waitForFile(resolvedPath, session);
479 res.set('Cache-Control', 'private, no-store');
480 res.type(contentTypeForAsset(resolvedPath));
481 res.sendFile(resolvedPath);
482}
483
484module.exports = {
485 STREAM_ROOT_DIR,
486 STREAM_SESSION_TTL_MS,
487 createVideoStreamSession,
488 sendVideoStreamAsset,
489};