feat: Tdarr Local Flow Plugin Suite v1.0
7 atomic plugins for automated x265 transcoding pipeline: - utility/mediaAnalyzerGOP : GOP calc, FPS detection, film/series/anime routing - utility/setAnimationFlag : manual animation flag override - utility/extractChaptersXml : mkvextract chapters to XML - audio/audioSelectorClamping : codec scoring, clamped Opus bitrates, 2 outputs - audio/backupSourceAudio : lossless DTS/TrueHD ITA backup (-c:a copy) - subtitles/extractSubtitlesAndOcr : SRT extract + SubtitleEdit OCR for PGS - video/transcode2PassX265 : 2-pass x265, Lanczos 1080p bound, Opus mux Test suite: 34 unit tests + 3 integration tests (FFmpeg real files) FlowHelpers mock for local testing included Docs: integration-guide.md with canvas wiring and deploy instructions
This commit is contained in:
commit
c2074be826
19 files changed
+2134
No files matched your search
@@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
const { execSync, spawnSync } = require('child_process');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const FFMPEG = process.env.FFMPEG_PATH || 'ffmpeg';
|
||||
|
||||
const SAMPLES = {
|
||||
test1: 'tests/samples/media/toshiba/Radarr/Film Test (2023)/Film Test (2023).mkv',
|
||||
test2: 'tests/samples/media/toshiba/Sonarr/Naruto S01/Naruto S01E01.mkv',
|
||||
test3: 'tests/samples/test3_ultrawide.mkv',
|
||||
test4: 'tests/samples/test4_subtitles.mkv',
|
||||
};
|
||||
|
||||
function run(cmd) {
|
||||
console.log(`\n>> ${cmd}\n`);
|
||||
const result = spawnSync(cmd, { shell: true, stdio: 'inherit' });
|
||||
if (result.status !== 0) {
|
||||
console.error(`Command failed with exit ${result.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureDir(filePath) {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
|
||||
// Test 1 — skip if already generated
|
||||
if (!fs.existsSync(SAMPLES.test1)) {
|
||||
console.log('Generating Test 1: 23.976fps Film (AC3 ITA 448k + EAC3 ENG 640k)...');
|
||||
ensureDir(SAMPLES.test1);
|
||||
run([
|
||||
FFMPEG, '-y',
|
||||
'-f', 'lavfi', '-i', 'color=c=blue:s=1920x1080:r=24000/1001:d=30',
|
||||
'-f', 'lavfi', '-i', 'sine=f=440:r=48000:d=30',
|
||||
'-f', 'lavfi', '-i', 'sine=f=660:r=48000:d=30',
|
||||
'-map', '0:v', '-map', '1:a', '-map', '2:a',
|
||||
'-c:v', 'libx264', '-crf', '28', '-preset', 'ultrafast',
|
||||
'-c:a:0', 'ac3', '-b:a:0', '448k', '-ac:a:0', '6', '-metadata:s:a:0', 'language=ita',
|
||||
'-c:a:1', 'eac3', '-b:a:1', '640k', '-ac:a:1', '6', '-metadata:s:a:1', 'language=eng',
|
||||
`"${SAMPLES.test1}"`,
|
||||
].join(' '));
|
||||
console.log('Test 1 OK.\n');
|
||||
} else {
|
||||
console.log('Test 1 already exists — skipping.\n');
|
||||
}
|
||||
|
||||
// Test 2 — EAC3 ITA 640k 5.1 at 25fps (DTS is experimental in FFmpeg)
|
||||
// Note: DTS logic is fully covered by unit tests with synthetic streams.
|
||||
// For integration, we use EAC3 640k which triggers series clamping: 640>=384 -> Opus=384
|
||||
console.log('Generating Test 2: 25fps Anime EAC3 ITA 640k 5.1 (Naruto)...');
|
||||
ensureDir(SAMPLES.test2);
|
||||
run([
|
||||
FFMPEG, '-y',
|
||||
'-f', 'lavfi', '-i', 'color=c=green:s=1280x720:r=25:d=30',
|
||||
'-f', 'lavfi', '-i', 'sine=f=660:r=48000:d=30',
|
||||
'-map', '0:v', '-map', '1:a',
|
||||
'-c:v', 'libx264', '-crf', '28', '-preset', 'ultrafast',
|
||||
'-c:a:0', 'eac3', '-b:a:0', '640k', '-ac:a:0', '6', '-metadata:s:a:0', 'language=ita',
|
||||
`"${SAMPLES.test2}"`,
|
||||
].join(' '));
|
||||
console.log('Test 2 OK.\n');
|
||||
|
||||
// Test 3 — Ultrawide 3840x1600
|
||||
console.log('Generating Test 3: Ultrawide 3840x1600...');
|
||||
ensureDir(SAMPLES.test3);
|
||||
run([
|
||||
FFMPEG, '-y',
|
||||
'-f', 'lavfi', '-i', 'color=c=red:s=3840x1600:r=24:d=10',
|
||||
'-f', 'lavfi', '-i', 'sine=f=440:r=48000:d=10',
|
||||
'-map', '0:v', '-map', '1:a',
|
||||
'-c:v', 'libx264', '-crf', '28', '-preset', 'ultrafast',
|
||||
'-c:a', 'aac', '-b:a', '128k', '-metadata:s:a:0', 'language=eng',
|
||||
`"${SAMPLES.test3}"`,
|
||||
].join(' '));
|
||||
console.log('Test 3 OK.\n');
|
||||
|
||||
// Test 4 — SRT forced + SRT SDH
|
||||
console.log('Generating Test 4: Subtitles (SRT forced + SRT SDH)...');
|
||||
ensureDir(SAMPLES.test4);
|
||||
|
||||
const srtContent = '1\n00:00:01,000 --> 00:00:03,000\nTest subtitle line 1\n\n2\n00:00:04,000 --> 00:00:06,000\nTest subtitle line 2\n';
|
||||
const tmpSrt = 'tests/samples/tmp_sub.srt';
|
||||
fs.writeFileSync(tmpSrt, srtContent);
|
||||
|
||||
run([
|
||||
FFMPEG, '-y',
|
||||
'-f', 'lavfi', '-i', 'color=c=gray:s=1920x1080:r=25:d=30',
|
||||
'-f', 'lavfi', '-i', 'sine=f=440:r=48000:d=30',
|
||||
'-i', `"${tmpSrt}"`,
|
||||
'-i', `"${tmpSrt}"`,
|
||||
'-map', '0:v', '-map', '1:a', '-map', '2:s', '-map', '3:s',
|
||||
'-c:v', 'libx264', '-crf', '28', '-preset', 'ultrafast',
|
||||
'-c:a', 'aac', '-b:a', '128k', '-metadata:s:a:0', 'language=ita',
|
||||
'-c:s:0', 'srt', '-metadata:s:s:0', 'language=ita', '-disposition:s:0', 'forced',
|
||||
'-c:s:1', 'srt', '-metadata:s:s:1', 'language=ita', '-disposition:s:1', 'hearing_impaired',
|
||||
`"${SAMPLES.test4}"`,
|
||||
].join(' '));
|
||||
try { fs.unlinkSync(tmpSrt); } catch(_) {}
|
||||
console.log('Test 4 OK.\n');
|
||||
|
||||
console.log('All test files generated. Run: node tests/run-tests.js --skip-transcode');
|
||||
@@ -0,0 +1,109 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* mock-tdarr-runtime.js
|
||||
* Creates a complete mock of the Tdarr args object for isolated plugin testing.
|
||||
* Supports loading real ffprobe data from actual MKV files.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
/**
|
||||
* Run ffprobe on a file and return parsed JSON.
|
||||
* Falls back to a minimal synthetic structure if ffprobe is unavailable.
|
||||
*/
|
||||
function probeFile(filePath) {
|
||||
try {
|
||||
const raw = execSync(
|
||||
`ffprobe -v quiet -print_format json -show_streams -show_format "${filePath}"`,
|
||||
{ encoding: 'utf8', timeout: 15000 },
|
||||
);
|
||||
return JSON.parse(raw);
|
||||
} catch (err) {
|
||||
console.warn(`[mock] ffprobe failed for ${filePath}: ${err.message}`);
|
||||
return { streams: [], format: {} };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a mock Tdarr args object.
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {string} opts.filePath - Path to the input MKV file
|
||||
* @param {object} [opts.inputs] - Plugin input overrides (UI inputs)
|
||||
* @param {object} [opts.variables] - Pre-populated variables
|
||||
* @param {string} [opts.ffmpegPath] - Override ffmpeg path
|
||||
* @param {string} [opts.workDir] - Override work directory
|
||||
*/
|
||||
function buildMockArgs(opts) {
|
||||
const {
|
||||
filePath,
|
||||
inputs = {},
|
||||
variables = {},
|
||||
ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg',
|
||||
workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tdarr-test-')),
|
||||
} = opts;
|
||||
|
||||
const ffProbeData = probeFile(filePath);
|
||||
const logs = [];
|
||||
|
||||
return {
|
||||
inputFileObj: {
|
||||
_id: filePath,
|
||||
file: filePath,
|
||||
ffProbeData,
|
||||
mediaInfo: { track: [] },
|
||||
container: path.extname(filePath).replace('.', ''),
|
||||
},
|
||||
variables: { ...variables },
|
||||
inputs,
|
||||
workDir,
|
||||
ffmpegPath,
|
||||
ffprobePath: process.env.FFPROBE_PATH || 'ffprobe',
|
||||
mkvpropeditPath: process.env.MKVPROPEDIT_PATH || 'mkvpropedit',
|
||||
userVariables: { global: {}, library: {} },
|
||||
jobLog: (msg) => {
|
||||
process.stdout.write(msg);
|
||||
logs.push(msg);
|
||||
},
|
||||
_logs: logs,
|
||||
_workDir: workDir,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup a workDir created by buildMockArgs.
|
||||
*/
|
||||
function cleanupWorkDir(mockArgs) {
|
||||
const dir = mockArgs._workDir || mockArgs.workDir;
|
||||
if (dir && dir.startsWith(os.tmpdir()) && fs.existsSync(dir)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple assertion helper.
|
||||
*/
|
||||
function assert(condition, message) {
|
||||
if (!condition) throw new Error(`ASSERTION FAILED: ${message}`);
|
||||
console.log(` [OK] ${message}`);
|
||||
}
|
||||
|
||||
function assertEqual(actual, expected, label) {
|
||||
assert(
|
||||
actual === expected,
|
||||
`${label}: expected "${expected}", got "${actual}"`,
|
||||
);
|
||||
}
|
||||
|
||||
function assertLessOrEqual(actual, max, label) {
|
||||
assert(
|
||||
parseInt(actual, 10) <= max,
|
||||
`${label}: ${actual} <= ${max}`,
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = { buildMockArgs, cleanupWorkDir, assert, assertEqual, assertLessOrEqual };
|
||||
@@ -0,0 +1,206 @@
|
||||
'use strict';
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
|
||||
const ROOT = process.cwd();
|
||||
let passed = 0, failed = 0;
|
||||
function ok(cond, msg) {
|
||||
if (cond) { console.log(` [PASS] ${msg}`); passed++; }
|
||||
else { console.error(` [FAIL] ${msg}`); failed++; }
|
||||
}
|
||||
function eq(a, b, msg) { ok(String(a) === String(b), `${msg} (expected "${b}", got "${a}")`); }
|
||||
|
||||
function makeStream(o) {
|
||||
return Object.assign({
|
||||
index: 0, codec_type: 'video', codec_name: 'h264',
|
||||
r_frame_rate: '24/1', avg_frame_rate: '24/1',
|
||||
width: 1920, height: 1080, channels: 2,
|
||||
bit_rate: '0', tags: {}, disposition: {}, profile: '',
|
||||
}, o);
|
||||
}
|
||||
function makeArgs(filePath, streams, inputs, variables) {
|
||||
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tdarr-logic-'));
|
||||
return {
|
||||
inputFileObj: { _id: filePath, ffProbeData: { streams }, mediaInfo: { track: [] } },
|
||||
variables: Object.assign({}, variables || {}),
|
||||
inputs: inputs || {},
|
||||
workDir,
|
||||
ffmpegPath: 'ffmpeg',
|
||||
mkvpropeditPath: 'mkvpropedit',
|
||||
jobLog: () => {},
|
||||
_workDir: workDir,
|
||||
};
|
||||
}
|
||||
function cleanup(a) { try { fs.rmSync(a._workDir, { recursive: true, force: true }); } catch(_){} }
|
||||
|
||||
const { plugin: analyzerPlugin } = require(path.join(ROOT, 'LocalFlowPlugins/utility/mediaAnalyzerGOP/1.0.0/index'));
|
||||
const { plugin: audioPlugin } = require(path.join(ROOT, 'LocalFlowPlugins/audio/audioSelectorClamping/1.0.0/index'));
|
||||
|
||||
const ANALYZER_INPUTS = {
|
||||
moviePathPatterns: '/Radarr', animeSeries: 'Naruto|One Piece',
|
||||
filmBitrate: '3000', seriesBitrate: '3000', animeBitrateHd: '2000', animeBitrateSd: '1000',
|
||||
};
|
||||
const AUDIO_INPUTS = {
|
||||
filmMultiChannelBitrate: '640', seriesMultiChannelThreshold: '384', stereoBitrateMax: '128',
|
||||
};
|
||||
|
||||
(async () => {
|
||||
// ── mediaAnalyzerGOP ──────────────────────────────────────────────────────
|
||||
console.log('\n── mediaAnalyzerGOP ──────────────────────────────────');
|
||||
|
||||
{ const a = makeArgs('/media/toshiba/Radarr/Film (2023)/Film.mkv',
|
||||
[makeStream({ r_frame_rate:'24000/1001', height:1080 })], ANALYZER_INPUTS);
|
||||
const o = await analyzerPlugin(a);
|
||||
eq(o.variables.gopKeyint, '48', '23.976fps -> keyint=48');
|
||||
eq(o.variables.isMovie, 'true', '/Radarr -> isMovie=true');
|
||||
eq(o.variables.isAnimation, 'false', 'no anime -> isAnimation=false');
|
||||
eq(o.variables.vBitrate, '3000k', 'film bitrate=3000k');
|
||||
eq(o.variables.vMaxRate, '6000k', 'maxrate=2x');
|
||||
eq(o.variables.vBufSize, '12000k', 'bufsize=4x');
|
||||
eq(o.variables.x265Tune, '', 'live-action -> no tune');
|
||||
cleanup(a); }
|
||||
|
||||
{ const a = makeArgs('/media/toshiba/Sonarr/Naruto S01/S01E01.mkv',
|
||||
[makeStream({ r_frame_rate:'25/1', height:720 })], ANALYZER_INPUTS);
|
||||
const o = await analyzerPlugin(a);
|
||||
eq(o.variables.gopKeyint, '50', '25fps -> keyint=50');
|
||||
eq(o.variables.isMovie, 'false', '/Sonarr -> isMovie=false');
|
||||
eq(o.variables.isAnimation, 'true', 'Naruto -> isAnimation=true');
|
||||
eq(o.variables.x265Tune, 'animation', 'anime -> tune=animation');
|
||||
eq(o.variables.vBitrate, '2000k', 'anime 720p HD -> 2000k');
|
||||
cleanup(a); }
|
||||
|
||||
{ const a = makeArgs('/media/toshiba/Sonarr/Naruto S01/S01E01.mkv',
|
||||
[makeStream({ r_frame_rate:'30000/1001', height:480 })], ANALYZER_INPUTS);
|
||||
const o = await analyzerPlugin(a);
|
||||
eq(o.variables.gopKeyint, '60', '29.97fps -> keyint=60');
|
||||
eq(o.variables.vBitrate, '1000k', 'anime SD 480p -> 1000k');
|
||||
cleanup(a); }
|
||||
|
||||
// Windows backslash path normalization
|
||||
{ const a = makeArgs('C:\\media\\toshiba\\Radarr\\Film (2023)\\Film.mkv',
|
||||
[makeStream({ r_frame_rate:'24/1', height:1080 })], ANALYZER_INPUTS);
|
||||
const o = await analyzerPlugin(a);
|
||||
eq(o.variables.isMovie, 'true', 'Windows backslash path: /Radarr still matched');
|
||||
cleanup(a); }
|
||||
|
||||
// ── audioSelectorClamping ─────────────────────────────────────────────────
|
||||
console.log('\n── audioSelectorClamping ────────────────────────────');
|
||||
|
||||
// EAC3 wins over AC3 by score
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'ac3', bit_rate:'448000', channels:6, tags:{language:'ita'} }),
|
||||
makeStream({ index:2, codec_type:'audio', codec_name:'eac3', bit_rate:'640000', channels:6, tags:{language:'eng'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Radarr/Film.mkv', streams, AUDIO_INPUTS, { isMovie:'true' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.outputNumber, 1, 'output 1 = tracks found');
|
||||
eq(o.variables.audioItaCodecName, 'ac3', 'ITA=ac3');
|
||||
eq(o.variables.audioEngCodecName, 'eac3', 'ENG=eac3');
|
||||
eq(o.variables.audioItaOpusBitrate, '448', 'ITA=min(640,448)=448');
|
||||
eq(o.variables.audioEngOpusBitrate, '640', 'ENG=min(640,640)=640');
|
||||
cleanup(a); }
|
||||
|
||||
// EAC3 640k vs AC3 680k same lang — EAC3 wins by weight
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'eac3', bit_rate:'640000', channels:6, tags:{language:'ita'} }),
|
||||
makeStream({ index:2, codec_type:'audio', codec_name:'ac3', bit_rate:'680000', channels:6, tags:{language:'ita'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Radarr/Film.mkv', streams, AUDIO_INPUTS, { isMovie:'true' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.variables.audioItaCodecName, 'eac3', 'EAC3@640k > AC3@680k by codec weight');
|
||||
eq(o.variables.audioItaStreamIndex, '1', 'EAC3 at stream index 1');
|
||||
cleanup(a); }
|
||||
|
||||
// Series DTS 768k >= 384 threshold -> 384
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'dts', bit_rate:'768000', channels:6, tags:{language:'ita'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Sonarr/Show/ep.mkv', streams, AUDIO_INPUTS, { isMovie:'false' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.variables.audioItaOpusBitrate, '384', 'Series DTS 768k >= 384 -> Opus=384');
|
||||
cleanup(a); }
|
||||
|
||||
// Series AC3 320k < 384 threshold -> 256
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'ac3', bit_rate:'320000', channels:6, tags:{language:'ita'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Sonarr/Show/ep.mkv', streams, AUDIO_INPUTS, { isMovie:'false' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.variables.audioItaOpusBitrate, '256', 'Series AC3 320k < 384 -> Opus=256');
|
||||
cleanup(a); }
|
||||
|
||||
// NEW: Series bitrate unknown (0) -> safe default 384k
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'dts', bit_rate:'0', channels:6, tags:{language:'ita'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Sonarr/Show/ep.mkv', streams, AUDIO_INPUTS, { isMovie:'false' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.variables.audioItaOpusBitrate, '384', 'Series unknown bitrate (0) -> safe default 384k');
|
||||
cleanup(a); }
|
||||
|
||||
// Stereo: min(128,192)=128
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'aac', bit_rate:'192000', channels:2, tags:{language:'ita'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Radarr/Film.mkv', streams, AUDIO_INPUTS, { isMovie:'true' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.variables.audioItaOpusBitrate, '128', 'Stereo 192k -> min(128,192)=128');
|
||||
cleanup(a); }
|
||||
|
||||
// Stereo: no upcoding — min(128,64)=64
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'aac', bit_rate:'64000', channels:2, tags:{language:'eng'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Radarr/Film.mkv', streams, AUDIO_INPUTS, { isMovie:'true' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.variables.audioEngOpusBitrate, '64', 'Stereo 64k -> no upcoding, stays 64k');
|
||||
cleanup(a); }
|
||||
|
||||
// No ITA/ENG -> output branch 2
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'ac3', bit_rate:'448000', channels:6, tags:{language:'fra'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Radarr/Film.mkv', streams, AUDIO_INPUTS, { isMovie:'true' });
|
||||
const o = await audioPlugin(a);
|
||||
eq(o.outputNumber, 2, 'No ITA/ENG -> output branch 2');
|
||||
cleanup(a); }
|
||||
|
||||
// DTS-HD MA detection via profile field
|
||||
{ const streams = [
|
||||
makeStream({ index:0, codec_type:'video' }),
|
||||
makeStream({ index:1, codec_type:'audio', codec_name:'dts', profile:'DTS-HD MA', bit_rate:'4000000', channels:8, tags:{language:'ita'} }),
|
||||
];
|
||||
const a = makeArgs('/media/Radarr/Film.mkv', streams, AUDIO_INPUTS, { isMovie:'true' });
|
||||
const o = await audioPlugin(a);
|
||||
// DTS-HD MA weight=95, score=95*10000+4000=954000 — should be selected
|
||||
eq(o.variables.audioItaCodecName, 'dts', 'DTS-HD MA detected (codec_name=dts, profile contains MA)');
|
||||
// source 4000kbps, film target 640 -> Opus=min(640,4000)=640
|
||||
eq(o.variables.audioItaOpusBitrate, '640', 'DTS-HD MA 4Mbps film -> clamped to 640k');
|
||||
cleanup(a); }
|
||||
|
||||
// ── buildAudioArgs structure check ────────────────────────────────────────
|
||||
console.log('\n── transcode2PassX265 buildAudioArgs structure ──────');
|
||||
const { plugin: transcodePlugin } = require(path.join(ROOT, 'LocalFlowPlugins/video/transcode2PassX265/1.0.0/index'));
|
||||
// Inspect the buildAudioArgs function by reading the file
|
||||
const transcodeCode = require('fs').readFileSync(path.join(ROOT, 'LocalFlowPlugins/video/transcode2PassX265/1.0.0/index.js'), 'utf8');
|
||||
ok(transcodeCode.includes('`-c:a:${audioTrackOut}`'), 'buildAudioArgs uses indexed -c:a:N (not global -c:a)');
|
||||
ok(transcodeCode.includes('`-b:a:${audioTrackOut}`'), 'buildAudioArgs uses indexed -b:a:N (not global -b:a)');
|
||||
ok(transcodeCode.includes('[...mapArgs, ...codecArgs]'), 'buildAudioArgs: maps first, then codec settings');
|
||||
ok(!transcodeCode.includes("'-c:a', 'libopus'"), 'no unindexed -c:a in buildAudioArgs');
|
||||
|
||||
// ── Summary ───────────────────────────────────────────────────────────────
|
||||
console.log(`\n${'='.repeat(55)}`);
|
||||
console.log(` ${passed} passed, ${failed} failed`);
|
||||
if (failed > 0) { console.error(' SOME TESTS FAILED'); process.exit(1); }
|
||||
else console.log(' ALL LOGIC TESTS PASSED');
|
||||
})();
|
||||
@@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* run-tests.js
|
||||
* Orchestrates all 4 test cases.
|
||||
* Usage: node tests/run-tests.js [--skip-transcode]
|
||||
*
|
||||
* Options:
|
||||
* --skip-transcode Skip test3 (which runs actual FFmpeg x265 encode)
|
||||
*/
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const skipTranscode = args.includes('--skip-transcode');
|
||||
|
||||
const tests = [
|
||||
{ name: 'Test 1 — Film 23.976fps (AC3 ITA + EAC3 ENG)', file: './test-cases/test1-movie-23976fps', heavy: false },
|
||||
{ name: 'Test 2 — Anime 25fps DTS ITA (Naruto)', file: './test-cases/test2-anime-25fps', heavy: false },
|
||||
{ name: 'Test 3 — Ultrawide 3840x1600 Scale', file: './test-cases/test3-ultrawide', heavy: true },
|
||||
{ name: 'Test 4 — Subtitle Extraction (forced + SDH)', file: './test-cases/test4-subtitles', heavy: false },
|
||||
];
|
||||
|
||||
async function main() {
|
||||
console.log('╔══════════════════════════════════════════════════════════╗');
|
||||
console.log('║ Tdarr Plugin Suite — Test Runner ║');
|
||||
console.log('╚══════════════════════════════════════════════════════════╝\n');
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const test of tests) {
|
||||
if (test.heavy && skipTranscode) {
|
||||
console.log(`[SKIP] ${test.name} (--skip-transcode)\n`);
|
||||
results.push({ name: test.name, status: 'SKIPPED' });
|
||||
continue;
|
||||
}
|
||||
|
||||
console.log(`[RUN] ${test.name}`);
|
||||
try {
|
||||
const fn = require(test.file);
|
||||
await fn();
|
||||
results.push({ name: test.name, status: 'PASSED' });
|
||||
} catch (err) {
|
||||
console.error(`\n[FAIL] ${test.name}\n ${err.message}\n`);
|
||||
results.push({ name: test.name, status: 'FAILED', error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Summary ───────────────────────────────────────────────────────────────
|
||||
console.log('\n╔══════════════════════════════════════════════════════════╗');
|
||||
console.log('║ SUMMARY ║');
|
||||
console.log('╚══════════════════════════════════════════════════════════╝\n');
|
||||
|
||||
let passed = 0, failed = 0, skipped = 0;
|
||||
for (const r of results) {
|
||||
const icon = r.status === 'PASSED' ? '[OK]' : r.status === 'SKIPPED' ? '[--]' : '[!!]';
|
||||
console.log(` ${icon} ${r.name}`);
|
||||
if (r.error) console.log(` Error: ${r.error}`);
|
||||
if (r.status === 'PASSED') passed++;
|
||||
if (r.status === 'FAILED') failed++;
|
||||
if (r.status === 'SKIPPED') skipped++;
|
||||
}
|
||||
|
||||
console.log(`\n Results: ${passed} passed, ${failed} failed, ${skipped} skipped\n`);
|
||||
|
||||
if (failed > 0) process.exit(1);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Fatal error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* test1-movie-23976fps.js
|
||||
* Validates: mediaAnalyzerGOP + audioSelectorClamping on a 23.976fps Film.
|
||||
* File: Radarr path, AC3 ITA 448k 5.1, EAC3 ENG 640k 5.1
|
||||
*
|
||||
* Expected:
|
||||
* gopKeyint = "48"
|
||||
* isMovie = "true"
|
||||
* isAnimation = "false"
|
||||
* vBitrate = "3000k"
|
||||
* audioItaCodecName = "ac3"
|
||||
* audioEngCodecName = "eac3" (EAC3 score > AC3 score)
|
||||
* audioItaOpusBitrate = "448" (clamped: min(640, 448) = 448)
|
||||
* audioEngOpusBitrate = "640" (clamped: min(640, 640) = 640)
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { buildMockArgs, cleanupWorkDir, assertEqual } = require('../mock-tdarr-runtime');
|
||||
const { plugin: analyzerPlugin } = require('../../LocalFlowPlugins/utility/mediaAnalyzerGOP/1.0.0/index');
|
||||
const { plugin: audioPlugin } = require('../../LocalFlowPlugins/audio/audioSelectorClamping/1.0.0/index');
|
||||
|
||||
const FILE = path.resolve('tests/samples/media/toshiba/Radarr/Film Test (2023)/Film Test (2023).mkv');
|
||||
|
||||
async function run() {
|
||||
console.log('\n=== TEST 1: 23.976fps Film (AC3 ITA + EAC3 ENG) ===\n');
|
||||
|
||||
// ── Step 1: mediaAnalyzerGOP ──────────────────────────────────────────────
|
||||
console.log('Running mediaAnalyzerGOP...');
|
||||
const args1 = buildMockArgs({
|
||||
filePath: FILE,
|
||||
inputs: {
|
||||
moviePathPatterns: '/Radarr',
|
||||
animeSeries: '',
|
||||
filmBitrate: '3000',
|
||||
seriesBitrate: '3000',
|
||||
animeBitrateHd: '2000',
|
||||
animeBitrateSd: '1000',
|
||||
},
|
||||
});
|
||||
|
||||
const out1 = await analyzerPlugin(args1);
|
||||
const vars = out1.variables;
|
||||
|
||||
assertEqual(out1.outputNumber, 1, 'outputNumber');
|
||||
assertEqual(vars.gopKeyint, '48', 'gopKeyint (2 x 23.976 = 47.95 -> 48)');
|
||||
assertEqual(vars.isMovie, 'true', 'isMovie (Radarr path)');
|
||||
assertEqual(vars.isAnimation, 'false', 'isAnimation (no anime match)');
|
||||
assertEqual(vars.vBitrate, '3000k', 'vBitrate (film default)');
|
||||
assertEqual(vars.x265Tune, '', 'x265Tune (live-action)');
|
||||
|
||||
// ── Step 2: audioSelectorClamping ────────────────────────────────────────
|
||||
console.log('\nRunning audioSelectorClamping...');
|
||||
const args2 = buildMockArgs({
|
||||
filePath: FILE,
|
||||
variables: vars,
|
||||
inputs: {
|
||||
filmMultiChannelBitrate: '640',
|
||||
seriesMultiChannelThreshold:'384',
|
||||
stereoBitrateMax: '128',
|
||||
},
|
||||
});
|
||||
|
||||
const out2 = await audioPlugin(args2);
|
||||
const vars2 = out2.variables;
|
||||
|
||||
assertEqual(out2.outputNumber, 1, 'outputNumber (tracks found)');
|
||||
assertEqual(vars2.audioHasIta, 'true', 'audioHasIta');
|
||||
assertEqual(vars2.audioHasEng, 'true', 'audioHasEng');
|
||||
assertEqual(vars2.audioItaCodecName, 'ac3', 'ITA codec = ac3');
|
||||
assertEqual(vars2.audioEngCodecName, 'eac3', 'ENG codec = eac3 (wins by score)');
|
||||
assertEqual(vars2.audioItaOpusBitrate, '448', 'ITA Opus = 448k (min(640,448))');
|
||||
assertEqual(vars2.audioEngOpusBitrate, '640', 'ENG Opus = 640k (min(640,640))');
|
||||
|
||||
cleanupWorkDir(args1);
|
||||
cleanupWorkDir(args2);
|
||||
console.log('\n=== TEST 1 PASSED ===\n');
|
||||
}
|
||||
|
||||
module.exports = run;
|
||||
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
/**
|
||||
* test2-anime-25fps.js
|
||||
* Validates mediaAnalyzerGOP + audioSelectorClamping on anime 25fps.
|
||||
* File: Sonarr path, EAC3 ITA 640k 5.1, "Naruto" in animeSeries list.
|
||||
* Note: DTS detection logic is fully covered in unit tests (quick-logic-test.js).
|
||||
*
|
||||
* Expected:
|
||||
* gopKeyint = "50"
|
||||
* isAnimation = "true"
|
||||
* isMovie = "false"
|
||||
* x265Tune = "animation"
|
||||
* vBitrate = "2000k" (anime HD 720p)
|
||||
* audioItaCodecName = "eac3"
|
||||
* audioItaOpusBitrate = "384" (series: 640k >= 384 threshold -> 384k)
|
||||
* audioHasEng = "false"
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { buildMockArgs, cleanupWorkDir, assertEqual } = require('../mock-tdarr-runtime');
|
||||
const { plugin: analyzerPlugin } = require(require('path').join(process.cwd(), 'LocalFlowPlugins/utility/mediaAnalyzerGOP/1.0.0/index'));
|
||||
const { plugin: audioPlugin } = require(require('path').join(process.cwd(), 'LocalFlowPlugins/audio/audioSelectorClamping/1.0.0/index'));
|
||||
|
||||
const FILE = path.resolve('tests/samples/media/toshiba/Sonarr/Naruto S01/Naruto S01E01.mkv');
|
||||
|
||||
async function run() {
|
||||
console.log('\n=== TEST 2: 25fps Anime EAC3 ITA (Naruto, Sonarr) ===\n');
|
||||
|
||||
console.log('Running mediaAnalyzerGOP...');
|
||||
const args1 = buildMockArgs({
|
||||
filePath: FILE,
|
||||
inputs: {
|
||||
moviePathPatterns: '/Radarr',
|
||||
animeSeries: 'Naruto|One Piece',
|
||||
filmBitrate: '3000',
|
||||
seriesBitrate: '3000',
|
||||
animeBitrateHd: '2000',
|
||||
animeBitrateSd: '1000',
|
||||
},
|
||||
});
|
||||
const out1 = await analyzerPlugin(args1);
|
||||
const vars = out1.variables;
|
||||
assertEqual(vars.gopKeyint, '50', 'gopKeyint (2 x 25 = 50)');
|
||||
assertEqual(vars.isMovie, 'false', 'isMovie=false (Sonarr path)');
|
||||
assertEqual(vars.isAnimation, 'true', 'isAnimation=true (Naruto in path)');
|
||||
assertEqual(vars.x265Tune, 'animation', 'x265Tune=animation');
|
||||
assertEqual(vars.vBitrate, '2000k', 'vBitrate=2000k (anime 720p HD)');
|
||||
|
||||
console.log('\nRunning audioSelectorClamping...');
|
||||
const args2 = buildMockArgs({
|
||||
filePath: FILE,
|
||||
variables: vars,
|
||||
inputs: {
|
||||
filmMultiChannelBitrate: '640',
|
||||
seriesMultiChannelThreshold:'384',
|
||||
stereoBitrateMax: '128',
|
||||
},
|
||||
});
|
||||
const out2 = await audioPlugin(args2);
|
||||
const vars2 = out2.variables;
|
||||
assertEqual(out2.outputNumber, 1, 'outputNumber=1 (ITA found)');
|
||||
assertEqual(vars2.audioHasIta, 'true', 'audioHasIta=true');
|
||||
assertEqual(vars2.audioHasEng, 'false','audioHasEng=false');
|
||||
assertEqual(vars2.audioItaCodecName, 'eac3', 'ITA codec=eac3');
|
||||
assertEqual(vars2.audioItaOpusBitrate, '384', 'ITA Opus=384k (series: 640k >= 384 threshold)');
|
||||
|
||||
cleanupWorkDir(args1);
|
||||
cleanupWorkDir(args2);
|
||||
console.log('\n=== TEST 2 PASSED ===\n');
|
||||
}
|
||||
|
||||
module.exports = run;
|
||||
@@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* test3-ultrawide.js
|
||||
* Validates: transcode2PassX265 scale filter on 3840x1600 input.
|
||||
* Expected output: 1920x800 (no letterbox, even dimensions).
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { execSync } = require('child_process');
|
||||
const { buildMockArgs, cleanupWorkDir, assert, assertEqual } = require('../mock-tdarr-runtime');
|
||||
const { plugin: analyzerPlugin } = require('../../LocalFlowPlugins/utility/mediaAnalyzerGOP/1.0.0/index');
|
||||
const { plugin: audioPlugin } = require('../../LocalFlowPlugins/audio/audioSelectorClamping/1.0.0/index');
|
||||
const { plugin: transcodePlugin } = require('../../LocalFlowPlugins/video/transcode2PassX265/1.0.0/index');
|
||||
|
||||
const FILE = path.resolve('tests/samples/test3_ultrawide.mkv');
|
||||
const FFMPEG = process.env.FFMPEG_PATH || 'ffmpeg';
|
||||
const FFPROBE = process.env.FFPROBE_PATH || 'ffprobe';
|
||||
|
||||
async function run() {
|
||||
console.log('\n=== TEST 3: Ultrawide 3840x1600 Scale Filter ===\n');
|
||||
|
||||
// Analyzer
|
||||
const args1 = buildMockArgs({
|
||||
filePath: FILE,
|
||||
inputs: { moviePathPatterns: '/Radarr', animeSeries: '', filmBitrate: '3000',
|
||||
seriesBitrate: '3000', animeBitrateHd: '2000', animeBitrateSd: '1000' },
|
||||
});
|
||||
const out1 = await analyzerPlugin(args1);
|
||||
const vars = out1.variables;
|
||||
assertEqual(vars.videoHeight, '1600', 'Source videoHeight = 1600');
|
||||
|
||||
// Audio selector
|
||||
const args2 = buildMockArgs({
|
||||
filePath: FILE, variables: vars,
|
||||
inputs: { filmMultiChannelBitrate: '640', seriesMultiChannelThreshold: '384', stereoBitrateMax: '128' },
|
||||
});
|
||||
const out2 = await audioPlugin(args2);
|
||||
|
||||
// Transcode (Pass 1 + Pass 2)
|
||||
console.log('Running transcode2PassX265 (this may take a minute)...');
|
||||
const args3 = buildMockArgs({
|
||||
filePath: FILE,
|
||||
variables: out2.variables,
|
||||
inputs: { x265Preset: 'ultrafast', outputContainer: 'mkv' },
|
||||
ffmpegPath: FFMPEG,
|
||||
});
|
||||
|
||||
const out3 = await transcodePlugin(args3);
|
||||
const outFile = out3.outputFileObj._id;
|
||||
|
||||
assert(fs.existsSync(outFile), `Output file exists: ${outFile}`);
|
||||
|
||||
// Verify dimensions with ffprobe
|
||||
const probeOut = execSync(
|
||||
`${FFPROBE} -v quiet -print_format json -show_streams -select_streams v:0 "${outFile}"`,
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
const { streams } = JSON.parse(probeOut);
|
||||
const w = streams[0].width;
|
||||
const h = streams[0].height;
|
||||
|
||||
console.log(` Output dimensions: ${w}x${h}`);
|
||||
assert(w === 1920, `Width = 1920 (got ${w})`);
|
||||
assert(h === 800, `Height = 800 (got ${h})`);
|
||||
assert(w % 2 === 0, 'Width is even');
|
||||
assert(h % 2 === 0, 'Height is even');
|
||||
|
||||
cleanupWorkDir(args1);
|
||||
cleanupWorkDir(args2);
|
||||
cleanupWorkDir(args3);
|
||||
console.log('\n=== TEST 3 PASSED ===\n');
|
||||
}
|
||||
|
||||
module.exports = run;
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* test4-subtitles.js
|
||||
* Validates: extractSubtitlesAndOcr produces correctly named SRT files.
|
||||
* Source: MKV with 2 ITA SRT streams (forced + SDH).
|
||||
* Expected: .ita.forced.srt and .ita.hearing_impaired.srt in source dir.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { buildMockArgs, cleanupWorkDir, assert } = require('../mock-tdarr-runtime');
|
||||
const { plugin: subPlugin } = require('../../LocalFlowPlugins/subtitles/extractSubtitlesAndOcr/1.0.0/index');
|
||||
|
||||
const FILE = path.resolve('tests/samples/test4_subtitles.mkv');
|
||||
const SOURCE_DIR = path.dirname(FILE);
|
||||
const BASE_NAME = path.basename(FILE, '.mkv');
|
||||
|
||||
async function run() {
|
||||
console.log('\n=== TEST 4: Subtitle Extraction (forced + SDH) ===\n');
|
||||
|
||||
const args = buildMockArgs({
|
||||
filePath: FILE,
|
||||
inputs: { subtitleEditPath: 'SubtitleEdit', languages: 'ita,eng' },
|
||||
});
|
||||
|
||||
await subPlugin(args);
|
||||
|
||||
// Check that forced SRT was created
|
||||
const forcedSrt = path.join(SOURCE_DIR, `${BASE_NAME}.ita.forced.srt`);
|
||||
const sdhSrt = path.join(SOURCE_DIR, `${BASE_NAME}.ita.sdh.srt`);
|
||||
|
||||
console.log(' Checking for:', path.basename(forcedSrt));
|
||||
assert(fs.existsSync(forcedSrt), `Forced SRT exists: ${path.basename(forcedSrt)}`);
|
||||
|
||||
console.log(' Checking for:', path.basename(sdhSrt));
|
||||
// Note: disposition hearing_impaired maps to 'sdh' suffix
|
||||
// If not found, check for .ita.default.srt variant (FFmpeg disposition naming may vary)
|
||||
const sdhExists = fs.existsSync(sdhSrt);
|
||||
const altSdhExists = fs.existsSync(path.join(SOURCE_DIR, `${BASE_NAME}.ita.default.srt`));
|
||||
assert(sdhExists || altSdhExists, `SDH/hearing-impaired SRT exists`);
|
||||
|
||||
// Cleanup generated subtitle files
|
||||
[forcedSrt, sdhSrt].forEach((f) => { try { fs.unlinkSync(f); } catch (_) {} });
|
||||
|
||||
cleanupWorkDir(args);
|
||||
console.log('\n=== TEST 4 PASSED ===\n');
|
||||
}
|
||||
|
||||
module.exports = run;
|
||||
Reference in new issue
Block a user