From b4ec978bf723a9cdb262e81584a6efc982f711c2 Mon Sep 17 00:00:00 2001 From: xmutantson Date: Fri, 2 Oct 2026 09:43:01 -0700 Subject: [PATCH 1/2] Make batch transcoding safe to resume and report failures accurately --- .gitattributes | 3 + .gitignore | 2 + README.md | 143 ++++++++-- tests/test_vidprocess.py | 283 +++++++++++++++++++ vidprocess.sh | 585 +++++++++++++++++---------------------- 5 files changed, 663 insertions(+), 353 deletions(-) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 tests/test_vidprocess.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d3f6ef6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +*.sh text eol=lf +*.py text eol=lf +*.md text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..43ae0e2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.py[cod] diff --git a/README.md b/README.md index e7d90bc..e530746 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,132 @@ -This repository contains a script that was painstakingly developed to automate and batch process ffmpeg jobs across various servers. There are many ways to formulate an ffmpeg command, this example rescales a letterboxed image captured in a 1920x1080 frame to 640x480. The script first defines all of the functions, then calls them all in sequence. This is needed later to repeat a run if for some reason the process misses some files. +# FFmpeg batch processing -The following assumptions are made about this script: +Transcode videos locally or across SSH workers sharing storage. The default +preset preserves this project's original use case: crop a specific letterboxed +1920×1080 capture to `1584:1072:158:6`, then scale to 640×480. Outputs use H.264 +(`libx264`, medium, CRF 23) and AAC (48 kHz, stereo, 128 kb/s) in MP4 containers. +For other source dimensions, choose a suitable `--filter`. -* There are 3 servers available over SSH -* All SSH sessions are using the same username and passwordless auth (pubkey in my case) -* Those servers all have the working directory mounted in the same place. I used a network share. -* Each server has r/w access to the working directory -* One of the processing servers is localhost -* All servers are of the same capability, can handle the same concurrency level (10 is used here, each of my servers has 56 threads) -* All servers have ffmpeg installed and available - +## Requirements -The script wil create: -* Temprary files in the working directory. Read the code for more info, all of them clean themselves up -* error_log.txt (used to collect ffmpeg errors/failures to read file) - +- Bash 4.4 or newer, GNU core utilities and GNU find, including `realpath`, + `sha256sum`, `mktemp`, and `ln -T`. +- FFmpeg with the `libx264` and AAC encoders on every worker. +- An output filesystem supporting hard links. This allows atomic publication + without replacing an existing destination. Preflight fails if hard links are + unavailable; there is no overwrite fallback. +- Remote workers need SSH public-key authentication, a POSIX login shell, and + the **same absolute input/output paths on shared storage**. Preflight checks a + unique shared run token and write access. The script is sent over SSH stdin; + no remote script installation is required. -Don't worry about: +The offline suite has been exercised with Git Bash 5.2 on Windows. GNU/Linux is +the intended deployment environment; check actual SSH/shared-storage behavior +on a small sample before scheduling a large batch. -* wait: no such job (means processing exited some time before wait was called. Job is successful though -* Evenly splitting files: The script splits on number of files, not size of files. This can mean that things are a teensy bit skewed towards one server or another. If you want everything to be exactly the same, feel free. It doesn't make much of a difference in my case and I was lazy so I didn't handle the file sizes and split that way. +## Start locally +```bash +# Inspect the plan: no writes, encodes, or SSH connections. +bash vidprocess.sh --input /media/captures --dry-run + +# Default: localhost, two concurrent jobs, no automatic retries. +bash vidprocess.sh --input /media/captures + +# Separate output root and one extra attempt per failed job. +bash vidprocess.sh --input /media/captures --output /media/converted \ + --jobs 4 --retries 1 + +# Material that does not need the original crop. +bash vidprocess.sh --input /media/captures --filter 'scale=640:-2' +``` + +`--help` lists all options. Zero matching files is a successful no-op. Discovery +is recursive, case-insensitive for supported extensions, NUL-delimited, and does +not follow directory symlinks. The selected output tree is excluded. Launch the +script from any working directory. + +Outputs preserve relative source paths and **append `.mp4` to the full filename**: + +| Input relative path | Output relative path | +| --- | --- | +| `camera-a/clip.mov` | `camera-a/clip.mov.mp4` | +| `camera-b/clip.mov` | `camera-b/clip.mov.mp4` | +| `camera-a/clip.mp4` | `camera-a/clip.mp4.mp4` | + +The default output is `INPUT/transcoded`. Input/output cannot be filesystem root, +and output cannot equal or contain input. `.vidprocess` is reserved at the output +root; source files beneath an input `.vidprocess` subtree are rejected because +their mapped destinations would collide with this state namespace. + +## Shared-storage workers + +```bash +bash vidprocess.sh --input /mnt/shared/captures \ + --host localhost --host encode-a --host encode-b --user media --jobs 2 +``` + +Each `--host` adds a worker with `--jobs` slots. This single list drives assignment, +including small batches. If no hosts are specified, only localhost is used. +Omit `--user` to use SSH's configured username. SSH uses batch mode and a +ten-second connection timeout. Concurrency limits FFmpeg processes, not their +internal threads. Scheduling uses bounded round-robin slots, not duration balancing. + +## Results and recovery + +Reports separate successful, verified-skipped, and failed jobs. Exit status is +`0` for a completed run without failures, `1` for failed jobs, `2` for configuration +or preflight errors, and `130` for handled interruption. No retry prompt requires +interactive input. + +State is retained under `OUTPUT/.vidprocess`: + +- `runs/run.*/files.nul`: exact input snapshot, NUL-delimited. +- `runs/run.*/manifest.tsv`: job ID, shell-escaped source/destination, and host. +- `runs/run.*/*.log`: stdout/stderr for each job attempt. +- `runs/run.*/*.result`: final job status. +- `runs/run.*/retry.nul`: failed paths after a completed run, if any. +- `receipts/`: source/preset and output-content verification hashes. +- `lock` and `locks/`: coordinator and individual-output reservations. + +Resume by rerunning the same command. An output is skipped only when its receipt +matches source contents, filter/preset, and current output contents. Failed or +unfinished files are attempted again, with additional attempts controlled by +`--retries`. Logs and manifests remain available after the run. Remove old run +directories manually only when no workers use them; keep receipts for future +verified skipping. + +Verification reads entire source and output files. Successful encoding also +checks the source again before publication to detect changes during processing. +This adds disk/network I/O. Keep source media stable while processing it. + +**Existing output conflicts are preserved and reported as failures.** This +includes files without matching receipts, modified files, and files made with a +different filter. Choose a new output root or move a conflicting output aside +after inspecting it; there is no overwrite flag. A crash between output and +receipt publication can leave a complete file without a receipt. It is +deliberately treated as a conflict: inspect it and move it aside or choose a new +output root before retrying. + +Unique partial files are created beside the final destination. Handled local +cancellation stops active encoders and removes owned partials/reservations while +retaining logs/manifests. SSH disconnection cannot guarantee remote process +termination. Confirm remote jobs have stopped before removing stale locks. +After an unhandled crash or machine failure, inspect worker processes and run +records before manually removing stale reservations or abandoned +`.vidprocess.*.mp4` partials. The script never recursively deletes the working +directory or clears previous run logs. + +## Offline regression tests + +```bash +python -m unittest discover -s tests -v +bash -n vidprocess.sh +``` + +Tests require Python 3.10+ and use temporary fixtures with local FFmpeg/SSH stubs; +they never contact remote hosts. Set `BASH_EXE` if needed (Windows defaults to the +standard Git Bash installation). Coverage includes zero-to-ten-file batches, +duplicate names, verified reruns, changed inputs/outputs, overwrite refusal, +bounded retries, empty/failed encodes, remote quoting/failures, cancellation, +and dry-run behavior. Newline filenames are skipped on Windows because its +filesystem forbids them. diff --git a/tests/test_vidprocess.py b/tests/test_vidprocess.py new file mode 100644 index 0000000..936df0e --- /dev/null +++ b/tests/test_vidprocess.py @@ -0,0 +1,283 @@ +"""Offline integration tests; ffmpeg and ssh are always temporary local stubs.""" +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +BASH = os.environ.get("BASH_EXE") or ( + r"C:\Program Files\Git\bin\bash.exe" if os.name == "nt" else shutil.which("bash") +) + + +def shell_path(path): + value = Path(path).resolve().as_posix() + if os.name == "nt": + return "/" + value[0].lower() + value[2:] + return value + + +ENCODER = r'''#!/usr/bin/env bash +set -eu +source='' +while (( $# )); do + if [[ $1 == -i ]]; then source=$2; shift 2; else output=$1; shift; fi +done +printf '%s\0' "$source" >> "$TEST_CALLS" +trap 'printf stopped > "$TEST_STOPPED"; exit 143' TERM +if [[ ${TEST_CANCEL:-0} == 1 ]]; then + touch "$TEST_READY" + while :; do sleep 0.05; done +fi +if [[ ${TEST_FAIL:-} == all || ( ${TEST_FAIL:-} == bad && $source == */bad.mp4 ) ]]; then + printf 'partial' > "$output" + echo 'synthetic encoder failure' >&2 + exit 9 +fi +if [[ ${TEST_FAIL_ONCE:-0} == 1 && ! -f "$TEST_ONCE" ]]; then + touch "$TEST_ONCE" + echo 'synthetic transient failure' >&2 + exit 9 +fi +if [[ ${TEST_EMPTY:-0} == 1 ]]; then : > "$output"; exit 0; fi +if [[ ${TEST_SLEEP:-0} != 0 ]]; then sleep "$TEST_SLEEP"; fi +printf 'encoded:' > "$output" +cat -- "$source" >> "$output" +''' + +SSH = r'''#!/usr/bin/env bash +set -eu +printf 'ssh\n' >> "$TEST_SSH_CALLS" +[[ ${TEST_SSH_FAIL:-0} != 1 ]] || exit 255 +if [[ ${TEST_SSH_WORKER_FAIL:-0} == 1 && $6 == *--internal-worker* ]]; then exit 255; fi +# Parse only the script's fixed options; never call an actual SSH executable. +[[ $1 == -o && $2 == BatchMode=yes && $3 == -o && $4 == ConnectTimeout=10 ]] || exit 88 +[[ $5 == "${TEST_EXPECT_TARGET:-worker}" ]] || exit 89 +exec bash -c "$6" +''' + + +class BatchTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="batch test '") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + self.inputs = self.base / "input files" + self.inputs.mkdir() + self.output = self.inputs / "transcoded" + self.bin = self.base / "bin" + self.bin.mkdir() + for name, source in (("ffmpeg", ENCODER), ("ssh", SSH)): + path = self.bin / name + path.write_text(source, encoding="utf-8", newline="\n") + path.chmod(0o755) + self.calls = self.base / "calls" + self.ssh_calls = self.base / "ssh-calls" + self.env = dict(os.environ, TEST_CALLS=shell_path(self.calls), + TEST_SSH_CALLS=shell_path(self.ssh_calls), + TEST_READY=shell_path(self.base / "ready"), + TEST_STOPPED=shell_path(self.base / "stopped"), + TEST_ONCE=shell_path(self.base / "once")) + + def add(self, name, content="media"): + path = self.inputs / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + return path + + def run_batch(self, *args, **environment): + env = dict(self.env, **environment) + command = [BASH, "-c", 'export PATH="$1:/usr/bin:/bin:$PATH"; shift; exec bash "$@"', + "test", shell_path(self.bin), shell_path(ROOT / "vidprocess.sh"), + "--input", shell_path(self.inputs), "--jobs", "2", *args] + return subprocess.run(command, env=env, cwd=self.base, capture_output=True, + text=True, timeout=30) + + def count_calls(self): + return self.calls.read_bytes().count(b"\0") if self.calls.exists() else 0 + + def assert_ok(self, result): + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_zero_through_ten_inputs_assigned_once(self): + for count in range(11): + with self.subTest(count=count): + self.inputs = self.base / str(count) + self.inputs.mkdir() + self.output = self.inputs / "transcoded" + before = self.count_calls() + for i in range(count): + self.add(f"clip{i}.mp4") + result = self.run_batch("--host", "localhost", "--host", "localhost", "--host", "localhost") + self.assert_ok(result) + self.assertEqual(self.count_calls() - before, count) + self.assertEqual(len(list(self.output.rglob("*.mp4"))), count) + + def test_duplicate_names_and_mixed_extensions(self): + for name in ("a/clip.mp4", "b/clip.mp4", "a/clip.mov"): + self.add(name, name) + self.assert_ok(self.run_batch()) + for name in ("a/clip.mp4", "b/clip.mp4", "a/clip.mov"): + self.assertEqual((self.output / (name + ".mp4")).read_text(), "encoded:" + name) + + def test_verified_rerun_skips_and_excludes_output_tree(self): + self.add("one.MP4") + self.assert_ok(self.run_batch()) + result = self.run_batch() + self.assert_ok(result) + self.assertIn("requested=1 success=0 skipped=1 failed=0", result.stdout) + self.assertEqual(self.count_calls(), 1) + + def test_unrelated_existing_output_is_preserved(self): + self.add("one.mp4") + self.output.mkdir() + target = self.output / "one.mp4.mp4" + target.write_text("keep me") + result = self.run_batch() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertEqual(target.read_text(), "keep me") + self.assertEqual(self.count_calls(), 0) + + def test_changed_input_or_output_is_not_silently_skipped(self): + source = self.add("one.mp4", "original") + self.assert_ok(self.run_batch()) + target = self.output / "one.mp4.mp4" + original = target.read_text() + source.write_text("changed") + self.assertEqual(self.run_batch().returncode, 1) + self.assertEqual(target.read_text(), original) + source.write_text("original") + target.write_text("modified output") + self.assertEqual(self.run_batch().returncode, 1) + self.assertEqual(target.read_text(), "modified output") + + def test_failure_is_not_success_and_logs_survive(self): + self.add("good.mp4") + bad = self.add("bad.mp4") + result = self.run_batch(TEST_FAIL="bad") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("success=1 skipped=0 failed=1", result.stdout) + self.assertFalse((self.output / "bad.mp4.mp4").exists()) + runs = list((self.output / ".vidprocess/runs").iterdir()) + self.assertEqual((runs[0] / "retry.nul").read_bytes(), shell_path(bad).encode() + b"\0") + self.assertTrue(any("synthetic encoder failure" in p.read_text() for p in runs[0].glob("*.log"))) + self.assertFalse(list(self.output.rglob(".vidprocess.*.mp4"))) + self.assert_ok(self.run_batch()) + self.assertEqual(self.count_calls(), 3) + + def test_single_file_bounded_retry(self): + self.add("one.mp4") + result = self.run_batch("--retries", "1", TEST_FAIL_ONCE="1") + self.assert_ok(result) + self.assertEqual(self.count_calls(), 2) + self.assertIn("success=1 skipped=0 failed=0", result.stdout) + + def test_permanent_failure_exhausts_retries(self): + self.add("one.mp4") + self.assertEqual(self.run_batch("--retries", "2", TEST_FAIL="all").returncode, 1) + self.assertEqual(self.count_calls(), 3) + + def test_empty_encoder_output_is_failure(self): + self.add("one.mp4") + self.assertEqual(self.run_batch(TEST_EMPTY="1").returncode, 1) + self.assertFalse((self.output / "one.mp4.mp4").exists()) + + def test_dry_run_is_read_only_and_does_not_connect(self): + self.add("one.mp4") + self.assert_ok(self.run_batch("--dry-run", "--host", "worker")) + self.assertFalse(self.output.exists()) + self.assertEqual(self.count_calls(), 0) + self.assertFalse(self.ssh_calls.exists()) + + def test_remote_stub_handles_spaces_apostrophes_and_username(self): + self.add("Bob's clip.MOV") + result = self.run_batch("--host", "worker", "--user", "media", TEST_EXPECT_TARGET="media@worker") + self.assert_ok(result) + self.assertEqual(self.count_calls(), 1) + self.assertEqual(self.ssh_calls.read_text().count("ssh"), 2) + + @unittest.skipIf(os.name == "nt", "Windows filesystem forbids newline filenames") + def test_newline_filename(self): + self.add("line\nbreak.mp4") + self.assert_ok(self.run_batch()) + self.assertTrue((self.output / "line\nbreak.mp4.mp4").exists()) + + def test_remote_preflight_failure_does_not_encode(self): + self.add("one.mp4") + result = self.run_batch("--host", "worker", TEST_SSH_FAIL="1") + self.assertEqual(result.returncode, 2) + self.assertEqual(self.count_calls(), 0) + + def test_remote_worker_failure_is_reported(self): + self.add("one.mp4") + result = self.run_batch("--host", "worker", TEST_SSH_WORKER_FAIL="1") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("success=0 skipped=0 failed=1", result.stdout) + self.assertEqual(self.count_calls(), 0) + + def test_brackets_in_output_path_are_pruned_on_rerun(self): + self.add("one.mp4") + output = self.inputs / "converted [2026]" + self.assert_ok(self.run_batch("--output", shell_path(output))) + result = self.run_batch("--output", shell_path(output)) + self.assert_ok(result) + self.assertIn("requested=1 success=0 skipped=1 failed=0", result.stdout) + self.assertEqual(self.count_calls(), 1) + + def test_term_stops_local_encoder_and_preserves_retry_state(self): + self.add("one.mp4") + wrapper = '''export PATH="$1:/usr/bin:/bin:$PATH"; shift +bash "$@" & batch=$! +for ((i=0;i<200;i++)); do + [[ ! -f "$TEST_READY" ]] || break + sleep 0.05 +done +[[ -f "$TEST_READY" ]] || { kill -TERM "$batch"; wait "$batch"; exit 99; } +kill -TERM "$batch" +wait "$batch" +''' + result = subprocess.run([BASH, "-c", wrapper, "cancel-test", shell_path(self.bin), + shell_path(ROOT / "vidprocess.sh"), "--input", shell_path(self.inputs)], + env=dict(self.env, TEST_CANCEL="1"), cwd=self.base, + capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, 130, result.stdout + result.stderr) + self.assertTrue((self.base / "stopped").exists()) + self.assertFalse((self.output / "one.mp4.mp4").exists()) + self.assertFalse((self.output / ".vidprocess/lock").exists()) + self.assertFalse(list((self.output / ".vidprocess/locks").iterdir())) + self.assertFalse(list(self.output.rglob(".vidprocess.*.mp4"))) + self.assertTrue(list((self.output / ".vidprocess/runs").glob("*/files.nul"))) + self.assert_ok(self.run_batch()) + + def test_existing_lock_is_preserved(self): + self.add("one.mp4") + lock = self.output / ".vidprocess/lock" + lock.mkdir(parents=True) + self.assertEqual(self.run_batch().returncode, 2) + self.assertTrue(lock.exists()) + self.assertEqual(self.count_calls(), 0) + + def test_reserved_state_namespace_is_rejected(self): + self.add(".vidprocess/lock/one.mp4") + result = self.run_batch() + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn("reserved output state", result.stderr) + self.assertEqual(self.count_calls(), 0) + self.assertFalse((self.output / ".vidprocess/lock").exists()) + + def test_input_and_output_overlap_is_rejected(self): + self.add("one.mp4") + self.assertEqual(self.run_batch("--output", shell_path(self.inputs)).returncode, 2) + self.assertEqual(self.run_batch("--output", shell_path(self.base)).returncode, 2) + + def test_invalid_options(self): + for args in (("--jobs", "0"), ("--retries", "-1"), ("--host", "-bad"), ("--input",)): + with self.subTest(args=args): + self.assertEqual(self.run_batch(*args).returncode, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/vidprocess.sh b/vidprocess.sh index 2344ed9..9366ac0 100644 --- a/vidprocess.sh +++ b/vidprocess.sh @@ -1,359 +1,272 @@ -#!/bin/bash - -# Define the directory to search for video files -directory="/YOUR-ABSOLUTE/PATH/HERE" -user="username" - -# Define list of all servers including localhost -servers=("localhost" "192.168.2.21" "192.168.2.11") -# Define a mapping of part files to server hostnames and IPs. Needed for monitor_progress -declare -A server_map=(["aa"]="192.168.2.21" ["ab"]="192.168.2.11" ["ac"]="localhost") -part_files=("$directory/files_list_partaa" "$directory/files_list_partab" "$directory/files_list_partac") # Adjust as needed based on actual part files generated -# Adjust max_concurrent_jobs in process_files() - -check_rw_access() { # Function to check read/write access. Called by check_directory_exists - local server=$1 - local check_file="${directory}/rw_check.tmp" - - # Command to create and then remove a temporary file - local cmd="touch '${check_file}' && rm '${check_file}'" +#!/usr/bin/env bash +# Shared-storage batch transcoding. Requires Bash 4.4+ and GNU core utilities. +set -uo pipefail + +die() { printf 'Error: %s\n' "$*" >&2; exit 2; } +(( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )) || die 'Bash 4.4 or newer is required' +hash_file() { sha256sum < "$1" | cut -d ' ' -f 1; } +hash_text() { printf '%s' "$1" | sha256sum | cut -d ' ' -f 1; } + +usage() { + cat <<'EOF' +Usage: bash vidprocess.sh --input DIR [options] + --output DIR Output root (default: INPUT/transcoded) + --host HOST Worker host; repeat for multiple hosts (default: localhost) + --user USER SSH username (default: SSH configuration) + --jobs N Concurrent encodes per host (default: 2) + --retries N Additional attempts per failed job (default: 0) + --filter FILTER FFmpeg video filter (default: original crop/scale preset) + --dry-run List planned files without writes or SSH connections + --help Show this help + +All hosts must share the same absolute input/output paths and have Bash 4.4+, +GNU core utilities and FFmpeg with libx264/AAC. Outputs preserve relative paths +and append .mp4 to the complete input filename. Existing files are never replaced. +EOF +} - if [ "$server" = "localhost" ]; then - # Execute command directly for local server - if ! eval "$cmd"; then - echo "Error: Unable to write to ${directory} on local server. Check read/write permissions." - exit 1 - fi - else - # Execute command via SSH for remote servers - if ! ssh "$user"@"$server" "$cmd"; then - echo "Error: Unable to write to ${directory} on server $server. Check read/write permissions." - exit 1 - fi - fi +check_tools() { + local tool + for tool in ffmpeg sha256sum cut mktemp mv ln mkdir rm rmdir realpath dirname cat; do + command -v "$tool" >/dev/null || die "Required command unavailable: $tool" + done } -check_directory_exists(){ # Check directory existence and read/write access on all servers -for server in "${servers[@]}"; do - if [ "$server" = "localhost" ]; then - # Check directory on the local server - if [ ! -d "$directory" ]; then - echo "Directory does not exist on local server." - exit 1 - else - echo "Directory exists on local server. Checking read/write access..." - check_rw_access "$server" - fi - else - # Check directory on remote servers - if ! ssh "$user"@"$server" "[ -d '$directory' ]"; then - echo "Directory does not exist on server $server." - exit 1 - else - echo "Directory exists on server $server. Checking read/write access..." - check_rw_access "$server" +worker() { + local source=$1 destination=$2 state=$3 run=$4 id=$5 filter=$6 attempt=$7 + local receipt="$state/receipts/$id" + # Cleanup variables outlive this function until the worker shell exits. + lock="$state/locks/$id" + temporary='' child='' receipt_tmp='' + local input_hash output_hash signature old_signature old_output + worker_cleanup() { + if [[ -n "$child" ]]; then kill "$child" 2>/dev/null || :; wait "$child" 2>/dev/null || :; fi + [[ -z "$temporary" ]] || rm -f -- "$temporary" + [[ -z "$receipt_tmp" ]] || rm -f -- "$receipt_tmp" + rmdir -- "$lock" 2>/dev/null || : + } + worker_stop() { exit 130; } + check_tools + mkdir -- "$lock" 2>/dev/null || { printf 'Output is locked: %s\n' "$destination" >&2; return 1; } + trap worker_cleanup EXIT + trap worker_stop INT TERM + input_hash=$(hash_file "$source") || return 1 + signature=$(hash_text "preset-v1|$input_hash|$filter") || return 1 + if [[ -e "$destination" || -L "$destination" ]]; then + if [[ -f "$destination" && ! -L "$destination" && -f "$receipt" ]]; then + { IFS= read -r old_signature; IFS= read -r old_output; } < "$receipt" || return 1 + output_hash=$(hash_file "$destination") || return 1 + if [[ "$signature" == "$old_signature" && "$output_hash" == "$old_output" ]]; then + printf 'skipped\n' > "$run/$id.result" + return 0 + fi fi + printf 'Existing output has no matching verified receipt; preserving it: %s\n' "$destination" >&2 + return 1 fi -done -echo "All servers have read/write access to the directory. Proceeding with the script..." + local parent + parent=$(dirname -- "$destination") + # Check prospective paths before creating directories, then verify again. + local actual_parent output_root + actual_parent=$(realpath -m -- "$parent") || return 1 + output_root=$(cd -- "$state/.." && pwd -P) || return 1 + [[ "$actual_parent/" == "$output_root/"* ]] || { printf 'Output escapes output root\n' >&2; return 1; } + mkdir -p -- "$parent" || return 1 + actual_parent=$(cd -- "$parent" && pwd -P) || return 1 + [[ "$actual_parent/" == "$output_root/"* ]] || return 1 + temporary=$(mktemp "$parent/.vidprocess.XXXXXXXX.mp4") || return 1 + ffmpeg -nostdin -hide_banner -v error -i "$source" \ + -vf "$filter" -c:v libx264 -preset medium -crf 23 \ + -c:a aac -ar 48000 -ac 2 -b:a 128k -f mp4 -y "$temporary" & + child=$! + local encode_status=0 + wait "$child" || encode_status=$? + child='' + (( encode_status == 0 )) || return "$encode_status" + [[ -s "$temporary" ]] || { printf 'Encoder produced an empty output\n' >&2; return 1; } + [[ "$(hash_file "$source")" == "$input_hash" ]] || { printf 'Input changed during encoding\n' >&2; return 1; } + output_hash=$(hash_file "$temporary") || return 1 + # A hard link atomically publishes a complete file and fails if the name exists. + # No replace/force flag: an unrelated writer's destination is always preserved. + ln -T -- "$temporary" "$destination" || return 1 + rm -- "$temporary" || return 1 + temporary='' + receipt_tmp=$(mktemp "$state/receipts/.receipt.XXXXXXXX") || return 1 + printf '%s\n%s\n' "$signature" "$output_hash" > "$receipt_tmp" || return 1 + mv -- "$receipt_tmp" "$receipt" || return 1 + receipt_tmp='' + printf 'success\n' > "$run/$id.result" } -find_files(){ #find all video files in $directory -# Find video files and generate a list -find "$directory" -type f -regex '.*\.\(mp4\|mov\|avi\|mkv\|flv\|wmv\|mpeg\|mpg\|webm\|3gp\|ogg\|ogv\|ts\)' > "$directory/files_list.txt" -echo "File list generated: $directory/files_list.txt" -} - -prep_files() { #set up the error log and divide files_list for distribution to servers, based on file number. Last file will catch the remainder. -# Create or clear the error log file -error_log="$directory/error_log.txt" -echo "Error log: $error_log" -> "$error_log" - -# Divide the total number of files evenly among the servers -total_files=$(wc -l < "$directory/files_list.txt") -echo "Total files: $total_files" -files_per_machine=$((total_files / 3)) -echo "Files per machine: $files_per_machine" -files_per_thread=$((files_per_machine / 56)) -echo "Files per thread: $files_per_thread" - -# Split the file list into three parts -split -l "$files_per_machine" "$directory/files_list.txt" "$directory/files_list_part" - -# Merge extra part file if exists -if [ -f "$directory/files_list_partad" ]; then - cat "$directory/files_list_partac" "$directory/files_list_partad" > "$directory/temp_ac" - mv "$directory/temp_ac" "$directory/files_list_partac" - rm "$directory/files_list_partad" +# Internal modes are also used by the script sent to remote workers over stdin. +if [[ ${1:-} == --internal-worker ]]; then + shift + (( $# == 7 )) || die 'Invalid worker arguments' + worker "$@" + exit $? +fi +if [[ ${1:-} == --internal-check ]]; then + shift + (( $# == 2 )) || die 'Invalid preflight arguments' + check_tools + [[ -f "$1" && "$(cat -- "$1")" == "$2" ]] || die 'Worker cannot see shared run state' + probe=$(mktemp "$(dirname -- "$1")/.probe.XXXXXXXX") || exit 2 + link="$probe.link" + ln -T -- "$probe" "$link" || { rm -f -- "$probe"; die 'Output filesystem must support hard links'; } + rm -- "$link" "$probe" || exit 2 + exit 0 fi -} - -checkfiles() { # triple check that files_list.txt and all parts are valid paths before we start actually chewing on them - -# After generating files_list.txt -echo "Checking validity of file paths in files_list.txt..." - -while IFS= read -r file; do - if [ ! -f "$file" ]; then - echo "Invalid file path detected: $file" - exit 1 - fi -done < "$directory/files_list.txt" - -echo "All file paths in files_list.txt are valid." -for server in "${servers[@]}"; do - for part_file in "${part_files[@]}"; do - if [ "$server" = "localhost" ]; then - # Check part file on the local server - if [ ! -f "$part_file" ]; then - echo "Part file does not exist on local server: $part_file" - exit 1 - fi - else - # Check part file on remote servers - if ! ssh "$user"@"$server" "[ -f '$part_file' ]"; then - echo "Part file does not exist on server $server: $part_file" - exit 1 - fi - fi - done +input='' output='' user='' jobs=2 retries=0 dry_run=0 +filter='crop=1584:1072:158:6,scale=640:480' +hosts=() +while (( $# )); do + case $1 in + --help|-h) usage; exit 0 ;; + --dry-run) dry_run=1; shift ;; + --input|--output|--user|--jobs|--retries|--filter|--host) + (( $# >= 2 )) || die "Missing value for $1" + case $1 in + --input) input=$2 ;; --output) output=$2 ;; --user) user=$2 ;; + --jobs) jobs=$2 ;; --retries) retries=$2 ;; --filter) filter=$2 ;; + --host) hosts+=("$2") ;; + esac + shift 2 ;; + *) die "Unknown option: $1" ;; + esac done - -echo "All part files exist on all servers." -} - -process_files() { # Function to process files in parallel with controlled concurrency. called by process_workers_start in loop - local file_list_part="$1" - local max_concurrent_jobs=10 # Adjust based on system capacity - local job_count=0 - local base_marker_dir="$directory/zzzzz-process_markers" - local part_name=$(basename "$file_list_part" | sed 's/files_list_part//') # Extract 'aa', 'ab', or 'ac' - local marker_dir="$base_marker_dir/$part_name" - local transcoded_dir="$directory/transcoded" # Subdirectory for transcoded files - - # Ensure the marker and transcoded directory exists - mkdir -p "$marker_dir" - mkdir -p "$transcoded_dir" - - echo "Inside process_files with: $file_list_part on host: $(hostname)" - - declare -a job_pids=() # Array to hold job PIDs - - while IFS= read -r file; do - local out_file="$transcoded_dir/$(basename "$file")" - if (( job_count >= max_concurrent_jobs )); then - # Wait for any job to finish before starting a new one - wait -n "${job_pids[@]}" - # Remove finished jobs from the array - job_pids=($(jobs -rp)) - job_count=${#job_pids[@]} - fi - - ( - # echo "Processing file on host: $(hostname)" - if ffmpeg -nostdin -v error -i "$file" \ - -vf "crop=1584:1072:158:6,scale=640:480" \ - -c:v libx264 -preset medium -crf 23 \ - -c:a aac -ar 48000 -ac 2 -b:a 128k \ - "$out_file" -y; then - # On success, create a success marker file - touch "$marker_dir/$(basename "$file").success" - # echo "Successfully processed $file on host: $(hostname)" - else - #echo "Error log: $error_log" - echo "$file" >> "$error_log" - touch "$marker_dir/$(basename "$file").failure" - fi - ) & - - # Capture PID of the background job - job_pids+=($!) - ((job_count++)) - done < "$file_list_part" - - # Wait for all remaining background jobs to finish - wait - - # count and log the number of success/failure markers for this part after processing - local success_count=$(find "$marker_dir" -type f -name '*.success' | wc -l) - local failure_count=$(find "$marker_dir" -type f -name '*.failure' | wc -l) - local processed_count=$((success_count + failure_count)) - echo "Total files successfully processed for part $part_name: $processed_count" +[[ -n "$input" && -d "$input" ]] || die '--input must name an existing directory' +[[ "$jobs" =~ ^[1-9][0-9]*$ && ${#jobs} -le 3 ]] || die '--jobs must be an integer from 1 to 999' +[[ "$retries" =~ ^[0-9]+$ && ${#retries} -le 2 ]] || die '--retries must be an integer from 0 to 99' +retries=$((10#$retries)) +[[ -n "$filter" ]] || die '--filter must not be empty' +(( ${#hosts[@]} )) || hosts=(localhost) +for host in "${hosts[@]}"; do + [[ "$host" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:-]*$ ]] || die "Invalid host: $host" +done +[[ -z "$user" || "$user" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$ ]] || die 'Invalid SSH username' +input=$(cd -- "$input" && pwd -P) || exit 2 +output=${output:-"$input/transcoded"} +command -v realpath >/dev/null || die 'GNU realpath is required' +output=$(realpath -m -- "$output") || exit 2 +[[ "$input" != / && "$output" != / && "$input" != "$output" && "$input/" != "$output/"* ]] || die 'Input/output cannot be filesystem root; output must not equal or contain input' +state="$output/.vidprocess" +script=$(realpath -- "${BASH_SOURCE[0]}") || exit 2 + +# Snapshot discovery using NUL delimiters, including uppercase extensions. Prune +# generated outputs and state; do not follow symlinks into other directory trees. +files=() +output_pattern=${output//\\/\\\\} +output_pattern=${output_pattern//\*/\\*} +output_pattern=${output_pattern//\?/\\?} +output_pattern=${output_pattern//\[/\\[} +discover() { + find "$input" -path "$output_pattern" -prune -o -type f \ + \( -iname '*.mp4' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.mkv' \ + -o -iname '*.flv' -o -iname '*.wmv' -o -iname '*.mpeg' -o -iname '*.mpg' \ + -o -iname '*.webm' -o -iname '*.3gp' -o -iname '*.ogg' -o -iname '*.ogv' -o -iname '*.ts' \) -print0 } +if (( dry_run )); then + # pipefail propagates discovery failures; dry-run creates no directories/files. + discover | while IFS= read -r -d '' file; do printf '%q -> %q\n' "$file" "$output/${file#"$input/"}.mp4"; done + exit $? +fi -monitor_progress() { # monitor job progress, called in process_workers_start - local base_marker_dir="./zzzzz-process_markers" - local report_interval=600 # Report every 10 minutes (600 seconds) - local total_processed - -while :; do - echo "---- Processing Report: $(date) ----" - total_processed=0 - for part in "${!server_map[@]}"; do - local server_ip=${server_map[$part]} - local hostname - - # Fetch hostname for remote servers, or use $(hostname) for localhost - if [[ "$server_ip" == "localhost" ]]; then - hostname=$(hostname) - else - hostname=$(ssh "$server_ip" 'hostname') - fi - - local part_dir="$base_marker_dir/$part" - local count=0 - if [[ -d "$part_dir" ]]; then - count=$(find "$part_dir" -type f -name '*.success' | wc -l) - fi - - echo "Server: $hostname ($server_ip), Part $part: $count files processed." - ((total_processed+=count)) - done - echo "Total processed across all servers: $total_processed" - echo "----------------------------------------" - - sleep "$report_interval" - done +mkdir -p -- "$state" || exit 2 +[[ ! -L "$state" ]] || die 'State directory must not be a symlink' +mkdir -- "$state/lock" 2>/dev/null || die "Run lock exists: $state/lock (ensure no workers remain before manually removing a stale lock)" +pids=() slot_ids=() slot_hosts=() interrupted=0 +cleanup() { + local pid + for pid in "${pids[@]}"; do [[ -z "$pid" ]] || kill "$pid" 2>/dev/null || :; done + for pid in "${pids[@]}"; do [[ -z "$pid" ]] || wait "$pid" 2>/dev/null || :; done + rmdir -- "$state/lock" 2>/dev/null || : } - -process_workers_start() { # spawn workers and start processing the files. -monitor_progress & -monitor_pid=$! - -# Initialize an array to hold background process IDs -bg_processes=() - -# Process files on each server -for part in aa ab ac; do - file_list_part="$directory/files_list_part$part" - base_marker_dir="$directory/zzzzz-process_markers" # Ensure this uses the global $directory variable - - if [ "$part" = "aa" ]; then - server="192.168.2.21" - elif [ "$part" = "ab" ]; then - server="192.168.2.11" - else - server="localhost" - fi - - if [ "$server" != "localhost" ]; then - # Use SSH to process files remotely in parallel - ssh "$user"@"$server" "bash -c 'directory=\"$directory\"; file_list_part=\"$file_list_part\"; base_marker_dir=\"$base_marker_dir\"; error_log=\"$error_log\"; $(declare -f process_files); process_files \"\$file_list_part\"'" & - bg_processes+=($!) - else - # Process files locally in parallel - process_files "$file_list_part" & - bg_processes+=($!) - fi +stop() { interrupted=1; exit 130; } +trap cleanup EXIT +trap stop INT TERM +mkdir -p -- "$state/runs" "$state/receipts" "$state/locks" || exit 2 +for dir in "$state/runs" "$state/receipts" "$state/locks"; do [[ ! -L "$dir" ]] || die "State path must not be a symlink: $dir"; done +run=$(mktemp -d "$state/runs/run.XXXXXXXX") || exit 2 +printf 'Run state: %s\n' "$run" +discover > "$run/files.nul" || die 'Input discovery failed; inspect directory permissions' +while IFS= read -r -d '' file; do files+=("$file"); done < "$run/files.nul" +for file in "${files[@]}"; do + [[ "$file" != "$input/.vidprocess/"* ]] || die 'Input .vidprocess subtree conflicts with reserved output state; select a narrower input directory' done - -# Wait for all background processes to complete -for pid in "${bg_processes[@]}"; do - wait $pid -done - -echo "All processing complete." -echo "Error log is located at: $error_log" -kill "$monitor_pid" - -} - -summarize_and_compare() { # summarize completed work, check the initial work list. If different, missed some files. Write missed files to errormissing.log - local base_marker_dir="$directory/zzzzz-process_markers" - local processed_files_log="$directory/errormissing.log" - local total_requested_files=$(wc -l < "$directory/files_list.txt") - local total_processed_files=0 - - # Reset or create the log file - > "$processed_files_log" - - # Generate a temporary file listing all processed filenames (without the .success extension) - local processed_filenames="$directory/processed_filenames.tmp" - find "$base_marker_dir" -type f -name '*.success' -exec basename {} .success \; > "$processed_filenames" - - echo "Summary of processing:" - for part in aa ab ac; do - # Count both success and failure markers within each part - local success_count=$(find "$base_marker_dir/$part" -type f -name '*.success' | wc -l) - local failure_count=$(find "$base_marker_dir/$part" -type f -name '*.failure' | wc -l) - local part_processed_count=$((success_count + failure_count)) - - echo "Part $part processed files: $part_processed_count" - ((total_processed_files+=part_processed_count)) +printf 'Requested: %s\n' "${#files[@]}" +if (( ${#files[@]} == 0 )); then printf 'No matching inputs.\n'; exit 0; fi +token=$(hash_text "$run|$$|$RANDOM") || exit 2 +printf '%s' "$token" > "$run/shared-token" + +remote() ( + local host=$1; shift + local command='bash -s --' argument quoted target=$host + [[ -z "$user" ]] || target="$user@$host" + for argument in "$@"; do + # POSIX single-quote escaping also supports apostrophes/newlines in paths. + quoted=${argument//\'/\'\\\'\'} + command+=" '$quoted'" done - - echo "Total requested files: $total_requested_files" - echo "Total processed files: $total_processed_files" - - # Directly log missed file paths to errormissing.log without additional comments - if [ "$total_requested_files" -ne "$total_processed_files" ]; then - echo "Identifying missed files..." - - while IFS= read -r file; do - local file_basename=$(basename "$file") - if ! grep -Fxq "$file_basename" "$processed_filenames"; then - echo "$file" >> "$processed_files_log" - fi - done < "$directory/files_list.txt" + exec ssh -o BatchMode=yes -o ConnectTimeout=10 "$target" "$command" < "$script" +) +for host in "${hosts[@]}"; do + if [[ "$host" == localhost ]]; then + bash "$script" --internal-check "$run/shared-token" "$token" || die 'Local preflight failed' else - echo "All requested files have been successfully processed." - rm -f "$processed_files_log" # delete the errormissing.log file, it's blank + command -v ssh >/dev/null || die 'SSH is required for remote workers' + remote "$host" --internal-check "$run/shared-token" "$token" || die "Preflight failed on $host" fi - # Cleanup temporary file - rm "$processed_filenames" + for ((j=0; j/dev/null || :; [[ -z "$worker_pid" ]] || wait "$worker_pid" 2>/dev/null || :; exit 130; } + trap job_stop INT TERM + for ((attempt=0; attempt<=retries; attempt++)); do + if [[ "$host" == localhost ]]; then + bash "$script" --internal-worker "$file" "$destination" "$state" "$run" "$id" "$filter" "$attempt" > "$run/$id.$attempt.log" 2>&1 & else - echo "Invalid input. Please enter 'y' for yes or 'n' for no." - # The loop will continue, prompting the user again for valid input + remote "$host" --internal-worker "$file" "$destination" "$state" "$run" "$id" "$filter" "$attempt" > "$run/$id.$attempt.log" 2>&1 & fi + worker_pid=$! + status=0 + wait "$worker_pid" || status=$? + worker_pid='' + (( status != 0 )) || return 0 done - - else - echo "No missed files. Reprocessing not required. Script exiting." - fi + printf 'failed\n' > "$run/$id.result" + return 1 } - -#main program. Function-heavy because it's easier to debug, so the following statements are functions meant to run sequentially. - -check_directory_exists # Check directory existence and read/write access on all servers -find_files # find all video files in $directory -# re-run from here -prep_files #divide files_list for distribution to servers, based on file number. Last file will catch the remainder. -# checkfiles # triple check that files_list.txt and all parts are valid paths before we start actually chewing on them. useful to debug cryptic "no such file" errors -process_workers_start # spawn workers and start processing the files. -summarize_and_compare # summarize completed work, check the initial work list. If different, missed some files. Write missed files to errormissing.log - -#sort the error_log.txt file alphabetically for ease of review -sort "$error_log" | uniq > "$error_log.tmp" && mv "$error_log.tmp" "$error_log" - -# Clean up temporary files. not a function because we should only clean up if the script made it all the way through to here. -echo "Cleaning up temporary files and exiting" -rm "$directory/files_list.txt" "$directory/files_list_part"* -rm -rf "$directory/zzzzz-process_markers" +success=0 skipped=0 failed=0 finished=0 +reap() { + local slot=$1 result='failed' status=0 id=${slot_ids[$1]} + [[ -n "${pids[$slot]}" ]] || return 0 + wait "${pids[$slot]}" || status=$? + pids[$slot]='' + if (( status == 0 )) && [[ -f "$run/$id.result" ]]; then IFS= read -r result < "$run/$id.result" || result=failed; fi + case $result in success) ((success+=1)) ;; skipped) ((skipped+=1)) ;; *) ((failed+=1)); printf '%s\0' "${job_sources[$id]}" >> "$run/retry.nul" ;; esac + ((finished+=1)) + printf 'Completed %s/%s: success=%s skipped=%s failed=%s\n' "$finished" "${#files[@]}" "$success" "$skipped" "$failed" +} +declare -A job_sources=() +index=0 +for file in "${files[@]}"; do + relative=${file#"$input/"} + id=$(hash_text "$relative") || exit 2 + job_sources[$id]=$file + destination="$output/$relative.mp4" + slot=$((index % ${#slot_hosts[@]})) + reap "$slot" + printf '%s\t%q\t%q\t%s\n' "$id" "$file" "$destination" "${slot_hosts[$slot]}" >> "$run/manifest.tsv" || die 'Could not write run manifest' + run_job "${slot_hosts[$slot]}" "$file" "$destination" "$id" & + pids[$slot]=$! + slot_ids[$slot]=$id + ((index+=1)) +done +for ((slot=0; slot<${#pids[@]}; slot++)); do reap "$slot"; done +printf 'Summary: requested=%s success=%s skipped=%s failed=%s\nLogs and manifests: %s\n' "${#files[@]}" "$success" "$skipped" "$failed" "$run" +(( failed == 0 )) From 2c263e2f4db0d5bec6adb6494fee38e159b07040 Mon Sep 17 00:00:00 2001 From: xmutantson Date: Fri, 2 Oct 2026 12:23:12 -0700 Subject: [PATCH 2/2] Reject FFmpeg decode errors before publishing verified batch outputs --- README.md | 10 ++++++++- tests/test_vidprocess.py | 47 +++++++++++++++++++++++++++++++++++++++- vidprocess.sh | 14 +++++++++--- 3 files changed, 66 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e530746..713c34e 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,12 @@ unfinished files are attempted again, with additional attempts controlled by directories manually only when no workers use them; keep receipts for future verified skipping. +FFmpeg runs with `-xerror`: reported decoding/demuxing errors fail the job before +publication or receipt creation. Receipts from the earlier permissive decoder +policy are not accepted; existing outputs are preserved as conflicts. Inspect +them and use a new output root or move them aside before retrying. This does not +detect missing content that the media container/decoder reports as valid. + Verification reads entire source and output files. Successful encoding also checks the source again before publication to detect changes during processing. This adds disk/network I/O. Keep source media stable while processing it. @@ -128,5 +134,7 @@ they never contact remote hosts. Set `BASH_EXE` if needed (Windows defaults to t standard Git Bash installation). Coverage includes zero-to-ten-file batches, duplicate names, verified reruns, changed inputs/outputs, overwrite refusal, bounded retries, empty/failed encodes, remote quoting/failures, cancellation, -and dry-run behavior. Newline filenames are skipped on Windows because its +and dry-run behavior. Real synthetic FFmpeg controls also cover truncated input, +retry after source repair, and valid media paths containing spaces/apostrophes +(explicitly converted for native Windows FFmpeg). Newline filenames are skipped on Windows because its filesystem forbids them. diff --git a/tests/test_vidprocess.py b/tests/test_vidprocess.py index 936df0e..c5c3eed 100644 --- a/tests/test_vidprocess.py +++ b/tests/test_vidprocess.py @@ -1,4 +1,5 @@ -"""Offline integration tests; ffmpeg and ssh are always temporary local stubs.""" +"""Offline tests using synthetic media and local stubs; SSH never contacts a host.""" +import hashlib import os from pathlib import Path import shutil @@ -26,6 +27,7 @@ def shell_path(path): while (( $# )); do if [[ $1 == -i ]]; then source=$2; shift 2; else output=$1; shift; fi done +case "$OSTYPE" in msys*|cygwin*) source=$(cygpath -u -- "$source");; esac printf '%s\0' "$source" >> "$TEST_CALLS" trap 'printf stopped > "$TEST_STOPPED"; exit 143' TERM if [[ ${TEST_CANCEL:-0} == 1 ]]; then @@ -131,6 +133,49 @@ def test_verified_rerun_skips_and_excludes_output_tree(self): self.assertIn("requested=1 success=0 skipped=1 failed=0", result.stdout) self.assertEqual(self.count_calls(), 1) + def test_permissive_policy_receipt_is_not_trusted(self): + source = self.add("one.mp4") + self.assert_ok(self.run_batch("--filter", "null")) + target = self.output / "one.mp4.mp4" + before = target.read_bytes() + receipt = next((self.output / ".vidprocess/receipts").iterdir()) + input_hash = hashlib.sha256(source.read_bytes()).hexdigest() + old_signature = hashlib.sha256(f"preset-v1|{input_hash}|null".encode()).hexdigest() + receipt.write_text(old_signature + "\n" + hashlib.sha256(before).hexdigest() + "\n") + result = self.run_batch("--filter", "null") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertEqual(target.read_bytes(), before) + self.assertEqual(self.count_calls(), 1) + self.assertIn("skipped=0 failed=1", result.stdout) + + def test_real_truncated_video_retries_then_accepts_repaired_source(self): + ffmpeg = shutil.which("ffmpeg") + if not ffmpeg: + self.skipTest("FFmpeg required for real synthetic video check") + (self.bin / "ffmpeg").unlink() + reference = self.base / "valid.mp4" + subprocess.run([ffmpeg, "-v", "error", "-f", "lavfi", "-i", + "testsrc2=size=128x96:rate=25:duration=2", "-c:v", "libx264", + "-movflags", "+faststart", "-y", str(reference)], + check=True, capture_output=True, timeout=30) + source = self.inputs / "clip.mp4" + data = reference.read_bytes() + source.write_bytes(data[:len(data)//2]) + for _ in range(2): + result = self.run_batch("--filter", "null") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("success=0 skipped=0 failed=1", result.stdout) + self.assertFalse((self.output / "clip.mp4.mp4").exists()) + self.assertEqual(list((self.output / ".vidprocess/receipts").iterdir()), []) + self.assertFalse(list(self.output.rglob(".vidprocess.*.mp4"))) + source.write_bytes(data) + repaired = self.run_batch("--filter", "null") + logs = "\n".join(p.read_text() for p in self.output.glob(".vidprocess/runs/*/*.log")) + self.assertEqual(repaired.returncode, 0, repaired.stdout + repaired.stderr + logs) + result = self.run_batch("--filter", "null") + self.assert_ok(result) + self.assertIn("success=0 skipped=1 failed=0", result.stdout) + def test_unrelated_existing_output_is_preserved(self): self.add("one.mp4") self.output.mkdir() diff --git a/vidprocess.sh b/vidprocess.sh index 9366ac0..1185c6f 100644 --- a/vidprocess.sh +++ b/vidprocess.sh @@ -51,7 +51,7 @@ worker() { trap worker_cleanup EXIT trap worker_stop INT TERM input_hash=$(hash_file "$source") || return 1 - signature=$(hash_text "preset-v1|$input_hash|$filter") || return 1 + signature=$(hash_text "preset-v2-strict-decode|$input_hash|$filter") || return 1 if [[ -e "$destination" || -L "$destination" ]]; then if [[ -f "$destination" && ! -L "$destination" && -f "$receipt" ]]; then { IFS= read -r old_signature; IFS= read -r old_output; } < "$receipt" || return 1 @@ -75,9 +75,17 @@ worker() { actual_parent=$(cd -- "$parent" && pwd -P) || return 1 [[ "$actual_parent/" == "$output_root/"* ]] || return 1 temporary=$(mktemp "$parent/.vidprocess.XXXXXXXX.mp4") || return 1 - ffmpeg -nostdin -hide_banner -v error -i "$source" \ + # Native Windows FFmpeg needs explicit conversion for paths containing quotes. + local media_source=$source media_output=$temporary + case "$OSTYPE" in + msys*|cygwin*) + media_source=$(cygpath -am -- "$source") || return 1 + media_output=$(cygpath -am -- "$temporary") || return 1 + ;; + esac + ffmpeg -nostdin -hide_banner -v error -xerror -i "$media_source" \ -vf "$filter" -c:v libx264 -preset medium -crf 23 \ - -c:a aac -ar 48000 -ac 2 -b:a 128k -f mp4 -y "$temporary" & + -c:a aac -ar 48000 -ac 2 -b:a 128k -f mp4 -y "$media_output" & child=$! local encode_status=0 wait "$child" || encode_status=$?