| 1 | 'use strict'; |
| 2 | |
| 3 | const { spawn } = require('child_process'); |
| 4 | const crypto = require('crypto'); |
| 5 | const fs = require('fs'); |
| 6 | const os = require('os'); |
| 7 | const path = require('path'); |
| 8 | |
| 9 | const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 10 | const STREAM_SESSION_TTL_MS = 30 * 60 * 1000; |
| 11 | const STREAM_READY_TIMEOUT_MS = 20 * 1000; |
| 12 | const STREAM_IDLE_STOP_MS = 5 * 60 * 1000; |
| 13 | const ESTIMATED_SEGMENT_BYTES = 1024 * 1024; |
| 14 | const STREAM_SEGMENT_RETENTION_COUNT = parseSegmentRetentionCount(process.env.VIDEO_STREAM_SEGMENT_RETENTION_COUNT); |
| 15 | const sessions = new Map(); |
| 16 | |
| 17 | function parseSegmentRetentionCount (value) |
| 18 | { |
| 19 | const parsed = Number.parseInt(String(value || ''), 10); |
| 20 | if (Number.isInteger(parsed) && parsed >= 30) return parsed; |
| 21 | return defaultSegmentRetentionCount(); |
| 22 | } |
| 23 | |
| 24 | function readRaspberryPiModel () |
| 25 | { |
| 26 | try |
| 27 | { |
| 28 | return fs.readFileSync('/proc/device-tree/model', 'utf8').replace(/\u0000/g, '').trim(); |
| 29 | } catch |
| 30 | { |
| 31 | return ''; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | function clampNumber (value, min, max) |
| 36 | { |
| 37 | return Math.min(max, Math.max(min, value)); |
| 38 | } |
| 39 | |
| 40 | function currentCpuPressureFactor (cpuCount) |
| 41 | { |
| 42 | if (typeof os.loadavg !== 'function') return 1; |
| 43 | if (!Number.isFinite(cpuCount) || cpuCount <= 0) return 1; |
| 44 | |
| 45 | const [load1] = os.loadavg(); |
| 46 | if (!Number.isFinite(load1) || load1 < 0) return 1; |
| 47 | |
| 48 | const saturation = load1 / cpuCount; |
| 49 | if (saturation >= 1.5) return 0.72; |
| 50 | if (saturation >= 1.2) return 0.8; |
| 51 | if (saturation >= 1.0) return 0.88; |
| 52 | if (saturation >= 0.8) return 0.94; |
| 53 | return 1; |
| 54 | } |
| 55 | |
| 56 | function defaultSegmentRetentionCount () |
| 57 | { |
| 58 | const totalMemBytes = Number(os.totalmem()) || 0; |
| 59 | const freeMemBytes = Number(os.freemem()) || 0; |
| 60 | const cpuCount = Math.max(1, ((os.cpus() || []).length || 1)); |
| 61 | const arch = String(os.arch() || '').toLowerCase(); |
| 62 | const piModel = readRaspberryPiModel().toLowerCase(); |
| 63 | const isPi5 = piModel.includes('raspberry pi 5'); |
| 64 | const isArm = arch === 'arm' || arch === 'arm64' || arch.startsWith('armv'); |
| 65 | const cpuPressure = currentCpuPressureFactor(cpuCount); |
| 66 | |
| 67 | const freeMemRatio = totalMemBytes > 0 ? (freeMemBytes / totalMemBytes) : 1; |
| 68 | const memoryPressure = freeMemRatio < 0.12 ? 0.72 : freeMemRatio < 0.2 ? 0.84 : freeMemRatio < 0.3 ? 0.92 : 1; |
| 69 | |
| 70 | if (isPi5) |
| 71 | { |
| 72 | const memoryBudgetBytes = Math.floor(totalMemBytes * 0.03); |
| 73 | const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES); |
| 74 | const byCpu = 120 + ((cpuCount - 2) * 20); |
| 75 | const combined = Math.min(byMemory, byCpu); |
| 76 | return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 100, 220); |
| 77 | } |
| 78 | |
| 79 | if (isArm) |
| 80 | { |
| 81 | const memoryBudgetBytes = Math.floor(totalMemBytes * 0.025); |
| 82 | const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES); |
| 83 | const byCpu = 90 + ((cpuCount - 2) * 14); |
| 84 | const combined = Math.min(byMemory, byCpu); |
| 85 | return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 80, 180); |
| 86 | } |
| 87 | |
| 88 | const memoryBudgetBytes = Math.floor(totalMemBytes * 0.05); |
| 89 | const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES); |
| 90 | const byCpu = 140 + ((cpuCount - 4) * 16); |
| 91 | const combined = Math.min(byMemory, byCpu); |
| 92 | return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 120, 320); |
| 93 | } |
| 94 | |
| 95 | function hasInitialHlsAssets (outputDir) |
| 96 | { |
| 97 | try |
| 98 | { |
| 99 | const entries = fs.readdirSync(outputDir, { withFileTypes: true }); |
| 100 | return entries.some((entry) => |
| 101 | { |
| 102 | if (!entry.isFile()) return false; |
| 103 | if (entry.name === 'master.m3u8') return true; |
| 104 | if (/^stream_\d+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true; |
| 105 | if (/^stream_\d+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true; |
| 106 | return false; |
| 107 | }); |
| 108 | } catch |
| 109 | { |
| 110 | return false; |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | function makeHttpError (status, message) |
| 115 | { |
| 116 | const err = new Error(message); |
| 117 | err.status = status; |
| 118 | return err; |
| 119 | } |
| 120 | |
| 121 | function ensureStreamRootDir () |
| 122 | { |
| 123 | fs.mkdirSync(STREAM_ROOT_DIR, { recursive: true }); |
| 124 | } |
| 125 | |
| 126 | function ffmpegPath () |
| 127 | { |
| 128 | return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg'; |
| 129 | } |
| 130 | |
| 131 | function ffprobePath () |
| 132 | { |
| 133 | return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe'; |
| 134 | } |
| 135 | |
| 136 | function pruneExpiredSessions () |
| 137 | { |
| 138 | const now = Date.now(); |
| 139 | for (const [sessionId, session] of sessions) |
| 140 | { |
| 141 | if (session.expiresAt > now) continue; |
| 142 | destroySession(sessionId); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | function refreshSession (session) |
| 147 | { |
| 148 | session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS; |
| 149 | } |
| 150 | |
| 151 | function destroySession (sessionId) |
| 152 | { |
| 153 | const session = sessions.get(sessionId); |
| 154 | if (!session) return false; |
| 155 | |
| 156 | sessions.delete(sessionId); |
| 157 | |
| 158 | if (session.idleTimer) |
| 159 | { |
| 160 | clearTimeout(session.idleTimer); |
| 161 | session.idleTimer = null; |
| 162 | } |
| 163 | |
| 164 | try |
| 165 | { |
| 166 | if (session.process) session.process.kill('SIGTERM'); |
| 167 | } catch |
| 168 | { |
| 169 | // Ignore process cleanup failures. |
| 170 | } |
| 171 | |
| 172 | fs.rmSync(session.outputDir, { recursive: true, force: true }); |
| 173 | return true; |
| 174 | } |
| 175 | |
| 176 | function touchSessionActivity (session) |
| 177 | { |
| 178 | refreshSession(session); |
| 179 | session.lastActivityAt = Date.now(); |
| 180 | } |
| 181 | |
| 182 | function clearIdleStopTimer (session) |
| 183 | { |
| 184 | if (!session.idleTimer) return; |
| 185 | clearTimeout(session.idleTimer); |
| 186 | session.idleTimer = null; |
| 187 | } |
| 188 | |
| 189 | function scheduleIdleStop (session) |
| 190 | { |
| 191 | clearIdleStopTimer(session); |
| 192 | if (session.activeRequests > 0) return; |
| 193 | |
| 194 | session.idleTimer = setTimeout(() => |
| 195 | { |
| 196 | const activeSession = sessions.get(session.id); |
| 197 | if (!activeSession) return; |
| 198 | if (activeSession.activeRequests > 0) return; |
| 199 | if (Date.now() - activeSession.lastActivityAt < STREAM_IDLE_STOP_MS) |
| 200 | { |
| 201 | scheduleIdleStop(activeSession); |
| 202 | return; |
| 203 | } |
| 204 | destroySession(activeSession.id); |
| 205 | }, STREAM_IDLE_STOP_MS); |
| 206 | } |
| 207 | |
| 208 | function startAssetRequest (session) |
| 209 | { |
| 210 | session.activeRequests += 1; |
| 211 | touchSessionActivity(session); |
| 212 | clearIdleStopTimer(session); |
| 213 | } |
| 214 | |
| 215 | function finishAssetRequest (session) |
| 216 | { |
| 217 | if (session.activeRequests > 0) session.activeRequests -= 1; |
| 218 | touchSessionActivity(session); |
| 219 | if (session.activeRequests === 0) scheduleIdleStop(session); |
| 220 | } |
| 221 | |
| 222 | function parseSegmentIndexFromAssetPath (assetPath) |
| 223 | { |
| 224 | const baseName = path.basename(String(assetPath || '')); |
| 225 | const match = baseName.match(/^stream_\d+_segment_(\d+)\.ts$/i); |
| 226 | if (!match) return null; |
| 227 | |
| 228 | const segmentIndex = Number.parseInt(match[1], 10); |
| 229 | return Number.isInteger(segmentIndex) ? segmentIndex : null; |
| 230 | } |
| 231 | |
| 232 | function runSegmentPrune (session) |
| 233 | { |
| 234 | if (session.segmentPruneRunning) return; |
| 235 | if (session.segmentPrunePendingCutoff <= session.segmentPrunedUntil) return; |
| 236 | |
| 237 | const cutoff = session.segmentPrunePendingCutoff; |
| 238 | session.segmentPruneRunning = true; |
| 239 | |
| 240 | fs.promises.readdir(session.outputDir) |
| 241 | .then((entries) => |
| 242 | { |
| 243 | const removals = []; |
| 244 | for (const entryName of entries) |
| 245 | { |
| 246 | const match = String(entryName).match(/^stream_\d+_segment_(\d+)\.ts$/i); |
| 247 | if (!match) continue; |
| 248 | const segmentIndex = Number.parseInt(match[1], 10); |
| 249 | if (!Number.isInteger(segmentIndex)) continue; |
| 250 | if (segmentIndex > cutoff) continue; |
| 251 | |
| 252 | removals.push( |
| 253 | fs.promises.unlink(path.join(session.outputDir, entryName)).catch(() => |
| 254 | { |
| 255 | // Ignore races while ffmpeg rotates temp files and request handlers read segments. |
| 256 | }) |
| 257 | ); |
| 258 | } |
| 259 | return Promise.all(removals); |
| 260 | }) |
| 261 | .then(() => |
| 262 | { |
| 263 | session.segmentPrunedUntil = Math.max(session.segmentPrunedUntil, cutoff); |
| 264 | }) |
| 265 | .catch(() => |
| 266 | { |
| 267 | // Best effort cleanup; keep streaming even if pruning fails. |
| 268 | }) |
| 269 | .finally(() => |
| 270 | { |
| 271 | session.segmentPruneRunning = false; |
| 272 | if (session.segmentPrunePendingCutoff > session.segmentPrunedUntil) |
| 273 | { |
| 274 | runSegmentPrune(session); |
| 275 | } |
| 276 | }); |
| 277 | } |
| 278 | |
| 279 | function scheduleSegmentPrune (session, segmentIndex) |
| 280 | { |
| 281 | if (!Number.isInteger(segmentIndex) || segmentIndex < 0) return; |
| 282 | |
| 283 | const pruneCutoff = segmentIndex - STREAM_SEGMENT_RETENTION_COUNT; |
| 284 | if (pruneCutoff <= session.segmentPrunedUntil) return; |
| 285 | |
| 286 | session.segmentPrunePendingCutoff = Math.max(session.segmentPrunePendingCutoff, pruneCutoff); |
| 287 | runSegmentPrune(session); |
| 288 | } |
| 289 | |
| 290 | function runCommand (command, args) |
| 291 | { |
| 292 | return new Promise((resolve, reject) => |
| 293 | { |
| 294 | const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] }); |
| 295 | let stdout = ''; |
| 296 | let stderr = ''; |
| 297 | |
| 298 | child.stdout.on('data', (chunk) => |
| 299 | { |
| 300 | stdout += chunk.toString(); |
| 301 | }); |
| 302 | |
| 303 | child.stderr.on('data', (chunk) => |
| 304 | { |
| 305 | stderr += chunk.toString(); |
| 306 | }); |
| 307 | |
| 308 | child.on('error', (err) => |
| 309 | { |
| 310 | if (err && err.code === 'ENOENT') |
| 311 | { |
| 312 | reject(makeHttpError(503, `${command} is not installed or not available in PATH.`)); |
| 313 | return; |
| 314 | } |
| 315 | reject(err); |
| 316 | }); |
| 317 | |
| 318 | child.on('close', (code) => |
| 319 | { |
| 320 | if (code === 0) |
| 321 | { |
| 322 | resolve({ stdout, stderr }); |
| 323 | return; |
| 324 | } |
| 325 | reject(makeHttpError(500, stderr.trim() || `${command} exited with code ${code}.`)); |
| 326 | }); |
| 327 | }); |
| 328 | } |
| 329 | |
| 330 | async function probeInput (sourcePath) |
| 331 | { |
| 332 | const { stdout } = await runCommand(ffprobePath(), [ |
| 333 | '-v', 'error', |
| 334 | '-print_format', 'json', |
| 335 | '-show_streams', |
| 336 | '-show_format', |
| 337 | sourcePath, |
| 338 | ]); |
| 339 | |
| 340 | let payload; |
| 341 | try |
| 342 | { |
| 343 | payload = JSON.parse(stdout || '{}'); |
| 344 | } catch |
| 345 | { |
| 346 | throw makeHttpError(500, 'ffprobe returned invalid stream metadata.'); |
| 347 | } |
| 348 | |
| 349 | const typedIndexes = { video: 0, audio: 0, subtitle: 0 }; |
| 350 | const streams = Array.isArray(payload.streams) ? payload.streams.map((stream) => |
| 351 | { |
| 352 | const codecType = String(stream.codec_type || '').toLowerCase(); |
| 353 | const relativeIndex = Object.prototype.hasOwnProperty.call(typedIndexes, codecType) |
| 354 | ? typedIndexes[codecType]++ |
| 355 | : null; |
| 356 | return { |
| 357 | ...stream, |
| 358 | codecType, |
| 359 | relativeIndex, |
| 360 | tags: stream.tags || {}, |
| 361 | disposition: stream.disposition || {}, |
| 362 | }; |
| 363 | }) : []; |
| 364 | |
| 365 | return { |
| 366 | raw: payload, |
| 367 | durationSeconds: inputDurationSeconds(payload, streams), |
| 368 | video: streams.filter((stream) => stream.codecType === 'video'), |
| 369 | audio: streams.filter((stream) => stream.codecType === 'audio'), |
| 370 | subtitles: streams.filter((stream) => stream.codecType === 'subtitle'), |
| 371 | }; |
| 372 | } |
| 373 | |
| 374 | function parsePositiveNumber (value) |
| 375 | { |
| 376 | const number = Number(value); |
| 377 | return Number.isFinite(number) && number > 0 ? number : null; |
| 378 | } |
| 379 | |
| 380 | function parseDurationTagSeconds (value) |
| 381 | { |
| 382 | const raw = String(value || '').trim(); |
| 383 | if (!raw) return null; |
| 384 | |
| 385 | const numeric = parsePositiveNumber(raw); |
| 386 | if (numeric) return numeric; |
| 387 | |
| 388 | const match = raw.match(/^(\d+):([0-5]?\d):([0-5]?\d(?:\.\d+)?)$/); |
| 389 | if (!match) return null; |
| 390 | |
| 391 | const hours = Number(match[1]); |
| 392 | const minutes = Number(match[2]); |
| 393 | const seconds = Number(match[3]); |
| 394 | if (!Number.isFinite(hours) || !Number.isFinite(minutes) || !Number.isFinite(seconds)) return null; |
| 395 | return hours * 3600 + minutes * 60 + seconds; |
| 396 | } |
| 397 | |
| 398 | function inputDurationSeconds (payload, streams) |
| 399 | { |
| 400 | const formatDuration = parsePositiveNumber(payload && payload.format && payload.format.duration); |
| 401 | if (formatDuration) return formatDuration; |
| 402 | |
| 403 | for (const stream of streams) |
| 404 | { |
| 405 | const duration = parsePositiveNumber(stream.duration); |
| 406 | if (duration) return duration; |
| 407 | } |
| 408 | |
| 409 | const formatTags = payload && payload.format && payload.format.tags; |
| 410 | const formatTagDuration = formatTags && parseDurationTagSeconds(formatTags.duration || formatTags.DURATION); |
| 411 | if (formatTagDuration) return formatTagDuration; |
| 412 | |
| 413 | for (const stream of streams) |
| 414 | { |
| 415 | const tagDuration = parseDurationTagSeconds(stream.tags.duration || stream.tags.DURATION); |
| 416 | if (tagDuration) return tagDuration; |
| 417 | } |
| 418 | |
| 419 | return null; |
| 420 | } |
| 421 | |
| 422 | function sanitiseTrackValue (value, fallback) |
| 423 | { |
| 424 | const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, ''); |
| 425 | return cleaned || fallback; |
| 426 | } |
| 427 | |
| 428 | function trackLanguage (stream) |
| 429 | { |
| 430 | return sanitiseTrackValue(stream.tags.language || stream.tags.LANGUAGE || 'und', 'und').slice(0, 8); |
| 431 | } |
| 432 | |
| 433 | function trackLabel (stream, fallback) |
| 434 | { |
| 435 | const title = String(stream.tags.title || stream.tags.handler_name || '').trim(); |
| 436 | if (title) return title; |
| 437 | const language = trackLanguage(stream); |
| 438 | if (language && language !== 'und') return `${fallback} (${language})`; |
| 439 | return fallback; |
| 440 | } |
| 441 | |
| 442 | async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams) |
| 443 | { |
| 444 | const extractedTracks = []; |
| 445 | let skippedCount = 0; |
| 446 | let trackNumber = 0; |
| 447 | |
| 448 | for (const stream of subtitleStreams) |
| 449 | { |
| 450 | const fileName = `subtitle-${trackNumber}.vtt`; |
| 451 | const targetPath = path.join(outputDir, fileName); |
| 452 | |
| 453 | try |
| 454 | { |
| 455 | await runCommand(ffmpegPath(), [ |
| 456 | '-hide_banner', |
| 457 | '-loglevel', 'error', |
| 458 | '-nostdin', |
| 459 | '-y', |
| 460 | '-i', sourcePath, |
| 461 | '-map', `0:s:${stream.relativeIndex}`, |
| 462 | '-c:s', 'webvtt', |
| 463 | targetPath, |
| 464 | ]); |
| 465 | } catch |
| 466 | { |
| 467 | skippedCount += 1; |
| 468 | continue; |
| 469 | } |
| 470 | |
| 471 | extractedTracks.push({ |
| 472 | fileName, |
| 473 | label: trackLabel(stream, `Subtitle ${trackNumber + 1}`), |
| 474 | language: trackLanguage(stream), |
| 475 | isDefault: !!stream.disposition.default, |
| 476 | }); |
| 477 | trackNumber += 1; |
| 478 | } |
| 479 | |
| 480 | return { |
| 481 | tracks: extractedTracks, |
| 482 | skippedCount, |
| 483 | }; |
| 484 | } |
| 485 | |
| 486 | function buildHlsArgs (sourcePath, outputDir, streamInfo) |
| 487 | { |
| 488 | const args = [ |
| 489 | '-hide_banner', |
| 490 | '-loglevel', 'error', |
| 491 | '-nostdin', |
| 492 | '-y', |
| 493 | '-i', sourcePath, |
| 494 | '-map', '0:v:0', |
| 495 | ]; |
| 496 | |
| 497 | for (const audioStream of streamInfo.audio) |
| 498 | { |
| 499 | args.push('-map', `0:a:${audioStream.relativeIndex}`); |
| 500 | } |
| 501 | |
| 502 | args.push( |
| 503 | '-c:v', 'libx264', |
| 504 | '-preset', 'veryfast', |
| 505 | '-crf', '23', |
| 506 | '-pix_fmt', 'yuv420p', |
| 507 | '-g', '48', |
| 508 | '-sc_threshold', '0', |
| 509 | ); |
| 510 | |
| 511 | if (streamInfo.audio.length) |
| 512 | { |
| 513 | args.push('-c:a', 'aac', '-b:a', '160k', '-ac', '2'); |
| 514 | } else |
| 515 | { |
| 516 | args.push('-an'); |
| 517 | } |
| 518 | |
| 519 | const variantMap = []; |
| 520 | if (streamInfo.audio.length) |
| 521 | { |
| 522 | variantMap.push('v:0,agroup:audio,name:video'); |
| 523 | streamInfo.audio.forEach((audioStream, index) => |
| 524 | { |
| 525 | let entry = `a:${index},agroup:audio,name:${sanitiseTrackValue(trackLabel(audioStream, `Audio ${index + 1}`), `audio-${index + 1}`)},language:${trackLanguage(audioStream)}`; |
| 526 | if (audioStream.disposition.default) entry += ',default:yes'; |
| 527 | variantMap.push(entry); |
| 528 | }); |
| 529 | } else |
| 530 | { |
| 531 | variantMap.push('v:0,name:video'); |
| 532 | } |
| 533 | |
| 534 | args.push( |
| 535 | '-f', 'hls', |
| 536 | '-hls_time', '4', |
| 537 | '-hls_list_size', '0', |
| 538 | '-hls_flags', 'independent_segments+temp_file', |
| 539 | '-master_pl_name', 'master.m3u8', |
| 540 | '-hls_segment_filename', path.join(outputDir, 'stream_%v_segment_%06d.ts'), |
| 541 | '-var_stream_map', variantMap.join(' '), |
| 542 | path.join(outputDir, 'stream_%v.m3u8'), |
| 543 | ); |
| 544 | |
| 545 | return args; |
| 546 | } |
| 547 | |
| 548 | function startHlsTranscode (session, streamInfo) |
| 549 | { |
| 550 | const args = buildHlsArgs(session.sourcePath, session.outputDir, streamInfo); |
| 551 | const child = spawn(ffmpegPath(), args, { stdio: ['ignore', 'ignore', 'pipe'] }); |
| 552 | let stderr = ''; |
| 553 | |
| 554 | child.stderr.on('data', (chunk) => |
| 555 | { |
| 556 | stderr += chunk.toString(); |
| 557 | if (stderr.length > 16000) stderr = stderr.slice(-16000); |
| 558 | }); |
| 559 | |
| 560 | child.on('error', (err) => |
| 561 | { |
| 562 | if (err && err.code === 'ENOENT') |
| 563 | { |
| 564 | session.error = makeHttpError(503, 'ffmpeg is not installed or not available in PATH.'); |
| 565 | return; |
| 566 | } |
| 567 | session.error = err; |
| 568 | }); |
| 569 | |
| 570 | child.on('close', (code) => |
| 571 | { |
| 572 | session.process = null; |
| 573 | if (code === 0 || session.error) return; |
| 574 | session.error = makeHttpError(500, stderr.trim() || `ffmpeg exited with code ${code}.`); |
| 575 | }); |
| 576 | |
| 577 | session.process = child; |
| 578 | } |
| 579 | |
| 580 | function waitForFile (targetPath, session, timeoutMs = STREAM_READY_TIMEOUT_MS) |
| 581 | { |
| 582 | const startedAt = Date.now(); |
| 583 | |
| 584 | return new Promise((resolve, reject) => |
| 585 | { |
| 586 | const check = () => |
| 587 | { |
| 588 | if (fs.existsSync(targetPath)) |
| 589 | { |
| 590 | resolve(); |
| 591 | return; |
| 592 | } |
| 593 | |
| 594 | if (session.error) |
| 595 | { |
| 596 | reject(session.error); |
| 597 | return; |
| 598 | } |
| 599 | |
| 600 | if (Date.now() - startedAt >= timeoutMs) |
| 601 | { |
| 602 | reject(makeHttpError(504, 'Timed out while preparing the video stream.')); |
| 603 | return; |
| 604 | } |
| 605 | |
| 606 | setTimeout(check, 120); |
| 607 | }; |
| 608 | |
| 609 | check(); |
| 610 | }); |
| 611 | } |
| 612 | |
| 613 | function waitForStreamStart (session, timeoutMs = STREAM_READY_TIMEOUT_MS) |
| 614 | { |
| 615 | const startedAt = Date.now(); |
| 616 | |
| 617 | return new Promise((resolve, reject) => |
| 618 | { |
| 619 | const check = () => |
| 620 | { |
| 621 | if (fs.existsSync(path.join(session.outputDir, 'master.m3u8')) || hasInitialHlsAssets(session.outputDir)) |
| 622 | { |
| 623 | resolve(); |
| 624 | return; |
| 625 | } |
| 626 | |
| 627 | if (session.error) |
| 628 | { |
| 629 | reject(session.error); |
| 630 | return; |
| 631 | } |
| 632 | |
| 633 | if (!session.process) |
| 634 | { |
| 635 | reject(makeHttpError(500, 'Video stream preparation stopped unexpectedly.')); |
| 636 | return; |
| 637 | } |
| 638 | |
| 639 | if (Date.now() - startedAt >= timeoutMs) |
| 640 | { |
| 641 | reject(makeHttpError(504, 'Timed out while preparing the video stream.')); |
| 642 | return; |
| 643 | } |
| 644 | |
| 645 | setTimeout(check, 120); |
| 646 | }; |
| 647 | |
| 648 | check(); |
| 649 | }); |
| 650 | } |
| 651 | |
| 652 | async function initialiseSession (session) |
| 653 | { |
| 654 | const streamInfo = await probeInput(session.sourcePath); |
| 655 | if (!streamInfo.video.length) |
| 656 | { |
| 657 | throw makeHttpError(400, 'File does not contain a video stream.'); |
| 658 | } |
| 659 | |
| 660 | const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles); |
| 661 | session.subtitleTracks = subtitleResult.tracks; |
| 662 | session.subtitleSummary = { |
| 663 | total: streamInfo.subtitles.length, |
| 664 | converted: subtitleResult.tracks.length, |
| 665 | skipped: subtitleResult.skippedCount, |
| 666 | }; |
| 667 | startHlsTranscode(session, streamInfo); |
| 668 | session.durationSeconds = streamInfo.durationSeconds; |
| 669 | await waitForStreamStart(session); |
| 670 | } |
| 671 | |
| 672 | async function createVideoStreamSession (sourcePath) |
| 673 | { |
| 674 | pruneExpiredSessions(); |
| 675 | ensureStreamRootDir(); |
| 676 | |
| 677 | const sessionId = crypto.randomBytes(18).toString('hex'); |
| 678 | const outputDir = path.join(STREAM_ROOT_DIR, sessionId); |
| 679 | fs.mkdirSync(outputDir, { recursive: true }); |
| 680 | |
| 681 | const session = { |
| 682 | id: sessionId, |
| 683 | sourcePath, |
| 684 | outputDir, |
| 685 | expiresAt: Date.now() + STREAM_SESSION_TTL_MS, |
| 686 | process: null, |
| 687 | error: null, |
| 688 | subtitleTracks: [], |
| 689 | subtitleSummary: { total: 0, converted: 0, skipped: 0 }, |
| 690 | readyPromise: null, |
| 691 | activeRequests: 0, |
| 692 | lastActivityAt: Date.now(), |
| 693 | idleTimer: null, |
| 694 | segmentPruneRunning: false, |
| 695 | segmentPrunePendingCutoff: -1, |
| 696 | segmentPrunedUntil: -1, |
| 697 | }; |
| 698 | |
| 699 | session.readyPromise = initialiseSession(session).catch((err) => |
| 700 | { |
| 701 | session.error = err; |
| 702 | throw err; |
| 703 | }); |
| 704 | |
| 705 | sessions.set(sessionId, session); |
| 706 | await session.readyPromise; |
| 707 | |
| 708 | return { |
| 709 | sessionId, |
| 710 | durationSeconds: session.durationSeconds, |
| 711 | subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })), |
| 712 | subtitleSummary: { |
| 713 | total: Number(session.subtitleSummary.total || 0), |
| 714 | converted: Number(session.subtitleSummary.converted || 0), |
| 715 | skipped: Number(session.subtitleSummary.skipped || 0), |
| 716 | }, |
| 717 | }; |
| 718 | } |
| 719 | |
| 720 | function contentTypeForAsset (assetPath) |
| 721 | { |
| 722 | const ext = path.extname(assetPath).toLowerCase(); |
| 723 | if (ext === '.m3u8') return 'application/vnd.apple.mpegurl'; |
| 724 | if (ext === '.ts') return 'video/mp2t'; |
| 725 | if (ext === '.vtt') return 'text/vtt; charset=utf-8'; |
| 726 | if (ext === '.aac') return 'audio/aac'; |
| 727 | if (ext === '.mp4' || ext === '.m4s') return 'video/mp4'; |
| 728 | return 'application/octet-stream'; |
| 729 | } |
| 730 | |
| 731 | async function sendVideoStreamAsset (sessionId, assetPath, req, res) |
| 732 | { |
| 733 | pruneExpiredSessions(); |
| 734 | const session = sessions.get(sessionId); |
| 735 | if (!session) throw makeHttpError(404, 'Video stream session not found.'); |
| 736 | |
| 737 | touchSessionActivity(session); |
| 738 | await session.readyPromise; |
| 739 | |
| 740 | const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, ''); |
| 741 | const resolvedPath = path.resolve(session.outputDir, relativeAssetPath); |
| 742 | const resolvedRoot = path.resolve(session.outputDir); |
| 743 | if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(resolvedRoot + path.sep)) |
| 744 | { |
| 745 | throw makeHttpError(404, 'Stream asset not found.'); |
| 746 | } |
| 747 | |
| 748 | const segmentIndex = parseSegmentIndexFromAssetPath(relativeAssetPath); |
| 749 | if (segmentIndex !== null) scheduleSegmentPrune(session, segmentIndex); |
| 750 | |
| 751 | await waitForFile(resolvedPath, session); |
| 752 | res.set('Cache-Control', 'private, no-store'); |
| 753 | res.type(contentTypeForAsset(resolvedPath)); |
| 754 | |
| 755 | startAssetRequest(session); |
| 756 | |
| 757 | let settled = false; |
| 758 | const finish = () => |
| 759 | { |
| 760 | if (settled) return; |
| 761 | settled = true; |
| 762 | finishAssetRequest(session); |
| 763 | }; |
| 764 | |
| 765 | req.on('aborted', finish); |
| 766 | res.on('close', finish); |
| 767 | res.on('finish', finish); |
| 768 | res.on('error', finish); |
| 769 | |
| 770 | await new Promise((resolve, reject) => |
| 771 | { |
| 772 | res.sendFile(resolvedPath, (err) => |
| 773 | { |
| 774 | finish(); |
| 775 | if (!err) |
| 776 | { |
| 777 | resolve(); |
| 778 | return; |
| 779 | } |
| 780 | |
| 781 | if (err.code === 'ECONNABORTED' || err.message === 'Request aborted') |
| 782 | { |
| 783 | resolve(); |
| 784 | return; |
| 785 | } |
| 786 | |
| 787 | reject(err); |
| 788 | }); |
| 789 | }); |
| 790 | } |
| 791 | |
| 792 | function releaseVideoStreamSession (sessionId) |
| 793 | { |
| 794 | pruneExpiredSessions(); |
| 795 | return destroySession(String(sessionId || '')); |
| 796 | } |
| 797 | |
| 798 | module.exports = { |
| 799 | STREAM_ROOT_DIR, |
| 800 | STREAM_SESSION_TTL_MS, |
| 801 | STREAM_IDLE_STOP_MS, |
| 802 | STREAM_SEGMENT_RETENTION_COUNT, |
| 803 | createVideoStreamSession, |
| 804 | sendVideoStreamAsset, |
| 805 | releaseVideoStreamSession, |
| 806 | }; |