Instancia transcoder t1: cambios locales

This commit is contained in:
Joaquin
2026-07-13 15:19:13 +00:00
parent 0e26a90dae
commit bb189a472e
27 changed files with 2161 additions and 496 deletions
+33 -18
View File
@@ -18,6 +18,7 @@ const fs = require('fs').promises;
const crypto = require('crypto');
const EventEmitter = require('events');
const hwDetect = require('./hwDetect');
const streamInput = require('../utils/streamInput');
// Session storage
const sessions = new Map();
@@ -26,9 +27,9 @@ const sessions = new Map();
const CACHE_DIR = path.join(process.cwd(), 'transcode-cache');
// Session settings
const SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes idle timeout
const SESSION_TIMEOUT_MS = 3 * 60 * 1000; // 3 minutes idle timeout (kills orphaned sessions quickly)
const SEGMENT_DURATION = 4; // seconds per HLS segment
const CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // Check every 5 minutes
const CLEANUP_INTERVAL_MS = 60 * 1000; // Check every 60 seconds
/**
* Generate a unique session ID
@@ -181,11 +182,17 @@ class TranscodeSession extends EventEmitter {
console.log(`[TranscodeSession ${this.id}] Auto encoder resolved to: ${encoder}`);
}
const sizing = streamInput.probeSizingForUrl(this.url);
const referer = streamInput.deriveRefererFromUrl(this.url);
const args = [
'-hide_banner',
'-loglevel', 'warning',
'-user_agent', this.options.userAgent,
];
if (referer) {
args.push('-referer', referer);
}
// Add hardware acceleration input options based on encoder (only if encoding)
if (videoMode === 'encode') {
@@ -194,8 +201,8 @@ class TranscodeSession extends EventEmitter {
// Input options (common)
args.push(
'-probesize', '5000000',
'-analyzeduration', '5000000',
'-probesize', sizing.probesize,
'-analyzeduration', sizing.analyzeduration,
'-fflags', '+genpts+discardcorrupt',
'-err_detect', 'ignore_err',
'-reconnect', '1',
@@ -222,7 +229,10 @@ class TranscodeSession extends EventEmitter {
if (this.options.videoCodec === 'hevc' || this.options.videoCodec === 'h265') {
args.push('-bsf:v', 'hevc_mp4toannexb');
} else if (this.options.videoCodec === 'h264' || this.options.videoCodec === 'avc') {
args.push('-bsf:v', 'h264_mp4toannexb');
// Keep Annex-B conversion and force parameter sets to be repeated.
// This helps players recover on streams where SPS/PPS appear sporadically,
// which often manifests as "audio OK, black video".
args.push('-bsf:v', 'h264_mp4toannexb,dump_extra');
} else {
// Fallback (e.g. unknown codec), try strict extraction
args.push('-bsf:v', 'dump_extra');
@@ -296,12 +306,12 @@ class TranscodeSession extends EventEmitter {
);
break;
case 'vaapi':
// VAAPI hardware decoding (Linux)
args.push(
'-hwaccel', 'vaapi',
'-hwaccel_device', '/dev/dri/renderD128',
'-hwaccel_output_format', 'vaapi'
);
// Solo registramos el dispositivo VAAPI globalmente.
// Se usa decodificación SOFTWARE para máxima compatibilidad con
// cualquier codec de entrada (HEVC, VP9, etc.) — el GPU Intel
// puede no tener soporte de decodificación para todos ellos.
// El upload a memoria VAAPI se hace en el filtro de vídeo.
args.push('-vaapi_device', '/dev/dri/renderD128');
break;
case 'qsv':
// Intel QuickSync hardware decoding
@@ -404,7 +414,9 @@ class TranscodeSession extends EventEmitter {
// Force nv12 (8-bit) output to handle 10-bit inputs (fixes "10 bit encode not supported")
return `scale_cuda=-2:${height}:interp_algo=lanczos:format=nv12`;
case 'vaapi':
return `scale_vaapi=w=-2:h=${height}:format=nv12`;
// Software decode → scale → nv12 → hwupload → VAAPI encode
// format=nv12 ANTES de hwupload es obligatorio para Intel iGPU en LXC
return `scale=-2:${height},format=nv12,hwupload`;
case 'qsv':
return `scale_qsv=w=-2:h=${height}:format=nv12`;
case 'amf':
@@ -466,14 +478,11 @@ class TranscodeSession extends EventEmitter {
// The format is handled automatically when using -hwaccel_output_format vaapi
args.push('-vf', this.buildScaleFilter('vaapi', height));
// VAAPI encoder with quality setting
// Note: -global_quality is the portable way to set quality for VAAPI
// VAAPI encoder. No especificar -profile:v ni -pix_fmt (los gestiona el driver).
// -bf 3 puede causar problemas en algunos drivers Intel; se omite.
args.push(
'-c:v', 'h264_vaapi',
'-profile:v', 'main', // Use main profile for compatibility
'-global_quality', String(qp),
'-bf', '3',
'-pix_fmt', 'yuv420p' // Force 8-bit output for compatibility
'-global_quality', String(qp)
);
}
@@ -551,6 +560,7 @@ class TranscodeSession extends EventEmitter {
/**
* Wait for playlist to be ready (with timeout)
* Fast-fails if FFmpeg exited with an error before the timeout.
*/
async waitForPlaylist(timeoutMs = 10000) {
const startTime = Date.now();
@@ -558,6 +568,11 @@ class TranscodeSession extends EventEmitter {
if (await this.isPlaylistReady()) {
return true;
}
// Fast-fail: FFmpeg already exited with an error — no point waiting
if (this.status === 'error' && !this.process) {
console.log(`[TranscodeSession ${this.id}] Fast-fail: FFmpeg exited with error, aborting wait`);
return false;
}
await new Promise(resolve => setTimeout(resolve, 200));
}
return false;