diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b51d9e2..daebc32 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -2,7 +2,8 @@ name: Build & Release
on:
release:
- types: [created]
+ # published also fires when a draft is published; created does not.
+ types: [published]
workflow_dispatch:
# Critical: Grant write permission to upload assets to the Release
@@ -44,6 +45,22 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python build.py
+ - name: Build Windows Installer
+ if: runner.os == 'Windows'
+ shell: pwsh
+ env:
+ BUILD_VERSION: ${{ github.ref_name }}
+ run: |
+ choco install innosetup -y --no-progress
+ $exe = Get-ChildItem dist -Filter "100mb-hevc-win64*.exe" | Select-Object -First 1
+ if (-not $exe) { throw "100mb-hevc Windows executable not found in dist" }
+ # Branch names on manual runs contain '/', which is not valid in the output file name.
+ $version = $env:BUILD_VERSION.TrimStart('v') -replace '[^\w.\-]', '-'
+ # File version resources take numbers only: v1.3.0-rc1 -> 1.3.0, branch builds -> 0.0.0.
+ $numeric = if ($version -match '^\d+(\.\d+){0,3}') { $Matches[0] } else { '0.0.0' }
+ & "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" "/DAppVersion=$version" "/DNumericVersion=$numeric" "/DSourceExe=$($exe.FullName)" installer\windows.iss
+ if ($LASTEXITCODE -ne 0) { throw "ISCC failed with exit code $LASTEXITCODE" }
+
# --- Upload Section ---
- name: Upload Artifacts (to Actions Run)
diff --git a/.gitignore b/.gitignore
index 405e9d0..8848649 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,9 @@
dist/
build/
+.agents/
*.spec
-ffmpeg.exe
-ffprobe.exe
-ffmpeg
-ffprobe
+ffmpeg*
+ffprobe*
__pycache__/
*.pyc
*.pyo
@@ -16,3 +15,14 @@ ffmpeg-minimal-builds/
.venv/
venv/
ffmpeg-licenses/
+*.mp4
+tests/benchmark_outputs/
+tests/binaries/
+tests/reports/
+
+# Launch film / video generation (HyperFrames), kept local
+launch-film/
+*.mhtml
+
+# deja session history, machine-local
+.deja/
diff --git a/README.md b/README.md
index fb14f81..98514c9 100644
--- a/README.md
+++ b/README.md
@@ -41,37 +41,45 @@ Under the hood, the engine calculates optimal Bits-Per-Pixel (BPP) rate control,
## Requirements
For running the script locally (your own build):
- Python 3.11+
-- ffmpeg installed and added to PATH (Optional)
+- FFmpeg on PATH (with `zscale` and `tonemap` for HDR videos), or run `python build.py` once to download the minimal build (see [Development](#development))
- CUDA capable GPU for faster encoding (Optional)
- HEVC or H.264 encoding capable GPU (Optional)
For using prebuilt binaries from releases, you just need to download the executable for your platform; no installation required (standalone executables bundle lightweight FFmpeg/FFprobe binaries from [ffmpeg-minimal-builds](https://github.com/SimpNick6703/ffmpeg-minimal-builds)). To make full use of GPU acceleration, you need a compatible NVIDIA/AMD/Intel GPU that supports hardware-accelerated video encoding.
> [!IMPORTANT]
-> On Linux, the bundled FFmpeg requires the VA-API runtime libraries `libva2`, `libva-drm2` and `libdrm2`. They are generally already present on desktop distributions, but minimal installs and containers may need them installed (e.g. `sudo apt install libva2 libva-drm2 libdrm2`).
+> On Linux, the prebuilt executables need glibc 2.38 or newer (for example Ubuntu 24.04 or Debian 13; they do not start on Ubuntu 22.04 or Debian 12). The bundled FFmpeg also requires the VA-API runtime libraries `libva2`, `libva-drm2` and `libdrm2`. They are generally already present on desktop distributions, but minimal installs and containers may need them installed (e.g. `sudo apt install libva2 libva-drm2 libdrm2`).
-> [!NOTE]
-> You may view if your Nvidia GPU supports NVENC [here](https://developer.nvidia.com/video-encode-decode-support-matrix) and keep your Nvidia GPU driver version 570.0 or higher.
+> [!IMPORTANT]
+> **NVIDIA GPUs need driver 610.0 or newer** for NVENC with the prebuilt executables (v1.1.4 and later). Run `nvidia-smi` to see your version, and check [whether your GPU supports NVENC](https://developer.nvidia.com/video-encode-decode-support-matrix). With an older driver, the app lists NVIDIA as *Unavailable* and uses the next encoder, down to the CPU. GTX 900 and 10 series cards cannot install 610 (see [Known Issues](#known-issues)).
## How to use
- In Windows:
- Download any of the target filesize builds from [releases](https://github.com/SimpNick6703/Video-Compression/releases).
- - Drag and drop your video directly onto the executable (e.g., `100mb-hevc-win64.exe`). (Or run from terminal as `./{size}mb-{codec}-win64.exe [output.mp4]`).
+ - Drag and drop your video directly onto the executable (e.g., `100mb-hevc-win64-v1.3.0.exe`). (Or run from terminal as `./{size}mb-{codec}-win64-{version}.exe [output.mp4]`).
+ - Or install `VideoCompression-Setup-win64-.exe` from [releases](https://github.com/SimpNick6703/Video-Compression/releases) to add a **Video-Compression** submenu (*Compress to 20 MB / 50 MB / 100 MB / 1 GB / Custom...*) to the right-click menu of `.mp4`, `.mkv`, `.mov`, `.avi`, `.webm`, `.m4v`, `.flv` and `.3gp` files. On Windows 11 it is under **Show more options**. The installer asks for the codec (HEVC or H.264); reinstall to change it. Updates keep the earlier choice, and a first silent install uses HEVC unless `/CODEC=h264` is passed. It installs for the current user only (no admin prompt), and uninstalling removes the menu.
- In Linux:
- Download your desired build from [releases]().
- - Make your downloaded file executable: `chmod +x {size}mb-{codec}-linux`
- - Run in terminal as `./{size}mb-{codec}-linux [output.mp4] [target_size_in_mb]`
+ - Make your downloaded file executable: `chmod +x {size}mb-{codec}-linux-{version}`
+ - Run in terminal as `./{size}mb-{codec}-linux-{version} [output.mp4] [target_size_in_mb]`
- In MacOS:
- - Download your desired build from [releases]() (prebuilt releases target Apple Silicon `{size}mb-{codec}-macos-arm64`).
- - Make your downloaded file executable: `chmod +x {size}mb-{codec}-macos-arm64`
- - Run in terminal as `./{size}mb-{codec}-macos-arm64 [output.mp4]`
+ - Download your desired build from [releases]() (prebuilt releases target Apple Silicon `{size}mb-{codec}-macos-arm64-{version}`).
+ - Make your downloaded file executable: `chmod +x {size}mb-{codec}-macos-arm64-{version}`
+ - Run in terminal as `./{size}mb-{codec}-macos-arm64-{version} [output.mp4]`
- You may need to allow the application from **Settings > Privacy & Security** since MacOS blocks unsigned applications initially unless allowed.
- *(For Intel Macs)*: Simply run `python build.py` on your machine; it will automatically detect `x86_64`, fetch the matching minimal FFmpeg binary from [ffmpeg-minimal-builds](https://github.com/SimpNick6703/ffmpeg-minimal-builds), and build native `{size}mb-{codec}-macos-x86_64` executables for you.
> [!NOTE]
-> `{codec}` can be either `hevc` or `h264` depending on the build you downloaded. HEVC offers better compression efficiency, while H.264 offers better compatibility with older devices.
+> `{version}` is the release tag, for example `v1.3.0`. `{codec}` can be either `hevc` or `h264` depending on the build you downloaded. HEVC offers better compression efficiency, while H.264 offers better compatibility with older devices.
+
+> [!NOTE]
+> **HDR videos (HDR10 and HLG):** with a GPU encoder, HEVC keeps the video in HDR at its original bit depth (10-bit stays 10-bit, 8-bit stays 8-bit). H.264, and HEVC on the CPU encoder, convert it to standard colours (SDR) so it looks right on every screen and player. That conversion runs on the CPU, so it is slower: an 8.5 s 4K60 HDR10 clip took 31 s instead of 8.5 s on an RTX 4060 laptop, and HLG takes up to 1.5 times as long as HDR10.
+>
+> **AV1 videos** can be compressed too (the output is still HEVC or H.264).
+>
+> **Audio** is copied untouched, unless it is lossless (PCM, FLAC) or is above 160 kbps and would take more than 10% of the target size. It is then re-encoded to 128 kbps stereo AAC and the saved bits go to the video. Audio the bundled FFmpeg cannot decode (for example ALAC) is always copied, which does not work for every format (see [Known Issues](#known-issues)).
## How to Run (Python CLI)
@@ -88,18 +96,20 @@ python -m videocompress [output.mp4] [target_size_in_mb] [codec] [--
| Parameter | Type | Required | Default | Description |
|:---|:---|:---|:---|:---|
-| `` | `string` (Path) | **Yes** | — | Path to the source video file. Must exist on disk. |
-| `[output.mp4]` | `string` (Path) | No | `_MB.mp4` | Destination path for the compressed video. |
+| `` | `string` (Path) | **Yes** | — | Path to the source video file, including its extension. Must exist on disk. |
+| `[output.mp4]` | `string` (Path) | No | `_MB.mp4` | Destination file for the compressed video, including its extension. A folder is not accepted. |
| `[target_size_in_mb]` | `number` | No | `100` | Target file size threshold in megabytes (e.g. `20`, `50`, `100`, `1024`). Maps directly to Discord tiers: `20` MB (Free/Server Lvl 1), `50` MB (Server Lvl 2/Nitro Basic), `100` MB (Server Lvl 3), and `1024` MB ($10 Nitro). |
| `[codec]` | `string` | No | `hevc` | Encoding codec: `hevc` (H.265, higher efficiency) or `h264` (H.264, broader compatibility). |
+| `--custom` | `flag` | No | `False` | Asks for the target size in MB at startup (used by the *Custom...* right-click entry). |
| `--verbose`, `-v` | `flag` | No | `False` | Prints the decision trail live: encoder probes, pipeline tier, split point, bitrates and every FFmpeg command. Setting the environment variable `DEBUG=1` does the same. |
-Exit codes: `0` success, `1` failure (including "already smaller than target"), `130` cancelled with Ctrl+C. The preset executables accept the same arguments; the size and codec in their name are defaults that later arguments override.
+Exit codes: `0` success, `1` failure (including "already smaller than target" and an argument that is not a size, codec or file name), `130` cancelled with Ctrl+C (the partial output is removed). The preset executables accept the same arguments; the size and codec in their name are defaults that later arguments override.
> [!TIP]
> **Invocation and argument order are flexible:**
> * You can invoke the CLI either directly by package directory (`python videocompress ...`) or as a module (`python -m videocompress ...`).
-> * Optional arguments can be provided in any order (e.g. `python videocompress input.mp4 50 hevc` or `python videocompress input.mp4 hevc 50`). The CLI automatically detects arguments by type: numeric values as target MB size, `hevc`/`h264` as the codec, existing file paths as the input, and any additional path as the output destination.
+> * Optional arguments can be provided in any order (e.g. `python videocompress input.mp4 50 hevc` or `python videocompress input.mp4 hevc 50`). The CLI automatically detects arguments by type: numeric values as target MB size, `hevc`/`h264` as the codec, and names with a file extension as paths (the first that exists is the input, the other is the output).
+> * File names always need their extension: `20` is a size even if a file or folder called `20` exists, while `20.mp4` is a file. Folder names and names without an extension are rejected.
### Examples
@@ -136,14 +146,14 @@ pip install -e ".[dev,build]" # dev: pytest, ruff, psutil; build: pyinstall
| Extra | Installs | Needed for |
|:---|:---|:---|
| *(none)* | `rich` | Running the CLI from source |
-| `dev` | `pytest`, `ruff`, `psutil` | Tests, linting, `tools/bench_vitals.py` |
+| `dev` | `pytest`, `ruff`, `psutil` | Tests, linting |
| `build` | `pyinstaller` | `python build.py` |
FFmpeg is looked up in this order: the bundled copy (inside an executable), an `ffmpeg-minimal-builds/` or `minimal-builds/` folder, the repository root, then `PATH`. `python build.py` downloads the minimal build to the repository root.
### Tests and Linting
-The tests need no GPU and no FFmpeg; every FFmpeg call is replaced with a fake, and the suite runs in well under a second. Real hardware is covered by running the CLI or the benchmark tool below.
+The tests need no GPU and no FFmpeg; every FFmpeg call is replaced with a fake, and the suite runs in well under a second. Real hardware is covered by running the CLI.
```bash
pytest -q # whole suite
@@ -158,7 +168,15 @@ ruff check --fix . # apply the safe automatic fixes
| `test_hwpipeline.py` | Exact FFmpeg arguments for every backend (NVENC, VA-API, AMF, QSV, VideoToolbox) and tier |
| `test_legacy_cmds.py` | The legacy fallback still produces the pre-v1.2 commands |
| `test_tier_fallback.py` | Tier probing order (zero-copy, then upload, then legacy) and the automatic retry |
-| `test_concat.py` | Segment stitching with and without `h264_mp4toannexb` |
+| `test_concat.py` | Segment stitching with and without `h264_mp4toannexb`, audio taken from the source |
+| `test_audio.py` | When audio is copied or re-encoded, and the video budget that leaves |
+| `test_hdr.py` | When HDR is kept or tone-mapped, and handling of missing colour tags |
+| `test_cli_custom.py` | The `--custom` target size prompt |
+| `test_runtime_libs.py` | The message for missing Linux system libraries |
+| `test_notices.py` | License notices shipped next to the executables |
+| `test_tables.py` | Rounded tables and panels, including in legacy Windows consoles |
+| `test_cancel.py` | Ctrl+C exits with 130 and removes the partial output |
+| `test_cli_args.py` | Sizes, codecs and file names on the command line, whatever is in the current folder |
| `test_diagnostics.py` | In-memory run log and the failure-only error log file |
| `test_version.py` | Version embedding in executables and FFmpeg release selection |
@@ -170,7 +188,7 @@ python build.py --verbose # same, but keep build/ and *.spec for debuggin
python build.py --clean-ffmpeg # also delete the downloaded ffmpeg/ffprobe afterwards
```
-This builds every preset (20, 50, 100 and 1024 MB, each for HEVC and H.264) for the current platform. If `ffmpeg`/`ffprobe` are not already in the repository root, it downloads the newest [ffmpeg-minimal-builds](https://github.com/SimpNick6703/ffmpeg-minimal-builds) release: the highest FFmpeg version, then the highest revision (e.g. `ffmpeg-n9.0.2-r2`). It then checks that the binary contains the hardware filters this platform needs.
+This builds every preset (20, 50, 100 and 1024 MB, each for HEVC and H.264) for the current platform. If `ffmpeg`/`ffprobe` are not already in the repository root, it downloads the newest [ffmpeg-minimal-builds](https://github.com/SimpNick6703/ffmpeg-minimal-builds) release: the highest FFmpeg version, then the highest revision (e.g. `ffmpeg-n9.0.2-r2`). It then checks that the binary contains the hardware filters this platform needs and the HDR tone-mapping filters (`zscale`, `tonemap`).
| Environment variable | Effect |
|:---|:---|
@@ -180,32 +198,13 @@ This builds every preset (20, 50, 100 and 1024 MB, each for HEVC and H.264) for
| `GITHUB_TOKEN` / `GH_TOKEN` | Used only to list FFmpeg releases; avoids the low anonymous GitHub API rate limit. |
| `CI` | When set, a missing hardware filter fails the build instead of only warning. |
-### Benchmarking
-
-`tools/bench_vitals.py` runs any command and reports wall time, CPU time of the command and everything it starts, host CPU, peak memory and GPU engine load as one JSON line. It is a development tool and is not bundled into the executables.
-
-```bash
-python tools/bench_vitals.py --label 4k_v120 --output out.mp4 -- python -m videocompress input-4K60.mp4 out.mp4 100 hevc
-python tools/bench_vitals.py --label old --output out.mp4 --csv samples.csv -- ./100mb-hevc-linux-v1.1.6 input-4K60.mp4 out.mp4
-```
-
-| Option | Meaning |
-|:---|:---|
-| `--label` | Name stored in the JSON line (required) |
-| `--output` | Encoded file whose size is reported as `output_mb` |
-| `--csv` | Also write per-sample rows to this file |
-| `--interval` | Sampling interval in seconds (default `0.5`) |
-| `--` | Everything after it is the command to measure |
-
-GPU load comes from DRM fdinfo on Linux (Intel and AMD, no root needed) and from `nvidia-smi` on any OS (first NVIDIA GPU). CPU time is exact on Linux and macOS and sampled on Windows (`tree_cpu_source` in the output says which).
-
### CI/CD Workflows
| Workflow | Runs on | Does |
|:---|:---|:---|
| **CI** (`ci.yml`) | Pull requests, pushes to `main`, manual | `ruff check` and `pytest` on Python 3.11 and 3.13 |
| **Deploy Architecture Page** (`deploy.yml`) | Pushes to `main` that change `docs/`, manual | Publishes `docs/` to GitHub Pages |
-| **Build & Release** (`release.yml`) | Creating a GitHub release, manual | Builds the executables on Windows, Linux and macOS; attaches them to the release (manual runs only keep them as run artifacts) |
+| **Build & Release** (`release.yml`) | Publishing a GitHub release (including pre-releases and drafts once published), manual | Builds the executables on Windows, Linux and macOS, plus the Windows installer; attaches them to the release (manual runs only keep them as run artifacts) |
### Releasing
@@ -224,14 +223,14 @@ Considering the wide variety of hardware configurations, the script uses a fallb
> `*_nvenc` > `*_vaapi` > `*_videotoolbox` > `*_amf` > `*_qsv` > `libx265` / `libx264` (CPU)
> [!NOTE]
-> All hardware encoders (NVENC, AMF, VAAPI, QSV, VideoToolbox) use parallel split single-pass encoding with hardware rate control (including on-chip lookahead and adaptive quantization). Software fallback (libx265 / libx264) uses a contiguous single-pass pipeline.
+> All hardware encoders (NVENC, AMF, VAAPI, QSV, VideoToolbox) use parallel split single-pass encoding with hardware rate control. NVENC and QSV add lookahead, and NVENC and AMF add adaptive quantization. Software fallback (libx265 / libx264) uses a contiguous single-pass pipeline.
> Hardware encodes pick the most GPU-resident pipeline that works on your input, probed automatically on a one-second sample of the real file (no flags needed):
> - **zero-copy**: hardware decode, hardware scale and hardware encode, so frames never return to system memory.
> - **upload**: software decode, then upload, hardware scale and hardware encode. Used when the GPU cannot decode the source format (for example VP9 or H.264 4:2:2 on VA-API).
-> - **legacy**: the previous pipeline with CPU scaling. Used when neither of the above works, and as an automatic retry if an encode fails part-way.
+> - **legacy**: the previous pipeline, which scales on the CPU except with NVENC. Used when neither of the above works, and as an automatic retry if an encode fails part-way (except when converting HDR to SDR, which has only one pipeline).
>
> The benefit is near-zero CPU use during the encode, which keeps the machine responsive while gaming or streaming. Wall-clock time is not guaranteed to improve, since the GPU encoder is often the limit. The selected tier is shown in the result summary.
-> If your dedicated GPU is being bypassed in favor of integrated GPU or CPU encoding, you'll need to manually change the priority logic in the script to suit your hardware setup. Or, you may simply remove unwanted encoders from the priority list in the script, build the executable again, and use that custom build.
+> If your dedicated GPU is being bypassed in favor of integrated GPU or CPU encoding, first check its driver (NVIDIA needs 610.0 or newer, see [Requirements](#requirements)). Otherwise, you'll need to manually change the priority logic in the script to suit your hardware setup. Or, you may simply remove unwanted encoders from the priority list in the script, build the executable again, and use that custom build.
## Reporting Problems
@@ -239,19 +238,35 @@ If a compression fails, a `
+
One exception: converting HDR to SDR takes frames through the CPU. See HDR & Color.
@@ -252,7 +254,7 @@
What changes when frames stay on the GPU
Host CPU load
-
~30–40% → < 5%
+
~52% → ~7%
Scaling moves from CPU cores to the GPU
@@ -264,7 +266,7 @@
What changes when frames stay on the GPU
- Test clip used for every number on this page
+ Test clip used for every number in this tabReference baseline
@@ -276,7 +278,7 @@
What changes when frames stay on the GPU
Duration
236.95 s
-
14,217 frames (03:56.95)
+
14,216 frames (03:56.95)
Input size
@@ -286,7 +288,7 @@
What changes when frames stay on the GPU
Target size
< 100.00 MB
-
3,446 kbps · 78.6% smaller
+
88.48 MB out · 3,132 kbps · 80.6% smaller
@@ -294,8 +296,8 @@
What changes when frames stay on the GPU
One raw frame in NV12 / YUV420p takes width × height × 1.5 bytes.
Native 1080p: frames never leave VRAM. Only the compressed bitstream crosses PCIe: 457 MB in + 88 MB out ≈ 545 MB.
Downscaled to 720p (legacy hybrid): FFmpeg downloads every decoded 1080p frame to system RAM for CPU Lanczos scaling (44.22 GB device → host), then uploads the 720p frames back to NVENC (19.65 GB host → device). With the bitstream that is ≈ 64.41 GB of PCIe traffic.
-hwaccel cuda was omitted, so every frame was decoded on the CPU while the GPU decoder sat idle and NVENC waited for frames.
- CPU 91% · NVDEC idle
+ CPU 80% · NVDEC idle
@@ -515,11 +517,11 @@
CPU software decode bottleneck
-
System RAM & CPUPegged at 91%
+
System RAM & CPU80% of all threads
CPU software decode (avcodec)
- 14,217 frames decoded on CPU
+ 14,216 frames decoded on CPUHeavy thread contention across cores
@@ -528,7 +530,7 @@
System RAM & CPUCompounds the CPU work queue
-
CPU throttling: severe frame drops, 42.1 s encode time
+
CPU-bound: 30.1 s encode time
@@ -566,7 +568,7 @@
GPU silicon & VRAMWhy NVDEC is essential:
- Path 1 moved less data over PCIe (~19.7 GB vs ~64.4 GB in Path 2), but decoding 1080p60 on the CPU held host cores at 91%. NVENC was starved for frames and the encode took 42.1 s. Path 2 restored NVDEC hardware decoding and cut wall time to 22.4 s.
+ Path 1 moved less data over PCIe (~19.7 GB vs ~64.4 GB in Path 2), but decoding 1080p60 on the CPU took 80% of all CPU threads. NVENC was starved for frames and the encode took 30.1 s. Path 2 restored NVDEC hardware decoding and cut wall time to 24.0 s.
@@ -599,12 +601,12 @@
System RAMDecoded 1080p frames (D2H)44.22 GB raw NV12
- 14,217 frames downloaded
+ 14,216 frames downloaded
CPU Lanczos filtergraphscale=-2:720 (libswscale)
- ~30–40% CPU utilization
+ Encode uses ~52% of the CPU
Scaled 720p frames (H2D)
@@ -635,7 +637,7 @@
PCIe 4.0 x16 busNVENC → disk (compressed bitstream)
-
Total PCIe volume: 64.41 GB (1.6 GB/s sustained)
+
Total PCIe volume: 64.41 GB (~2.7 GB/s over 24 s)
@@ -643,7 +645,7 @@
GPU silicon & VRAM
NVDEC decoder
- Active (~88% engine)
+ Active (~57% engine)Decodes into a VRAM surface
@@ -653,7 +655,7 @@
GPU silicon & VRAMNVENC encoder
- Active (~91% engine)
+ Active (~81% engine)Encodes the 720p stream from host RAM
@@ -663,7 +665,7 @@
GPU silicon & VRAMTrade-off:
- Moving decode to NVDEC removed the 91% CPU decode bottleneck of Path 1. But because scaling still ran in CPU software, the 44.22 GB decoded stream and the 19.65 GB scaled stream ping-ponged across PCIe.
+ Moving decode to NVDEC removed the CPU decode bottleneck of Path 1. But because scaling still ran in CPU software, the 44.22 GB decoded stream and the 19.65 GB scaled stream ping-ponged across PCIe.
@@ -704,7 +706,7 @@
System RAMNo pixel buffers allocated
-
Host footprint: < 15 MB RAM · < 3% CPU
+
Whole process tree: ~709 MB RAM · ~7% CPU
@@ -712,11 +714,11 @@
PCIe 4.0 x16 bus
1 · H2D inbound457.00 MB
- Compressed bitstream only (~1.9 MB/s)
+ Compressed bitstream only (~19 MB/s)
2 · D2H outbound88.50 MB
- Compressed bitstream only (~0.37 MB/s)
+ Compressed bitstream only (~3.7 MB/s)
PCIe bandwidth saved
@@ -746,7 +748,7 @@
GPU silicon & VRAMNo pixel transfer latency
-
Estimated ~15–18 s encode
+
Measured 23.8 s encode
@@ -763,7 +765,7 @@
GPU silicon & VRAM
4 · Benchmarks
Every version side by side
-
Same test clip: 1080p60, 236.95 s, 14,217 frames, 457.00 MB, NVIDIA GPU. Values marked est. are estimates, not measurements.
+
Same test clip: 1080p60, 236.95 s, 14,216 frames, 457.00 MB, RTX 4060 laptop with a Ryzen 7 7435HS. Release executables, mean of two runs; Current is v1.3.0-rc5. PCIe volumes are calculated, everything else is measured.
@@ -808,39 +810,39 @@
Every version side by side
0.55 GB (−99.1%)
-
System RAM I/O
-
> 200 GB
-
> 60 GB
-
~64 GB
-
< 1 GB
+
Peak process RAM
+
661 MB
+
964 MB
+
902 MB
+
709 MB
-
CPU utilization
-
43%
-
91% (NVENC starved)
-
~30–40%
-
< 5%
+
CPU, share of all threads
+
38%
+
80% (NVENC starved)
+
52%
+
7%
GPU decode engine
-
~88%
+
70%
0% (idle)
-
~88%
-
~88%
+
57%
+
56%
GPU 3D / CUDA engine
-
~91%
-
~4%
-
~5–10%
-
~35–50% (scale_cuda)
+
34%
+
15%
+
35%
+
21% (scale_cuda)
Wall-clock encode
-
37.81 s
-
23.22 s (CPU-bound)
-
22.4–23.0 s
-
~15–18 s (est.)
+
38.7 s
+
30.1 s (CPU-bound)
+
24.0 s
+
23.8 s
@@ -849,7 +851,7 @@
Every version side by side
Takeaway:
- The single-pass legacy hybrid (Path 2) halved PCIe traffic compared with v1.1.5 and cut wall-clock time from 37.8 s to 22.4 s by dropping the first pass and decoding on NVDEC. The zero-copy pipeline (Path 3) then removes a further 99.1% of PCIe traffic, down to 545 MB, and frees the host CPU and RAM almost entirely.
+ The single-pass legacy hybrid (Path 2) halved PCIe traffic compared with v1.1.5 and cut wall-clock time from 38.7 s to 24.0 s by dropping the first pass and decoding on NVDEC. The zero-copy pipeline (Path 3) then removes a further 99.1% of PCIe traffic, down to 545 MB, and cuts CPU use from 52% to 7%. It is not faster (23.8 s), because NVENC is now the limit.
The concat demuxer joins both halves in under a second and moves the index (moov box) to the front of the file so it can start playing before it fully downloads.
Both halves are encoded without audio. FFmpeg joins the video halves without re-encoding, takes the audio from the source in one piece (copied, or re-encoded to AAC when the audio rule says so), and moves the index (moov box) to the front of the file so it can start playing before it fully downloads.
-
- Known issue:
- the stitch currently leaves a 40–100 ms gap in video timestamps at T. Playback stutters briefly there and video runs slightly behind audio for the second half. A fix is planned for the next release; see Known Issues.
-
-
Show the full split flowchart
@@ -934,12 +932,522 @@
Further reading
+
+
+
+
+
Background · Decisions · Measurements
+
+ HDR, Color Depth and Codecs
+
+
+ These three properties of a video decide whether it can stay HDR, whether it can stay on the GPU, and how long compressing it takes. They are often mixed up, but each answers a different question.
+
+
+
+
+
+
Codec
+
How is it packed?
+
H.264, HEVC, AV1: the method that compresses the frames
+
+
+
Color depth
+
How fine are the steps?
+
8-bit or 10-bit: how many shades each channel can store
+
+
+
Dynamic range
+
What do they mean?
+
SDR or HDR: how bright and how saturated each value is
+
+
+
+
+
+
+
1 · Codec
+
The method that compresses the frames
+
A codec turns raw frames into a bitstream and back. It is not the file type: .mp4, .mkv and .mov are containers, and each can hold several codecs. Newer codecs need fewer bits for the same quality, but fewer devices can play or encode them.
+
+
+
+
+
+
+
Codec
+
Bitrate for similar quality
+
Plays on
+
10-bit GPU encoding
+
In Video-Compression
+
+
+
+
+
H.264 (AVC)
+
Baseline (100%)
+
Almost everything
+
Rare, and 10-bit H.264 rarely plays
+
Output for compatibility, always SDR when the source is HDR
+
+
+
HEVC (H.265)
+
Roughly 50–70%
+
Most devices from recent years
+
Common (Main 10)
+
Default output, can keep HDR
+
+
+
AV1
+
Roughly 40–60%
+
Newer devices only
+
Only on the newest GPUs
+
Input only
+
+
+
+
+
+
+ Why it matters here:
+ At a fixed file size, a more efficient codec means better quality. That is why HEVC is the default. AV1 is not offered as an output because too few GPUs can encode it and too few devices can play it.
+
+
+
+
+
+
+
2 · Color depth
+
How many steps exist between black and white
+
More bits do not make a video brighter or more colorful. They make the steps between neighboring shades smaller, so smooth skies and glows do not break into visible bands.
+
+
+
+
+ 8-bit
+ 256 levels · 16.7 million colors
+
+
+
A raw 4K frame takes 12.4 MB (NV12).
+
+
+
+ 10-bit
+ 1,024 levels · 1.07 billion colors
+
+
+
A raw 4K frame takes 24.9 MB (P010).
+
+
+
The bands are exaggerated (12 steps against 48, the same 1:4 ratio) so the difference shows on any screen.
+
+ Why it matters here:
+ Converting 8-bit to 10-bit cannot bring back shades that were never recorded. The output therefore matches the source: 10-bit HDR stays 10-bit, and 8-bit HDR stays 8-bit.
+
+
+
+
+
+
+
3 · Dynamic range
+
What the stored numbers mean
+
A pixel only stores numbers. Color tags tell the player how to turn them into light. The transfer function maps a number to brightness, and the primaries say which red, green and blue are meant. Read HDR numbers as SDR and the picture looks gray and washed out.
+
+
+
+
+
+
+
Property
+
SDRBT.709
+
HDR10PQ
+
HLGHybrid Log-Gamma
+
+
+
+
+
Brightness
+
Mastered for about 100 nits
+
Absolute, up to 10,000 nits
+
Relative to the display, typically 1,000 nits
+
+
+
Color gamut
+
BT.709
+
BT.2020
+
BT.2020
+
+
+
Usual color depth
+
8-bit
+
10-bit
+
10-bit
+
+
+
Often comes from
+
Screen recordings, the web
+
Game capture, films
+
Phones, cameras, broadcast
+
+
+
Transfer tag the app reads
+
bt709 or none
+
smpte2084
+
arib-std-b67
+
+
+
+
+
+
+ HDR is not the same as 10-bit:
+ 10-bit SDR and 8-bit HDR both exist. HDR is usually 10-bit because spreading 8 bits over such a wide range shows banding, but it is the transfer tag that makes a video HDR.
+
+
+
+
+
+
+
4 · Putting them together
+
What happens to your video
+
The app reads the transfer tag (from the first frame, or from the container if the frame has none) and the pixel format, then combines them with the output codec and the encoder that is available.
+
+
+
+
+
+
+
Source
+
Output codec
+
Result
+
Where frames are processed
+
Reason
+
+
+
+
+
SDR
+
HEVC or H.264
+
SDR
+
GPU when supported
+
Nothing to convert
+
+
+
HDR 10-bit
+
HEVC, GPU encoder
+
HDR 10-bit (Main 10)
+
GPU when supported
+
HEVC encoders handle 10-bit, so only the tags need carrying over
+
+
+
HDR 8-bit
+
HEVC, GPU encoder
+
HDR 8-bit (Main)
+
GPU when supported
+
Depth follows the source
+
+
+
HDR, any depth
+
H.264
+
SDR 8-bit
+
CPU tone mapping
+
H.264 is picked for compatibility, and HDR H.264 plays wrong on most devices
+
+
+
HDR, any depth
+
HEVC, CPU encoder
+
SDR 8-bit
+
CPU
+
The bundled x265 is 8-bit on Linux and macOS
+
+
+
+
+
+
+
+
+
+
+
5 · Tone mapping
+
How HDR becomes SDR
+
Tone mapping squeezes a very wide brightness range into SDR while keeping detail in the highlights. It works on every pixel of every frame in floating point, after any downscale so that there are fewer pixels to process.
+
+
+
+
+
Step 1 · Linearize
+
Numbers to light
+
zscale=t=linear:npl=100
+format=gbrpf32le
+
Undo the HDR transfer so the math works on real light, with 1.0 meaning 100 nits.
+
+
+
Step 2 · Gamut
+
BT.2020 to BT.709
+
zscale=p=bt709
+
Express each color with the narrower SDR primaries. Without this step colors look faded.
+
+
+
Step 3 · Compress range
+
Hable curve
+
tonemap=hable:desat=0
+
Roll off highlights smoothly instead of clipping them to flat white.
+
+
+
Step 4 · Re-encode
+
Light to SDR numbers
+
zscale=t=bt709:m=bt709:r=tv
+
Apply the SDR curve, tag the result BT.709 and hand it to the encoder.
+
+
+
+
+ Two adjustments to step 1:
+ HLG adds agamma=0, because zscale's faster default applies HLG's system gamma to each channel separately and shifts saturated colors. The exact math makes HLG conversion 1.3–1.5 times slower at 4K60, and HDR10 does not need it. When the frames lack color tags, the transfer comes from the container and BT.2020 is assumed for primaries and matrix, as both HDR formats specify. Dolby Vision profile 5 carries no HDR transfer tag, so it is not recognized as HDR.
+
+
+
+ Why tone mapping runs on the CPU
+
+
FFmpeg has no CUDA tone-mapping filter, so there is no equivalent of scale_cuda for this step. These alternatives were prototyped with plain FFmpeg on an RTX 4060 laptop (video only, one encode at a time):
+
+
+
+
+
Method, 8.5 s 4K60 HDR10
+
Time
+
CPU
+
Catch
+
+
+
+
+
zscale and tonemap (shipped)
+
26.1 s
+
72%
+
Uses the CPU, works on every platform
+
+
+
libplacebo on Vulkan
+
8.3 s
+
7%
+
Adds a Vulkan renderer and shader compiler to every build, still needs a CPU fallback, and zero-copy from CUDA failed
+
+
+
tonemap_opencl
+
7.7 s
+
14%
+
Brighter, warmer picture and the wrong output range
+
+
+
+
+
tonemap_vaapi was also tried on an Intel iGPU. It refuses videos without mastering display metadata, which game recordings often lack.
+
Only HDR sources saved as H.264, or encoded without a GPU, need this step. That is too narrow a gain for the extra size and upkeep, so it stays on the CPU.
+
+
+
+
+
+
+
+
6 · Benchmarks
+
What each decision costs
+
v1.3.0-rc5 release executables on an RTX 4060 laptop with a Ryzen 7 7435HS. Mean of two runs. CPU is the encode's average share of all 16 threads.
+
+
+
+
+ Keeping HDR against converting it to SDR
+
+
+
+
+
+
Source and target
+
Output
+
Time
+
CPU
+
Size
+
+
+
+
+
HDR10 HEVC 4K60, 8.5 s20 MB, stays 4K
+
HEVC, HDR kept
+
8.5 s
+
2%
+
16.12 MB
+
+
+
H.264, to SDR
+
31.0 s
+
72%
+
16.50 MB
+
+
+
HDR10 HEVC 4K60, 12 s20 MB, scaled to 1440p
+
HEVC, HDR kept
+
6.2 s
+
3%
+
17.20 MB
+
+
+
H.264, to SDR
+
21.4 s
+
72%
+
16.73 MB
+
+
+
HDR10 AV1 720p60, 17 s5 MB, stays 720p
+
HEVC, HDR kept
+
3.9 s
+
3%
+
4.64 MB
+
+
+
H.264, to SDR
+
9.3 s
+
52%
+
4.53 MB
+
+
+
+
+
+
+
+
+ Against v1.2.0, HEVC
+ 110 MB: mean of two runs. 20 MB: one run.
+
+
+
+
+
+
SDR source and target
+
Version
+
Time
+
Size
+
Video bitrate
+
Gap at split
+
+
+
+
+
4K60, 170 s110 MB, audio copied
+
v1.2.0
+
41.8 s
+
99.57 MB
+
4,693 kbps
+
43 ms
+
+
+
v1.3.0-rc5
+
42.3 s
+
99.53 MB
+
4,691 kbps
+
none
+
+
+
4K, variable rate, 183 s110 MB, audio copied
+
v1.2.0
+
42.3 s
+
99.61 MB
+
4,337 kbps
+
486 ms
+
+
+
v1.3.0-rc5
+
42.9 s
+
99.62 MB
+
4,348 kbps
+
none
+
+
+
4K, variable rate, 183 s20 MB, audio re-encoded
+
v1.2.0
+
42.2 s
+
18.51 MB
+
639 kbps
+
486 ms
+
+
+
v1.3.0-rc5
+
46.4 s
+
18.48 MB
+
703 kbps (+10%)
+
none
+
+
+
+
+
+
+
+ Takeaway:
+ Keeping HDR costs almost no CPU. Converting HDR10 is 2–4 times slower (HLG more) and uses most of the CPU, so choose HEVC for HDR videos unless the viewer needs H.264. Audio is copied unless it is lossless or takes over 10% of a small target (and is above 160 kbps). Then it becomes 128 kbps AAC and the video gets the saved bits, for about 4 extra seconds on a 3-minute clip.
+
+
+
+ Further reading
+ Explainers, from the basics to tone curves
+
- By dividing the video at a calculated keyframe and utilizing Python's threading to run multiple FFmpeg subprocesses simultaneously, the tool significantly reduces encoding times on modern multi-core systems and hardware encoders.
+ By dividing the video at a calculated keyframe and utilizing Python's threading to run multiple FFmpeg subprocesses simultaneously, the tool significantly reduces encoding times on hardware encoders. CPU encoders run as one process.
@@ -951,7 +1459,7 @@
Parallel Split Encoding
-
Hardware encoders execute a dual-worker parallel split pipeline with on-chip rate control and hardware lookahead for maximum speed and bitrate compliance.
+
Hardware encoders execute a dual-worker parallel split pipeline with on-chip rate control, plus lookahead or pre-analysis on NVENC, AMF and QSV.
The input codec decides where decoding runs. The color, output codec and available encoder decide everything after that. Find your input in the first table, then follow its row in the second.
+
GPU is hardware accelerated, CPU is software, GPU or CPU depends on the hardware.
+
+
+
+
+ 1. Where the input is decoded
+ Needs a GPU that supports the format
+
+
+
+
+
+
Input video
+
NVIDIATested on RTX 4060
+
AMD and IntelTested on UHD 630, Linux
+
AppleNot tested
+
No GPU
+
+
+
+
+
H.2648-bit 4:2:0
+
GPU
+
GPU
+
GPU
+
CPU
+
+
+
H.26410-bit or 4:2:2
+
CPUOn most GPUs
+
CPUOn most GPUs
+
CPUOn most Macs
+
CPU
+
+
+
HEVC8-bit or 10-bit 4:2:0
+
GPU
+
GPU
+
GPU
+
CPU
+
+
+
HEVC4:2:2
+
CPUOn most GPUs
+
CPUOn most GPUs
+
GPU or CPUDepends on the Mac
+
CPU
+
+
+
AV18-bit or 10-bit
+
GPURTX 30 or newer, else CPU
+
GPURX 6000 or 11th Gen+, else CPU
+
GPUM3 or newer, else CPU
+
CPU
+
+
+
VP9, MPEG-4Any depth
+
CPU
+
CPU
+
CPU
+
CPU
+
+
+
+
+
+
+
+
+ 2. What happens after that
+ Scaling only runs when the target size needs it
+
+
+
+
+
+
Input
+
Output
+
GPU encoder
+
Decode
+
Scale
+
HDR to SDR
+
Encode
+
Result
+
+
+
+
+
SDR 8-bitAny input codec
+
HEVC
+
Yes
+
GPU or CPUSee the table above
+
GPU
+
None
+
GPU, 2 parts
+
SDR 8-bit
+
+
+
No
+
CPU
+
CPU
+
None
+
CPU, 1 part
+
SDR 8-bit
+
+
+
H.264
+
Yes
+
GPU or CPUSee the table above
+
GPU
+
None
+
GPU, 2 parts
+
SDR 8-bit
+
+
+
No
+
CPU
+
CPU
+
None
+
CPU, 1 part
+
SDR 8-bit
+
+
+
SDR 10-bitAny input codec
+
HEVC
+
Yes
+
GPU or CPUSee the table above
+
GPU
+
None
+
GPU, 2 parts
+
SDR 8-bit10-bit on NVENC if not scaled
+
+
+
No
+
CPU
+
CPU
+
None
+
CPU, 1 part
+
SDR 10-bit on Windows8-bit on Linux and macOS
+
+
+
H.264
+
Yes
+
GPU or CPUSee the table above
+
GPU
+
None
+
GPU, 2 parts
+
SDR 8-bit
+
+
+
No
+
CPU
+
CPU
+
None
+
CPU, 1 part
+
SDR 8-bit
+
+
+
HDR 8-bitHDR10 or HLG
+
HEVC
+
Yes
+
GPU or CPUSee the table above
+
GPU
+
None
+
GPU, 2 parts
+
HDR 8-bit
+
+
+
No
+
CPU
+
CPU
+
CPU
+
CPU, 1 part
+
SDR 8-bit
+
+
+
H.264
+
Yes
+
GPU or CPUAlways CPU on VA-API
+
CPU
+
CPU
+
GPU, 2 parts
+
SDR 8-bit
+
+
+
No
+
CPU
+
CPU
+
CPU
+
CPU, 1 part
+
SDR 8-bit
+
+
+
HDR 10-bitHDR10 or HLG
+
HEVC
+
Yes
+
GPU or CPUSee the table above
+
GPU
+
None
+
GPU, 2 parts
+
HDR 10-bit
+
+
+
No
+
CPU
+
CPU
+
CPU
+
CPU, 1 part
+
SDR 8-bit
+
+
+
H.264
+
Yes
+
GPU or CPUAlways CPU on VA-API
+
CPU
+
CPU
+
GPU, 2 parts
+
SDR 8-bit
+
+
+
No
+
CPU
+
CPU
+
CPU
+
CPU, 1 part
+
SDR 8-bit
+
+
+
+
+
+
+
+ The rule to remember:
+ HDR survives only as HEVC from a GPU encoder. Every other HDR path is converted to SDR on the CPU, even when a GPU does the encoding. See why.
+
+
+
+ Exceptions and how this was tested
+
+
Pipeline names: when decoding, scaling and encoding all run on the GPU the app calls it zero-copy. CPU decoding followed by GPU work is upload. On NVENC without scaling, the app can show zero-copy although the CPU decoded.
+
Failed GPU pipeline: the app retries once with legacy, which scales on the CPU except on NVENC. It does not switch to a CPU encoder, and HDR to SDR has no retry.
+
Very wide videos: an encode that stays wider than the GPU encoder supports fails. For most H.264 encoders that is 4,096 pixels, and some older GPUs have a similar limit for HEVC.
+
10-bit SDR: NVENC keeps 10-bit only for unscaled 4:2:0 HEVC, and VideoToolbox follows the decoded frames. The bundled x265 is 10-bit capable only on Windows.
+
4:2:2 color: output is 4:2:0, except HEVC on the CPU encoder, which keeps SDR sources in 4:2:2.
+
HDR detection: only the PQ and HLG transfer tags count. Untagged HDR and Dolby Vision profile 5 are treated as SDR.
+
Tested: 464 real encodes with the bundled FFmpeg n9.1. They cover 29 inputs (H.264, HEVC, AV1, VP9 and MPEG-4 in SDR, HDR10 and HLG), both output codecs, scaled and unscaled, on NVENC (RTX 4060, Windows), VA-API (Intel UHD 630, Linux) and both CPU encoders. AMF, QSV and VideoToolbox rows follow the code and vendor support, and were not run.
+
+
+
@@ -1043,7 +1808,7 @@
Logic Candidates
Hardware Priority Matrix
- The tool uses a dynamic fallback chain. It tests hardware availability with a dummy encode and selects the fastest valid encoder before falling back to CPU-based rendering. Select an OS to view its priority mapping.
+ The tool uses a dynamic fallback chain. It tests hardware availability with a dummy encode in a fixed order and uses the first encoder that works, falling back to the CPU last. Select an OS to view its priority mapping.
diff --git a/docs/styles.css b/docs/styles.css
index cb918fa..ef1b7ec 100644
--- a/docs/styles.css
+++ b/docs/styles.css
@@ -492,7 +492,9 @@ body {
font-weight: 600;
white-space: nowrap;
}
-.df-table td { font-family: 'JetBrains Mono', monospace; color: #cbd5e1; white-space: nowrap; }
+.df-table td { font-family: 'JetBrains Mono', monospace; white-space: nowrap; }
+/* Zero specificity, so text color utilities on a cell win. */
+:where(.df-table td) { color: #cbd5e1; }
.df-table .df-col-current {
background: rgba(6, 78, 59, 0.22);
box-shadow: inset 1px 0 0 rgba(16, 185, 129, 0.35), inset -1px 0 0 rgba(16, 185, 129, 0.35);
@@ -636,3 +638,25 @@ body {
height: auto !important;
}
+/* HDR & Color section: prose tables, banding illustration, CPU meters */
+.df-table.df-table-text td { font-family: inherit; white-space: normal; min-width: 9rem; line-height: 1.5; }
+.df-ramp { height: 3rem; border-radius: 0.375rem; }
+.df-ramp-coarse {
+ background: repeating-linear-gradient(90deg, rgba(2, 6, 23, 0.35) 0 calc(100% / 24), transparent 0 calc(100% / 12)),
+ linear-gradient(90deg, #0b1230, #3b82f6, #fde68a);
+}
+.df-ramp-fine {
+ background: repeating-linear-gradient(90deg, rgba(2, 6, 23, 0.1) 0 calc(100% / 96), transparent 0 calc(100% / 48)),
+ linear-gradient(90deg, #0b1230, #3b82f6, #fde68a);
+}
+.df-meter {
+ display: inline-block;
+ width: 5rem;
+ height: 0.5rem;
+ margin-right: 0.5rem;
+ border-radius: 999px;
+ background: rgba(148, 163, 184, 0.2);
+ overflow: hidden;
+ vertical-align: middle;
+}
+.df-meter > span { display: block; height: 100%; min-width: 2px; }
diff --git a/installer/windows.iss b/installer/windows.iss
new file mode 100644
index 0000000..6224972
--- /dev/null
+++ b/installer/windows.iss
@@ -0,0 +1,155 @@
+; Windows installer: adds a "Video-Compression" submenu to the right-click menu of video files.
+;
+; Build (from the repository root, after `python build.py`):
+; iscc /DAppVersion=1.3.0 /DSourceExe=..\dist\100mb-hevc-win64-v1.3.0.exe installer\windows.iss
+; (relative paths resolve from this folder)
+;
+; Installs per user (no admin prompt). The menu lives in the classic menu
+; (Shift + right-click, or "Show more options" on Windows 11); the modern
+; Windows 11 menu needs a signed package and is not used.
+;
+; Codec: asked on a wizard page, which starts on the previous install's choice.
+; Silent installs (WinGet) keep that choice, or use HEVC on a first install,
+; unless `/CODEC=hevc` or `/CODEC=h264` is passed. Reinstall to change it.
+
+#ifndef AppVersion
+ #error Pass /DAppVersion=
+#endif
+#ifndef SourceExe
+ #error Pass /DSourceExe=
+#endif
+
+#ifndef NumericVersion
+ ; File version resources only accept numbers; branch builds have none.
+ #define NumericVersion "0.0.0"
+#endif
+
+#define AppName "Video-Compression"
+#define AppUrl "https://github.com/SimpNick6703/Video-Compression"
+#define HdrInfoUrl "https://simpnick6703.github.io/Video-Compression/#sec-color-decisions"
+; Submenu entries live in one shared key; each extension's menu entry points at it.
+#define MenuKey "Software\Classes\VideoCompression.Menu"
+; Explorer ignores the perceived-type key (SystemFileAssociations\video) when another
+; app (e.g. VLC) owns the extension, so the menu is registered per extension.
+#dim Exts[8] {".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v", ".flv", ".3gp"}
+; v1.3.0-rc1 and rc2 also registered these, which the bundled FFmpeg cannot read.
+#dim RemovedExts[6] {".wmv", ".ts", ".mts", ".m2ts", ".mpg", ".mpeg"}
+#define i 0
+
+[Setup]
+AppId={{004B68D8-64A4-46FA-8982-4B69DF87D66F}
+AppName={#AppName}
+AppVersion={#AppVersion}
+AppPublisher=SimpNick6703
+AppCopyright=Copyright (c) 2026 SimpNick6703. Licensed under GPL-3.0-or-later.
+VersionInfoVersion={#NumericVersion}
+AppPublisherURL={#AppUrl}
+AppSupportURL={#AppUrl}/issues
+AppUpdatesURL={#AppUrl}/releases
+DefaultDirName={autopf}\{#AppName}
+DisableProgramGroupPage=yes
+DisableDirPage=yes
+PrivilegesRequired=lowest
+ArchitecturesAllowed=x64compatible
+ArchitecturesInstallIn64BitMode=x64compatible
+LicenseFile=..\LICENSE
+OutputDir=..\dist
+OutputBaseFilename=VideoCompression-Setup-win64-{#AppVersion}
+UninstallDisplayIcon={app}\videocompress.exe
+Compression=lzma2/max
+SolidCompression=yes
+ChangesAssociations=yes
+
+[Files]
+Source: "{#SourceExe}"; DestDir: "{app}"; DestName: "videocompress.exe"; Flags: ignoreversion
+Source: "..\LICENSE"; DestDir: "{app}"; Flags: ignoreversion
+Source: "..\dist\THIRD_PARTY_NOTICES-win64.txt"; DestDir: "{app}"; Flags: ignoreversion
+
+[Registry]
+#sub ExtEntry
+ #define ExtKey "Software\Classes\SystemFileAssociations\" + Exts[i]
+Root: HKA; Subkey: "{#ExtKey}"; Flags: uninsdeletekeyifempty
+Root: HKA; Subkey: "{#ExtKey}\shell"; Flags: uninsdeletekeyifempty
+Root: HKA; Subkey: "{#ExtKey}\shell\VideoCompression"; ValueType: string; ValueName: "MUIVerb"; ValueData: "{#AppName}"; Flags: uninsdeletekey
+Root: HKA; Subkey: "{#ExtKey}\shell\VideoCompression"; ValueType: string; ValueName: "Icon"; ValueData: "{app}\videocompress.exe,0"
+Root: HKA; Subkey: "{#ExtKey}\shell\VideoCompression"; ValueType: string; ValueName: "ExtendedSubCommandsKey"; ValueData: "VideoCompression.Menu"
+#endsub
+#for {i = 0; i < DimOf(Exts); i++} ExtEntry
+#sub RemovedExtEntry
+Root: HKA; Subkey: "Software\Classes\SystemFileAssociations\{#RemovedExts[i]}\shell\VideoCompression"; ValueType: none; Flags: deletekey
+#endsub
+#for {i = 0; i < DimOf(RemovedExts); i++} RemovedExtEntry
+Root: HKA; Subkey: "{#MenuKey}"; Flags: uninsdeletekey
+; Entries are listed in key-name order, hence the number prefixes.
+Root: HKA; Subkey: "{#MenuKey}\shell\1_20mb"; ValueType: string; ValueName: "MUIVerb"; ValueData: "Compress to 20 MB"
+Root: HKA; Subkey: "{#MenuKey}\shell\1_20mb\command"; ValueType: string; ValueData: """{app}\videocompress.exe"" ""%1"" 20 {code:GetCodec}"
+Root: HKA; Subkey: "{#MenuKey}\shell\2_50mb"; ValueType: string; ValueName: "MUIVerb"; ValueData: "Compress to 50 MB"
+Root: HKA; Subkey: "{#MenuKey}\shell\2_50mb\command"; ValueType: string; ValueData: """{app}\videocompress.exe"" ""%1"" 50 {code:GetCodec}"
+Root: HKA; Subkey: "{#MenuKey}\shell\3_100mb"; ValueType: string; ValueName: "MUIVerb"; ValueData: "Compress to 100 MB"
+Root: HKA; Subkey: "{#MenuKey}\shell\3_100mb\command"; ValueType: string; ValueData: """{app}\videocompress.exe"" ""%1"" 100 {code:GetCodec}"
+Root: HKA; Subkey: "{#MenuKey}\shell\4_1gb"; ValueType: string; ValueName: "MUIVerb"; ValueData: "Compress to 1 GB"
+Root: HKA; Subkey: "{#MenuKey}\shell\4_1gb\command"; ValueType: string; ValueData: """{app}\videocompress.exe"" ""%1"" 1024 {code:GetCodec}"
+Root: HKA; Subkey: "{#MenuKey}\shell\5_custom"; ValueType: string; ValueName: "MUIVerb"; ValueData: "Compress to Custom..."
+Root: HKA; Subkey: "{#MenuKey}\shell\5_custom\command"; ValueType: string; ValueData: """{app}\videocompress.exe"" ""%1"" --custom {code:GetCodec}"
+
+[Code]
+var
+ CodecPage: TInputOptionWizardPage;
+
+procedure OpenLink(Sender: TObject; const Link: string; LinkType: TSysLinkType);
+var
+ ErrorCode: Integer;
+begin
+ if not ShellExecAsOriginalUser('open', Link, '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode) then
+ MsgBox('Could not open the link. Visit:' + #13#10 + Link, mbInformation, MB_OK);
+end;
+
+procedure AddHdrNote;
+var
+ Note: TNewLinkLabel;
+begin
+ { The option list fills the page by default, so shrink it to make room. }
+ CodecPage.CheckListBox.Height := ScaleY(56);
+ Note := TNewLinkLabel.Create(CodecPage);
+ Note.AutoSize := False;
+ Note.Left := CodecPage.CheckListBox.Left;
+ Note.Top := CodecPage.CheckListBox.Top + CodecPage.CheckListBox.Height + ScaleY(8);
+ Note.Width := CodecPage.CheckListBox.Width;
+ Note.Caption :=
+ 'Note: H.264 output is never HDR. HDR videos are always converted to SDR on the CPU, ' +
+ 'even if you have a GPU, which is slower. Choose HEVC to keep HDR (needs a GPU encoder). ' +
+ 'Learn more in the Architecture Explorer';
+ Note.OnLinkClick := @OpenLink;
+ Note.Parent := CodecPage.Surface;
+ Note.TabStop := True; { keyboard access to the link }
+ Note.AdjustHeight;
+end;
+
+procedure InitializeWizard;
+begin
+ CodecPage := CreateInputOptionPage(wpLicense,
+ 'Video codec', 'Which codec should the right-click menu use?',
+ 'HEVC gives better quality at the same size. Choose H.264 if the videos must play on older devices or browsers. Reinstall to change this later.',
+ True, False);
+ CodecPage.Add('HEVC (H.265), recommended');
+ CodecPage.Add('H.264');
+ { /CODEC wins, then the choice stored by the previous install (kept in its uninstall key). }
+ if CompareText(ExpandConstant('{param:CODEC|' + GetPreviousData('Codec', 'hevc') + '}'), 'h264') = 0 then
+ CodecPage.SelectedValueIndex := 1
+ else
+ CodecPage.SelectedValueIndex := 0;
+ AddHdrNote;
+end;
+
+function GetCodec(Param: string): string;
+begin
+ if CodecPage.SelectedValueIndex = 1 then
+ Result := 'h264'
+ else
+ Result := 'hevc';
+end;
+
+procedure RegisterPreviousData(PreviousDataKey: Integer);
+begin
+ SetPreviousData(PreviousDataKey, 'Codec', GetCodec(''));
+end;
diff --git a/pyproject.toml b/pyproject.toml
index 448146a..2db0439 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,6 +41,9 @@ Releases = "https://github.com/SimpNick6703/Video-Compression/releases"
build = ["pyinstaller>=6.0"]
dev = ["pytest>=8.0", "psutil>=5.9", "ruff>=0.17,<0.18"]
+[tool.setuptools.packages.find]
+include = ["videocompress*"]
+
[tool.setuptools_scm]
fallback_version = "1.2.0"
diff --git a/tests/test_audio.py b/tests/test_audio.py
new file mode 100644
index 0000000..09a7c43
--- /dev/null
+++ b/tests/test_audio.py
@@ -0,0 +1,118 @@
+"""Audio: copy by default, re-encode lossless or over-budget tracks and give the saved bits to the video."""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import List
+
+import pytest
+
+from videocompress import core, encode
+
+
+@pytest.fixture
+def ffmpeg_codecs(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(core, "check_audio_encoder_available", lambda encoder_name="aac": True)
+ monkeypatch.setattr(core, "check_audio_decoder_available", lambda codec: codec not in ("alac", "mp2"))
+
+
+@pytest.mark.parametrize(
+ ("codec", "kbps", "target_mb", "duration", "expected"),
+ [
+ ("aac", 192, 110, 183, (192, False)), # 4% of the target
+ ("aac", 192, 20, 183, (128, True)), # 21% of the target
+ ("ac3", 384, 110, 183, (384, False)), # 8%: surround survives
+ ("aac", 160, 8, 183, (160, False)), # over 10%, but too little to save
+ ("pcm_s16le", 1536, 1024, 60, (128, True)), # lossless, however small a share
+ ("flac", 900, 1024, 60, (128, True)),
+ ("alac", 1461, 5, 24, (1461, False)), # no decoder: copy at the real bitrate
+ ("mp2", 384, 5, 24, (384, False)),
+ ("", 0, 100, 60, (0, False)),
+ ],
+)
+def test_plan_audio(
+ ffmpeg_codecs: None, codec: str, kbps: int, target_mb: float, duration: float, expected: tuple
+) -> None:
+ assert core.plan_audio(codec, kbps, target_mb, duration) == expected
+
+
+def test_plan_audio_copies_without_an_aac_encoder(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(core, "check_audio_encoder_available", lambda encoder_name="aac": False)
+ assert core.plan_audio("flac", 900, 5, 60) == (900, False)
+
+
+@pytest.mark.parametrize(
+ ("codec", "expected"),
+ [("flac", True), ("aac", True), ("alac", False), ("pcm_s16be", False), ("missing", False)],
+)
+def test_check_audio_decoder_available_parses_listing(
+ monkeypatch: pytest.MonkeyPatch, codec: str, expected: bool
+) -> None:
+ listing = " DEA.L. aac AAC\n D.AI.S flac FLAC\n ..AI.S alac ALAC\n ..AI.S pcm_s16be PCM\n"
+ monkeypatch.setattr(core.subprocess, "run", lambda *a, **k: SimpleNamespace(stdout=listing))
+ assert core.check_audio_decoder_available(codec) is expected
+
+
+def test_estimate_bitrate_from_packets() -> None:
+ packets = [(i * 0.02, 500) for i in range(100)]
+ assert core.estimate_bitrate(packets) == pytest.approx(200_000, abs=1)
+ assert core.estimate_bitrate(list(reversed(packets))) == pytest.approx(200_000, abs=1)
+
+
+@pytest.mark.parametrize("packets", [[], [(0.0, 500)], [(1.0, 500), (1.0, 500)]])
+def test_estimate_bitrate_needs_a_time_span(packets: list) -> None:
+ assert core.estimate_bitrate(packets) == 0
+
+
+@pytest.mark.parametrize(
+ ("packets", "expected_kbps"),
+ [
+ ([{"pts_time": str(i / 8), "size": "16000"} for i in range(9)], 1024),
+ ([], 128),
+ ],
+)
+def test_video_info_measures_audio_without_reported_bitrate(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, packets: list, expected_kbps: int
+) -> None:
+ source = tmp_path / "in.mkv"
+ source.write_bytes(b"x")
+
+ def fake_probe(cmd: List[str], **kwargs: object) -> str:
+ if "packet=pts_time,size" in cmd:
+ return json.dumps({"packets": packets})
+ if "a:0" in cmd:
+ return json.dumps({"streams": [{"codec_name": "flac"}]})
+ return json.dumps(
+ {"streams": [{"width": 1920, "height": 1080, "avg_frame_rate": "60/1"}], "format": {"duration": "10"}}
+ )
+
+ monkeypatch.setattr(core.subprocess, "check_output", fake_probe)
+ info = core.get_video_info(str(source))
+ assert info is not None
+ assert info[3] == expected_kbps
+ assert info[6] == "flac"
+
+
+def test_compress_video_budgets_the_output_audio(
+ ffmpeg_codecs: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ source, output = tmp_path / "in.mov", tmp_path / "out.mp4"
+ source.write_bytes(b"x")
+ seen: List[tuple] = []
+
+ def fake_split(**kwargs: object) -> tuple:
+ seen.append((kwargs["audio_kbps"], kwargs["reencode_audio"]))
+ output.write_bytes(b"encoded")
+ return True, ""
+
+ info = (10.0, 500 * 1024 * 1024, 60.0, 1536, 1920, 1080, "pcm_s16le")
+ monkeypatch.setattr(encode, "find_missing_runtime_library", lambda exe: None)
+ monkeypatch.setattr(encode, "get_video_info", lambda p: info)
+ monkeypatch.setattr(encode, "get_hdr_source", lambda p: None)
+ monkeypatch.setattr(encode, "select_best_encoder", lambda c: ("hevc_nvenc", [("hevc_nvenc", "selected")]))
+ monkeypatch.setattr(encode, "probe_pipeline_tier", lambda *a, **k: core.Tier.LEGACY)
+ monkeypatch.setattr(encode, "get_smart_split_point", lambda p, d: 5.0)
+ monkeypatch.setattr(encode, "_encode_hw_split", fake_split)
+
+ assert encode.compress_video(str(source), str(output), 20.0, "hevc")[0]
+ assert seen == [(128, True)]
diff --git a/tests/test_cancel.py b/tests/test_cancel.py
new file mode 100644
index 0000000..2eb9d79
--- /dev/null
+++ b/tests/test_cancel.py
@@ -0,0 +1,58 @@
+"""Ctrl+C exits 130 and leaves no partial output, on both encode paths."""
+
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import NoReturn
+
+import pytest
+
+from videocompress import cli, encode
+from videocompress.hwpipeline import Tier
+
+ENCODERS = ["libx265", "hevc_nvenc"]
+
+
+def cancel_encode(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, encoder: str, writes: bool) -> int:
+ """Run the CLI, press Ctrl+C while FFmpeg runs, return the exit code."""
+ source, output = tmp_path / "in.mp4", tmp_path / "out.mp4"
+ source.write_bytes(b"x")
+
+ def interrupted(*args: object, **kwargs: object) -> NoReturn:
+ if writes:
+ output.write_bytes(b"partial")
+ raise KeyboardInterrupt
+
+ finished = SimpleNamespace(poll=lambda: 0)
+ monkeypatch.setattr(encode, "get_video_info", lambda p: (10.0, 500 * 1024 * 1024, 60.0, 128, 1920, 1080, "aac"))
+ monkeypatch.setattr(encode, "get_hdr_source", lambda p: None)
+ monkeypatch.setattr(encode, "find_missing_runtime_library", lambda p: None)
+ monkeypatch.setattr(encode, "select_best_encoder", lambda c: (encoder, [(encoder, "selected")]))
+ monkeypatch.setattr(encode, "probe_pipeline_tier", lambda *a, **k: Tier.LEGACY)
+ monkeypatch.setattr(encode, "get_smart_split_point", lambda p, d: 5.0)
+ monkeypatch.setattr(encode, "check_bsf_available", lambda name: True)
+ monkeypatch.setattr(encode.subprocess, "Popen", lambda *a, **k: finished)
+ monkeypatch.setattr(encode.subprocess, "run", interrupted) # GPU: cancelled while stitching
+ monkeypatch.setattr(encode, "run_dual_progress", lambda *a, **k: True)
+ monkeypatch.setattr(encode, "run_single_progress", interrupted) # CPU: cancelled while encoding
+ monkeypatch.setattr(sys, "argv", ["videocompress", str(source), str(output)])
+ with pytest.raises(SystemExit) as exc:
+ cli.main()
+ return exc.value.code
+
+
+@pytest.mark.parametrize("encoder", ENCODERS)
+def test_cancel_exits_130_and_removes_partial_output(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, encoder: str
+) -> None:
+ assert cancel_encode(monkeypatch, tmp_path, encoder, writes=True) == 130
+ assert not (tmp_path / "out.mp4").exists()
+
+
+@pytest.mark.parametrize("encoder", ENCODERS)
+def test_cancel_keeps_a_file_ffmpeg_never_touched(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, encoder: str
+) -> None:
+ (tmp_path / "out.mp4").write_bytes(b"from an earlier run")
+ assert cancel_encode(monkeypatch, tmp_path, encoder, writes=False) == 130
+ assert (tmp_path / "out.mp4").read_bytes() == b"from an earlier run"
diff --git a/tests/test_cli_args.py b/tests/test_cli_args.py
new file mode 100644
index 0000000..7c610ee
--- /dev/null
+++ b/tests/test_cli_args.py
@@ -0,0 +1,69 @@
+"""Only names with a file extension are paths, whatever exists in the current folder."""
+
+import sys
+from pathlib import Path
+from typing import List, Optional, Tuple
+
+import pytest
+
+from videocompress import cli
+
+Parsed = Tuple[str, Optional[str], float, str]
+
+
+@pytest.fixture(autouse=True)
+def video_folder(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
+ """Run in a folder holding a video and items named like sizes."""
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "input.mp4").write_bytes(b"x")
+ for folder in ("20", "20.5", "100", "1.5e3", "Holiday", "clips.mp4"):
+ (tmp_path / folder).mkdir()
+ for file in ("50", "noext"):
+ (tmp_path / file).write_bytes(b"x")
+ return tmp_path
+
+
+def parse(monkeypatch: pytest.MonkeyPatch, args: List[str]) -> Parsed:
+ """Run the CLI with encoding stubbed out and return what it would encode."""
+ calls: List[Parsed] = []
+
+ def fake_compress(input_path: str, output_path: Optional[str], target_size_mb: float, codec_type: str) -> Tuple[bool, str]:
+ calls.append((input_path, output_path, target_size_mb, codec_type))
+ return True, "out.mp4"
+
+ monkeypatch.setattr(cli, "compress_video", fake_compress)
+ monkeypatch.setattr(sys, "argv", ["videocompress", *args])
+ cli.main()
+ return calls[0]
+
+
+@pytest.mark.parametrize("args, size", [
+ (["input.mp4", "20"], 20.0),
+ (["input.mp4", "50"], 50.0),
+ (["input.mp4", "20.5"], 20.5),
+ (["input.mp4", "1.5e3"], 1500.0),
+ (["hevc", "100", "input.mp4", "20", "hevc"], 20.0), # right-click menu
+ (["hevc", "20", "input.mp4"], 20.0), # preset executable
+])
+def test_a_size_is_never_a_path(monkeypatch: pytest.MonkeyPatch, args: List[str], size: float) -> None:
+ assert parse(monkeypatch, args) == ("input.mp4", None, size, "hevc")
+
+
+@pytest.mark.parametrize("name", ["20.mp4", "out.mp4", "clip.3gp", "clip.3g2", "OUT.MP4", "v1.2 final.mp4"])
+def test_a_name_with_an_extension_is_a_path(monkeypatch: pytest.MonkeyPatch, name: str) -> None:
+ assert parse(monkeypatch, ["input.mp4", name]) == ("input.mp4", name, 100.0, "hevc")
+
+
+def test_an_input_named_like_a_size_works_with_its_extension(monkeypatch: pytest.MonkeyPatch, video_folder: Path) -> None:
+ (video_folder / "20.mp4").write_bytes(b"x")
+ assert parse(monkeypatch, ["20.mp4", "50"]) == ("20.mp4", None, 50.0, "hevc")
+
+
+@pytest.mark.parametrize("name", ["Holiday", "clips.mp4", "noext", "./20", "newname", "0", "-5", "", "--help"])
+def test_an_incomplete_file_name_is_rejected(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], name: str
+) -> None:
+ with pytest.raises(SystemExit) as exc:
+ parse(monkeypatch, ["input.mp4", name])
+ assert exc.value.code == 1
+ assert "complete file name" in capsys.readouterr().err
diff --git a/tests/test_cli_custom.py b/tests/test_cli_custom.py
new file mode 100644
index 0000000..883f73a
--- /dev/null
+++ b/tests/test_cli_custom.py
@@ -0,0 +1,68 @@
+"""Tests for the interactive custom target size used by the Windows context menu."""
+
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional, Union
+
+import pytest
+
+from videocompress import cli
+
+Call = Dict[str, Union[str, float, None]]
+
+
+def run_cli(monkeypatch: pytest.MonkeyPatch, argv: List[str], answers: List[str]) -> Call:
+ calls: List[Call] = []
+ replies = iter(answers)
+
+ def fake_compress(input_path: str, output_path: Optional[str], target_size_mb: float, codec_type: str) -> tuple:
+ calls.append({"input": input_path, "output": output_path, "mb": target_size_mb, "codec": codec_type})
+ return True, "out.mp4"
+
+ def fake_input(prompt: str = "") -> str:
+ try:
+ return next(replies)
+ except StopIteration:
+ raise EOFError
+
+ monkeypatch.setattr(cli, "compress_video", fake_compress)
+ monkeypatch.setattr("builtins.input", fake_input)
+ monkeypatch.setattr(sys, "argv", ["videocompress", *argv])
+ cli.main()
+ return calls[0]
+
+
+def test_custom_prompts_for_size(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source = tmp_path / "clip.mp4"
+ source.write_bytes(b"x")
+ call = run_cli(monkeypatch, [str(source), "--custom", "hevc"], ["35"])
+ assert call == {"input": str(source), "output": None, "mb": 35.0, "codec": "hevc"}
+
+
+def test_custom_reprompts_until_valid(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source = tmp_path / "clip.mp4"
+ source.write_bytes(b"x")
+ call = run_cli(monkeypatch, [str(source), "--custom"], ["", "abc", "-5", "0", "12.5"])
+ assert call["mb"] == 12.5
+
+
+def test_custom_without_answer_exits(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source = tmp_path / "clip.mp4"
+ source.write_bytes(b"x")
+ with pytest.raises(SystemExit) as exc:
+ run_cli(monkeypatch, [str(source), "--custom"], [])
+ assert exc.value.code == 1
+
+
+def test_ctrl_c_at_the_prompt_exits_130(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source = tmp_path / "clip.mp4"
+ source.write_bytes(b"x")
+
+ def interrupted(prompt: str = "") -> str:
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr("builtins.input", interrupted)
+ monkeypatch.setattr(sys, "argv", ["videocompress", str(source), "--custom"])
+ with pytest.raises(SystemExit) as exc:
+ cli.main()
+ assert exc.value.code == 130
diff --git a/tests/test_concat.py b/tests/test_concat.py
index ebe9078..bd7952b 100644
--- a/tests/test_concat.py
+++ b/tests/test_concat.py
@@ -9,20 +9,40 @@
def test_concat_keeps_auto_convert_when_annexb_bsf_present() -> None:
- cmd = core.build_concat_cmd("ffmpeg", "list.txt", "out.mp4", annexb_available=True)
+ cmd = core.build_concat_cmd("ffmpeg", "list.txt", "out.mp4", annexb_available=True, source_path="in.mp4", audio_kbps=0)
assert "-auto_convert" not in cmd
assert cmd == [
"ffmpeg", "-hide_banner", "-v", "error", "-f", "concat", "-safe", "0", "-i", "list.txt",
- "-c", "copy", "-movflags", "+faststart", "-y", "out.mp4",
+ "-i", "in.mp4", "-map", "0:v:0", "-an",
+ "-c:v", "copy", "-movflags", "+faststart", "-y", "out.mp4",
]
def test_concat_disables_auto_convert_without_annexb_bsf() -> None:
- cmd = core.build_concat_cmd("ffmpeg", "list.txt", "out.mp4", annexb_available=False)
+ cmd = core.build_concat_cmd("ffmpeg", "list.txt", "out.mp4", annexb_available=False, source_path="in.mp4", audio_kbps=0)
assert cmd[cmd.index("-auto_convert") + 1] == "0"
assert cmd.index("-auto_convert") < cmd.index("-i")
+@pytest.mark.parametrize(
+ ("audio_kbps", "reencode", "expected_audio"),
+ [
+ (128, False, ["-map", "1:a:0?", "-c:a", "copy"]),
+ (128, True, ["-map", "1:a:0?", "-c:a", "aac", "-b:a", "128k", "-ac", "2"]),
+ (320, False, ["-map", "1:a:0?", "-c:a", "copy"]),
+ ],
+)
+def test_concat_takes_audio_from_source(audio_kbps: int, reencode: bool, expected_audio: list[str]) -> None:
+ # Split segments are video-only; audio comes from the source in one piece so no gap opens at the split.
+ cmd = core.build_concat_cmd(
+ "ffmpeg", "list.txt", "out.mp4", annexb_available=True, source_path="in.mp4",
+ audio_kbps=audio_kbps, reencode_audio=reencode,
+ )
+ start = cmd.index("0:v:0") + 1
+ assert cmd[start:start + len(expected_audio)] == expected_audio
+ assert cmd[cmd.index("-c:v") + 1] == "copy"
+
+
@pytest.mark.parametrize(
("listing", "expected"),
[
@@ -50,3 +70,37 @@ def boom(*args: object, **kwargs: object) -> None:
monkeypatch.setattr(core.subprocess, "run", boom)
assert core.check_bsf_available("h264_mp4toannexb") is False
core.check_bsf_available.cache_clear()
+
+
+def test_concat_list_pins_first_segment_duration() -> None:
+ # The first segment's reported duration includes its start offset, which can differ
+ # from the second segment's (a long-held first frame gave 0.47 s vs 0.02 s), so the
+ # list states the true length: the split time.
+ listing = core.build_concat_list("/tmp/a/p1.mp4", "/tmp/a/p2.mp4", 90.549689)
+ assert listing == "file '/tmp/a/p1.mp4'\nduration 90.549689\nfile '/tmp/a/p2.mp4'\n"
+
+
+@pytest.mark.parametrize(
+ ("listing", "expected"),
+ [
+ (" A....D aac AAC (Advanced Audio Coding)\n", True), # FFmpeg 9 flag layout
+ (" A..... aac AAC (Advanced Audio Coding)\n", True),
+ (" A....D aac_at AAC (AudioToolbox)\n", False),
+ (" V....D libx264 H.264\n", False),
+ ("", False),
+ ],
+)
+def test_check_audio_encoder_available_parses_listing(
+ monkeypatch: pytest.MonkeyPatch, listing: str, expected: bool
+) -> None:
+ monkeypatch.setattr(core.subprocess, "run", lambda *a, **k: SimpleNamespace(stdout=listing))
+ assert core.check_audio_encoder_available("aac") is expected
+
+
+def test_concat_list_escapes_single_quotes() -> None:
+ # A Windows user named O'Brien has a temp folder with a quote in it.
+ listing = core.build_concat_list(r"C:\Users\O'Brien\Temp\p1.mp4", "/tmp/it's/p2.mp4", 1.5)
+ assert listing == (
+ "file 'C:\\Users\\O'\\''Brien\\Temp\\p1.mp4'\nduration 1.500000\n"
+ "file '/tmp/it'\\''s/p2.mp4'\n"
+ )
diff --git a/tests/test_hdr.py b/tests/test_hdr.py
new file mode 100644
index 0000000..4970498
--- /dev/null
+++ b/tests/test_hdr.py
@@ -0,0 +1,179 @@
+"""HDR sources: hardware HEVC keeps HDR at the source bit depth, everything else is tone-mapped to SDR."""
+
+import json
+
+import pytest
+
+from videocompress import core
+from videocompress.core import probe_pipeline_tier
+from videocompress.core import is_high_bit_depth
+from videocompress.hwpipeline import BACKENDS, TONEMAP_FILTERS, HdrSource, Tier, build_video_args
+
+PQ = HdrSource("smpte2084", ten_bit=True)
+KEEP_PQ = (
+ "-profile:v", "main10",
+ "-color_primaries", "bt2020", "-color_trc", "smpte2084", "-colorspace", "bt2020nc",
+)
+SDR_TAGS = ("-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709")
+
+
+def test_nvenc_hevc_zero_copy_keeps_10_bit() -> None:
+ args = build_video_args(BACKENDS["nvenc"], Tier.ZERO_COPY, 2160, 1440, 60.0, 60.0, "hevc", hdr=PQ)
+ assert args.filters == ("scale_cuda=-2:1440:interp_algo=lanczos:format=p010",)
+ assert args.post_input == KEEP_PQ
+
+
+def test_upload_tier_uploads_p010() -> None:
+ args = build_video_args(BACKENDS["vaapi"], Tier.UPLOAD, 2160, 1440, 60.0, 60.0, "hevc", hdr=PQ)
+ assert args.filters == ("format=p010", "hwupload", "scale_vaapi=w=-2:h=1440:format=p010")
+
+
+def test_legacy_nvenc_keeps_10_bit() -> None:
+ args = build_video_args(BACKENDS["nvenc"], Tier.LEGACY, 2160, 1440, 60.0, 60.0, "hevc", hdr=PQ)
+ assert args.filters == ("scale_cuda=-2:1440:interp_algo=lanczos:format=p010",)
+ assert args.post_input == KEEP_PQ
+
+
+def test_hlg_transfer_is_kept() -> None:
+ args = build_video_args(BACKENDS["qsv"], Tier.ZERO_COPY, 2160, 2160, 60.0, 60.0, "hevc", hdr=HdrSource("arib-std-b67", ten_bit=True))
+ assert args.post_input[-3] == "arib-std-b67"
+
+
+def test_h264_on_nvenc_is_tone_mapped_on_cpu() -> None:
+ args = build_video_args(BACKENDS["nvenc"], Tier.ZERO_COPY, 2160, 720, 60.0, 30.0, "h264", hdr=PQ)
+ assert args.pre_input == ("-hwaccel", "cuda")
+ assert args.filters == ("fps=30.0", "scale=-2:720:flags=lanczos", *TONEMAP_FILTERS, "format=nv12")
+ assert args.post_input == SDR_TAGS
+
+
+def test_h264_on_vaapi_uploads_after_tone_mapping() -> None:
+ args = build_video_args(BACKENDS["vaapi"], Tier.ZERO_COPY, 2160, 2160, 60.0, 60.0, "h264", "/dev/dri/renderD128", PQ)
+ assert args.filters[-2:] == ("format=nv12", "hwupload")
+ assert args.pre_input[0] == "-init_hw_device"
+
+
+def test_cpu_hevc_is_tone_mapped() -> None:
+ args = build_video_args(None, Tier.LEGACY, 2160, 2160, 60.0, 60.0, "hevc", hdr=PQ)
+ assert args.filters == (*TONEMAP_FILTERS, "format=yuv420p")
+
+
+def test_sdr_is_unchanged() -> None:
+ sdr = build_video_args(BACKENDS["nvenc"], Tier.ZERO_COPY, 1080, 720, 60.0, 60.0, "hevc")
+ assert sdr.filters == ("scale_cuda=-2:720:interp_algo=lanczos:format=nv12",)
+ assert sdr.post_input == ()
+
+
+def test_tone_mapping_skips_tier_probes() -> None:
+ tier = probe_pipeline_tier("ffmpeg-not-run", "in.mp4", "h264_nvenc", "h264", 2160, 720, 60.0, 60.0, None, PQ)
+ assert tier is Tier.LEGACY
+
+
+def test_8_bit_hdr_stays_8_bit_with_hdr_tags() -> None:
+ hdr8 = HdrSource("smpte2084", ten_bit=False)
+ args = build_video_args(BACKENDS["nvenc"], Tier.ZERO_COPY, 2160, 1440, 60.0, 60.0, "hevc", hdr=hdr8)
+ assert args.filters == ("scale_cuda=-2:1440:interp_algo=lanczos:format=nv12",)
+ assert args.post_input == ("-color_primaries", "bt2020", "-color_trc", "smpte2084", "-colorspace", "bt2020nc")
+
+
+def linearize_step(hdr: HdrSource) -> str:
+ args = build_video_args(BACKENDS["nvenc"], Tier.LEGACY, 2160, 2160, 60.0, 60.0, "h264", hdr=hdr)
+ return args.filters[0]
+
+
+def test_hlg_applies_the_system_gamma_on_luminance() -> None:
+ # zscale's default agamma=1 applies it per channel, which shifts saturated colours.
+ assert linearize_step(HdrSource("arib-std-b67", ten_bit=True)) == "zscale=t=linear:npl=100:agamma=0"
+
+
+def test_pq_keeps_the_fast_gamma() -> None:
+ # agamma=0 changes nothing for PQ and made 4K tone mapping 2.5x slower.
+ assert linearize_step(PQ) == "zscale=t=linear:npl=100"
+
+
+@pytest.mark.parametrize(
+ ("has_primaries", "has_matrix", "extra"),
+ [
+ (False, True, ":pin=bt2020:p=bt2020"),
+ (True, False, ":min=bt2020nc"),
+ (False, False, ":pin=bt2020:p=bt2020:min=bt2020nc"),
+ ],
+)
+def test_missing_color_tags_are_assumed_bt2020(has_primaries: bool, has_matrix: bool, extra: str) -> None:
+ pq = HdrSource("smpte2084", True, has_primaries=has_primaries, has_matrix=has_matrix)
+ hlg = pq._replace(transfer="arib-std-b67")
+ assert linearize_step(pq) == f"zscale=t=linear:npl=100{extra}"
+ assert linearize_step(hlg) == f"zscale=t=linear:npl=100:agamma=0{extra}"
+
+
+def test_cpu_and_vaapi_get_the_same_hlg_chain() -> None:
+ hlg = HdrSource("arib-std-b67", ten_bit=True)
+ for backend in (None, BACKENDS["vaapi"]):
+ args = build_video_args(backend, Tier.LEGACY, 2160, 2160, 60.0, 60.0, "h264", "/dev/dri/renderD128", hdr=hlg)
+ assert "zscale=t=linear:npl=100:agamma=0" in args.filters
+
+
+@pytest.mark.parametrize(
+ ("tags", "has_primaries", "has_matrix"),
+ [
+ ({"color_primaries": "bt2020", "color_space": "bt2020nc"}, True, True),
+ ({"color_primaries": "smpte432", "color_space": "bt709"}, True, True),
+ ({}, False, False),
+ ({"color_primaries": "unknown", "color_space": "bt2020nc"}, False, True),
+ ({"color_primaries": "bt2020", "color_space": "reserved"}, True, False),
+ ],
+)
+def test_hdr_source_notes_missing_color_tags(
+ monkeypatch: pytest.MonkeyPatch, tags: dict, has_primaries: bool, has_matrix: bool
+) -> None:
+ stream = {"color_transfer": "arib-std-b67", "pix_fmt": "yuv420p10le", **tags}
+
+ def fake_probe(cmd: list, **kwargs: object) -> str:
+ if "frame=color_transfer,color_primaries,color_space" in cmd:
+ return json.dumps({"frames": [stream]})
+ return json.dumps({"streams": [stream]})
+
+ monkeypatch.setattr(core.subprocess, "check_output", fake_probe)
+ hdr = core.get_hdr_source("in.mp4")
+ assert hdr is not None
+ assert (hdr.has_primaries, hdr.has_matrix) == (has_primaries, has_matrix)
+
+
+def test_container_only_tags_count_as_missing(monkeypatch: pytest.MonkeyPatch) -> None:
+ # ffprobe's stream entry shows the container's tags, but zscale only sees the frames'.
+ stream = {
+ "color_transfer": "arib-std-b67", "color_primaries": "bt2020", "color_space": "bt2020nc",
+ "pix_fmt": "yuv420p10le",
+ }
+ frame = {"color_transfer": "unknown"}
+
+ def fake_probe(cmd: list, **kwargs: object) -> str:
+ if "frame=color_transfer,color_primaries,color_space" in cmd:
+ return json.dumps({"frames": [frame]})
+ return json.dumps({"streams": [stream]})
+
+ monkeypatch.setattr(core.subprocess, "check_output", fake_probe)
+ hdr = core.get_hdr_source("in.mp4")
+ assert hdr is not None
+ assert (hdr.has_transfer, hdr.has_primaries, hdr.has_matrix) == (False, False, False)
+ assert linearize_step(hdr) == "zscale=t=linear:npl=100:agamma=0:tin=arib-std-b67:pin=bt2020:p=bt2020:min=bt2020nc"
+
+
+def test_stream_tags_are_used_when_no_frame_decodes(monkeypatch: pytest.MonkeyPatch) -> None:
+ stream = {"color_transfer": "smpte2084", "color_primaries": "bt2020", "color_space": "bt2020nc"}
+
+ def fake_probe(cmd: list, **kwargs: object) -> str:
+ if "frame=color_transfer,color_primaries,color_space" in cmd:
+ return json.dumps({"frames": []})
+ return json.dumps({"streams": [stream]})
+
+ monkeypatch.setattr(core.subprocess, "check_output", fake_probe)
+ assert core.get_hdr_source("in.mp4") == HdrSource("smpte2084", ten_bit=False)
+
+
+def test_pq_with_untagged_transfer_is_assumed_pq() -> None:
+ assert linearize_step(PQ._replace(has_transfer=False)) == "zscale=t=linear:npl=100:tin=smpte2084"
+
+
+def test_bit_depth_from_pix_fmt() -> None:
+ assert is_high_bit_depth("yuv420p10le") and is_high_bit_depth("p010le") and is_high_bit_depth("yuv420p12le")
+ assert not is_high_bit_depth("yuv420p") and not is_high_bit_depth("yuvj420p") and not is_high_bit_depth("nv12")
diff --git a/tests/test_legacy_cmds.py b/tests/test_legacy_cmds.py
index 10f06d6..88b24a9 100644
--- a/tests/test_legacy_cmds.py
+++ b/tests/test_legacy_cmds.py
@@ -33,7 +33,7 @@
],
),
"hevc_vaapi scaled, fps drop, trimmed, audio re-encode": dict(
- args=dict(encoder="hevc_vaapi", codec_type="hevc", tgt_h=720, tgt_fps=30.0, start=10.0, end=20.0, audio_kbps=192),
+ args=dict(encoder="hevc_vaapi", codec_type="hevc", tgt_h=720, tgt_fps=30.0, start=10.0, end=20.0, audio_kbps=128, reencode_audio=True),
expected=[
"ffmpeg", "-y", "-init_hw_device", "vaapi=va", "-filter_hw_device", "va",
"-ss", "10.0", "-to", "20.0", "-i", "in.mp4", "-avoid_negative_ts", "make_zero",
@@ -70,12 +70,6 @@ def build(args: Dict[str, object], tier: Optional[Tier] = None) -> List[str]:
)
-@pytest.fixture(autouse=True)
-def stub_audio_probe(monkeypatch: pytest.MonkeyPatch) -> None:
- """Make the AAC availability check deterministic."""
- monkeypatch.setattr(core, "check_audio_encoder_available", lambda encoder_name="aac": True)
-
-
@pytest.mark.parametrize("name", list(CASES))
def test_default_tier_is_legacy_command(name: str) -> None:
case = CASES[name]
diff --git a/tests/test_runtime_libs.py b/tests/test_runtime_libs.py
new file mode 100644
index 0000000..c610dc3
--- /dev/null
+++ b/tests/test_runtime_libs.py
@@ -0,0 +1,46 @@
+"""Tests for the missing system library check run before probing."""
+
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+from videocompress import core
+
+LOADER_ERROR = (
+ "ffprobe: error while loading shared libraries: libva.so.2: "
+ "cannot open shared object file: No such file or directory\n"
+)
+
+
+def test_reports_missing_library_with_install_hint(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(core.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=127, stderr=LOADER_ERROR))
+ message = core.find_missing_runtime_library("ffprobe")
+ assert message is not None
+ assert "libva.so.2" in message
+ assert "apt install libva2 libva-drm2 libdrm2" in message
+
+
+@pytest.mark.parametrize("result", [SimpleNamespace(returncode=0, stderr=""), SimpleNamespace(returncode=1, stderr="other failure")])
+def test_no_message_when_ffprobe_starts(monkeypatch: pytest.MonkeyPatch, result: SimpleNamespace) -> None:
+ monkeypatch.setattr(core.subprocess, "run", lambda *a, **k: result)
+ assert core.find_missing_runtime_library("ffprobe") is None
+
+
+@pytest.mark.parametrize("error", [subprocess.TimeoutExpired("ffprobe", 10), OSError("missing")])
+def test_no_message_when_ffprobe_cannot_run(monkeypatch: pytest.MonkeyPatch, error: BaseException) -> None:
+ def boom(*args: object, **kwargs: object) -> None:
+ raise error
+
+ monkeypatch.setattr(core.subprocess, "run", boom)
+ assert core.find_missing_runtime_library("ffprobe") is None
+
+
+def test_compress_video_stops_with_library_message(monkeypatch: pytest.MonkeyPatch, tmp_path: object) -> None:
+ from videocompress import encode
+
+ source = tmp_path / "in.mp4" # type: ignore[operator]
+ source.write_bytes(b"x")
+ monkeypatch.setattr(encode, "find_missing_runtime_library", lambda exe: "missing libva.so.2")
+ ok, message = encode.compress_video(str(source), None, 20.0, "hevc")
+ assert (ok, message) == (False, "missing libva.so.2")
diff --git a/tests/test_tables.py b/tests/test_tables.py
new file mode 100644
index 0000000..336c44a
--- /dev/null
+++ b/tests/test_tables.py
@@ -0,0 +1,28 @@
+"""Every bordered table and panel has rounded corners, including in legacy Windows consoles."""
+
+import io
+
+import pytest
+
+from videocompress import progress
+
+
+def test_tables_and_panels_are_rounded(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Rich swaps rounded boxes for square ones on legacy Windows unless safe boxes are off.
+
+ Example:
+ >>> # pytest tests/test_tables.py
+ """
+ output = io.StringIO()
+ monkeypatch.setattr(progress.console, "file", output)
+ monkeypatch.setattr(progress.console, "legacy_windows", True)
+ monkeypatch.setattr(progress.console, "_width", 120)
+
+ progress.show_encoder_detection([("hevc_nvenc", "selected")])
+ progress.console.print(progress.build_dual_display(40, 60, 1, 1, 1, 1, 1, 1, 1, 1, "Encoding", 0))
+ progress.console.print(progress.build_single_display(50, 1, 1, 1, 1, "Encoding", 0))
+ progress.show_result_panel(2, 1, 1, 1.0, "hevc_nvenc", "parallel split")
+
+ text = output.getvalue()
+ assert text.count("╭") == 6 # 3 tables, 3 panels
+ assert not set(text) & set("┌┐└┘┏┓┡┩")
diff --git a/tests/test_tier_fallback.py b/tests/test_tier_fallback.py
index a78107f..e50896c 100644
--- a/tests/test_tier_fallback.py
+++ b/tests/test_tier_fallback.py
@@ -134,7 +134,7 @@ def fake_split(**kwargs: object) -> Tuple[bool, str]:
return True, ""
return False, "Split encode failed"
- monkeypatch.setattr(encode, "get_video_info", lambda p: (10.0, 500 * 1024 * 1024, 60.0, 128, 1920, 1080))
+ monkeypatch.setattr(encode, "get_video_info", lambda p: (10.0, 500 * 1024 * 1024, 60.0, 128, 1920, 1080, "aac"))
monkeypatch.setattr(encode, "select_best_encoder", lambda c: ("hevc_vaapi", [("hevc_vaapi", "selected")]))
monkeypatch.setattr(encode, "resolve_vaapi_node", lambda enc: "/dev/dri/renderD128")
monkeypatch.setattr(encode, "probe_pipeline_tier", lambda *a, **k: Tier.ZERO_COPY)
@@ -144,3 +144,18 @@ def fake_split(**kwargs: object) -> Tuple[bool, str]:
ok, result = encode.compress_video(str(source), str(output), 100.0, "hevc")
assert ok and result == str(output)
assert tiers == [Tier.ZERO_COPY, Tier.LEGACY]
+
+
+def test_small_input_skips_audio_and_hdr_probes(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source = tmp_path / "in.mp4"
+ source.write_bytes(b"x")
+
+ def must_not_run(*args: object, **kwargs: object) -> None:
+ raise AssertionError("probed a file that is already under the target")
+
+ monkeypatch.setattr(encode, "find_missing_runtime_library", lambda p: None)
+ monkeypatch.setattr(encode, "get_video_info", lambda p: (10.0, 5 * 1024 * 1024, 60.0, 128, 1920, 1080, "aac"))
+ monkeypatch.setattr(encode, "plan_audio", must_not_run)
+ monkeypatch.setattr(encode, "get_hdr_source", must_not_run)
+ ok, result = encode.compress_video(str(source), None, 20.0, "hevc")
+ assert not ok and result.startswith("Already smaller than target")
diff --git a/tools/bench_vitals.py b/tools/bench_vitals.py
deleted file mode 100644
index b5f59b9..0000000
--- a/tools/bench_vitals.py
+++ /dev/null
@@ -1,268 +0,0 @@
-"""Benchmark monitor: run a command and sample vitals for its whole process tree.
-
-Development tool only. It is never imported by the `videocompress` package and
-is not bundled into the PyInstaller executables. Requires the `dev` extra
-(`pip install -e .[dev]`) for `psutil`.
-
-Measures, for the command and every process it starts:
- - CPU time: exact on Linux/macOS (OS resource accounting of finished child
- processes); sampled every interval on Windows, where very short-lived
- processes can be missed.
- - Host-wide CPU, peak resident memory (sampled).
- - GPU: per-engine busy time from DRM fdinfo on Linux (Intel i915/xe and AMD
- amdgpu, no root needed), and NVIDIA SM/encoder/decoder utilization from
- `nvidia-smi` on any OS (first NVIDIA GPU, GPU-wide rather than per process).
-
-The command's own output is discarded; a single JSON summary line is printed
-when it exits.
-
-Usage:
- python tools/bench_vitals.py --label v120_4k --output out.mp4 -- python -m videocompress input-4K60.mp4 out.mp4 100 hevc
-
-Options:
- --label Name stored in the JSON summary (required).
- --output Encoded file whose size is reported as output_mb.
- --csv Write per-sample rows to this CSV file.
- --interval Sampling interval in seconds (default 0.5).
-"""
-
-import argparse
-import csv
-import json
-import logging
-import shutil
-import subprocess
-import time
-from pathlib import Path
-from typing import Dict, List, NamedTuple, Optional, Tuple, Union
-
-import psutil
-
-try:
- import resource
-except ImportError:
- resource = None
-
-log = logging.getLogger("vitals")
-
-EngineTotals = Dict[str, int]
-Summary = Dict[str, Union[float, str]]
-IDLE_FIELDS = ("idle", "iowait")
-GUEST_FIELDS = ("guest", "guest_nice")
-
-
-def host_busy_seconds(times: NamedTuple) -> float:
- """Return busy CPU seconds from psutil.cpu_times() on any OS.
-
- Idle/iowait are excluded, and guest time is skipped because Linux already
- counts it inside user/nice.
-
- Example:
- >>> host_busy_seconds(psutil.cpu_times()) >= 0
- True
- """
- return sum(
- value for name, value in zip(times._fields, times)
- if name not in IDLE_FIELDS + GUEST_FIELDS
- )
-
-
-def children_cpu_seconds() -> Optional[float]:
- """Return user+system CPU seconds of all finished, waited-for descendants (POSIX only).
-
- Example:
- >>> children_cpu_seconds() is None or children_cpu_seconds() >= 0
- True
- """
- if resource is None:
- return None
- usage = resource.getrusage(resource.RUSAGE_CHILDREN)
- return usage.ru_utime + usage.ru_stime
-
-
-def read_drm_engines(pid: int) -> Dict[str, EngineTotals]:
- """Return cumulative engine ns per DRM client id for one process.
-
- Example:
- >>> isinstance(read_drm_engines(1), dict)
- True
- """
- clients: Dict[str, EngineTotals] = {}
- fdinfo_dir = Path(f"/proc/{pid}/fdinfo")
- try:
- entries = list(fdinfo_dir.iterdir())
- except OSError:
- return clients
- for entry in entries:
- try:
- text = entry.read_text()
- except OSError:
- continue
- if "drm-client-id" not in text:
- continue
- fields = dict(
- line.split(":", 1) for line in text.splitlines() if ":" in line
- )
- client_id = fields["drm-client-id"].strip()
- engines = {
- key.replace("drm-engine-", ""): int(value.strip().split()[0])
- for key, value in fields.items()
- if key.startswith("drm-engine-") and not key.startswith("drm-engine-capacity")
- }
- clients[client_id] = engines
- return clients
-
-
-def read_nvidia() -> Optional[Tuple[float, float, float]]:
- """Return (sm%, enc%, dec%) from nvidia-smi, or None when unavailable.
-
- Example:
- >>> read_nvidia() is None or len(read_nvidia()) == 3
- True
- """
- if shutil.which("nvidia-smi") is None:
- return None
- try:
- out = subprocess.run(
- ["nvidia-smi", "--query-gpu=utilization.gpu,utilization.encoder,utilization.decoder",
- "--format=csv,noheader,nounits"],
- capture_output=True, text=True, timeout=2.0, check=True,
- ).stdout.splitlines()[0]
- sm, enc, dec = (float(v) for v in out.split(","))
- return sm, enc, dec
- except (subprocess.SubprocessError, ValueError, IndexError) as exc:
- log.debug("nvidia-smi sample failed: %s", exc)
- return None
-
-
-def tree(root: psutil.Process) -> List[psutil.Process]:
- """Return the root process plus all live descendants.
-
- Example:
- >>> len(tree(psutil.Process())) >= 1
- True
- """
- try:
- return [root] + root.children(recursive=True)
- except psutil.NoSuchProcess:
- return []
-
-
-def monitor(cmd: List[str], interval: float, csv_path: Optional[Path]) -> Summary:
- """Run cmd to completion while sampling vitals; return a summary dict.
-
- Example:
- >>> import sys
- >>> monitor([sys.executable, "-c", "import time; time.sleep(1)"], 0.5, None)["wall_s"] > 0.9
- True
- """
- psutil.cpu_percent(None)
- host_t0 = psutil.cpu_times()
- rusage_t0 = children_cpu_seconds()
- start = time.monotonic()
- proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- try:
- root: Optional[psutil.Process] = psutil.Process(proc.pid)
- except psutil.NoSuchProcess:
- root = None
- cpu_time_seen: Dict[int, float] = {}
- engine_seen: Dict[Tuple[int, str], EngineTotals] = {}
- rows: List[Dict[str, float]] = []
- prev_engine_sum: EngineTotals = {}
- prev_t = start
- peak_rss = 0
-
- while proc.poll() is None:
- time.sleep(interval)
- now = time.monotonic()
- procs = tree(root) if root is not None else []
- rss = 0
- for p in procs:
- try:
- with p.oneshot():
- t = p.cpu_times()
- cpu_time_seen[p.pid] = t.user + t.system
- rss += p.memory_info().rss
- for client, engines in read_drm_engines(p.pid).items():
- engine_seen[(p.pid, client)] = engines
- except (psutil.NoSuchProcess, psutil.AccessDenied):
- continue
- peak_rss = max(peak_rss, rss)
- engine_sum: EngineTotals = {}
- for engines in engine_seen.values():
- for name, ns in engines.items():
- engine_sum[name] = engine_sum.get(name, 0) + ns
- dt = now - prev_t
- row: Dict[str, float] = {
- "t": round(now - start, 2),
- "host_cpu_pct": psutil.cpu_percent(None),
- "tree_cpu_s": round(sum(cpu_time_seen.values()), 2),
- "rss_mb": round(rss / 2**20, 1),
- }
- for name, ns in engine_sum.items():
- row[f"gpu_{name}_pct"] = round(100.0 * (ns - prev_engine_sum.get(name, 0)) / (dt * 1e9), 1)
- nv = read_nvidia()
- if nv is not None:
- row["nv_sm_pct"], row["nv_enc_pct"], row["nv_dec_pct"] = nv
- rows.append(row)
- prev_engine_sum, prev_t = engine_sum, now
-
- wall = time.monotonic() - start
- host_busy_s = host_busy_seconds(psutil.cpu_times()) - host_busy_seconds(host_t0)
- rusage_t1 = children_cpu_seconds()
- if rusage_t0 is not None and rusage_t1 is not None:
- cpu_s, cpu_source = rusage_t1 - rusage_t0, "exact"
- else:
- cpu_s, cpu_source = sum(cpu_time_seen.values()), "sampled"
- logical = psutil.cpu_count() or 1
- summary: Summary = {
- "exit": proc.returncode,
- "wall_s": round(wall, 1),
- "tree_cpu_s": round(cpu_s, 1),
- "tree_cpu_source": cpu_source,
- "host_busy_cpu_s": round(host_busy_s, 1),
- "avg_tree_cpu_cores": round(cpu_s / wall, 2) if wall else 0.0,
- "avg_tree_cpu_pct_of_host": round(100.0 * cpu_s / wall / logical, 1) if wall else 0.0,
- "avg_host_cpu_pct": round(sum(r["host_cpu_pct"] for r in rows) / len(rows), 1) if rows else 0.0,
- "peak_rss_mb": round(peak_rss / 2**20, 1),
- }
- for name, ns in prev_engine_sum.items():
- summary[f"gpu_{name}_busy_pct"] = round(100.0 * ns / (wall * 1e9), 1) if wall else 0.0
- nv_rows = [r for r in rows if "nv_sm_pct" in r]
- for key in ("nv_sm_pct", "nv_enc_pct", "nv_dec_pct"):
- if nv_rows:
- summary[f"avg_{key}"] = round(sum(r[key] for r in nv_rows) / len(nv_rows), 1)
-
- if csv_path is not None and rows:
- keys = sorted({k for r in rows for k in r}, key=lambda k: (k != "t", k))
- with csv_path.open("w", newline="") as fh:
- writer = csv.DictWriter(fh, fieldnames=keys)
- writer.writeheader()
- writer.writerows(rows)
- return summary
-
-
-def main() -> None:
- """Parse args, run the monitored command, print a JSON summary line."""
- parser = argparse.ArgumentParser()
- parser.add_argument("--label", required=True)
- parser.add_argument("--interval", type=float, default=0.5)
- parser.add_argument("--csv", type=Path, default=None)
- parser.add_argument("--output", type=Path, default=None, help="Encoded file to report size of")
- parser.add_argument("cmd", nargs=argparse.REMAINDER)
- args = parser.parse_args()
- cmd = args.cmd[1:] if args.cmd and args.cmd[0] == "--" else args.cmd
- if not cmd:
- parser.error("no command given; put it after `--`")
- try:
- summary = monitor(cmd, args.interval, args.csv)
- except OSError as e:
- parser.error(f"could not start {cmd[0]!r}: {e}")
- if args.output is not None and args.output.exists():
- summary["output_mb"] = round(args.output.stat().st_size / 2**20, 2)
- print(json.dumps({"label": args.label, **summary}))
-
-
-if __name__ == "__main__":
- logging.basicConfig(level=logging.INFO)
- main()
diff --git a/uv.lock b/uv.lock
new file mode 100644
index 0000000..c91ca15
--- /dev/null
+++ b/uv.lock
@@ -0,0 +1,266 @@
+version = 1
+revision = 3
+requires-python = ">=3.11"
+
+[[package]]
+name = "altgraph"
+version = "0.17.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7e/f8/97fdf103f38fed6792a1601dbc16cc8aac56e7459a9fff08c812d8ae177a/altgraph-0.17.5.tar.gz", hash = "sha256:c87b395dd12fabde9c99573a9749d67da8d29ef9de0125c7f536699b4a9bc9e7", size = 48428, upload-time = "2025-11-21T20:35:50.583Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a9/ba/000a1996d4308bc65120167c21241a3b205464a2e0b58deda26ae8ac21d1/altgraph-0.17.5-py2.py3-none-any.whl", hash = "sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597", size = 21228, upload-time = "2025-11-21T20:35:49.444Z" },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
+]
+
+[[package]]
+name = "iniconfig"
+version = "2.3.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" },
+]
+
+[[package]]
+name = "macholib"
+version = "1.16.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "altgraph" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/10/2f/97589876ea967487978071c9042518d28b958d87b17dceb7cdc1d881f963/macholib-1.16.4.tar.gz", hash = "sha256:f408c93ab2e995cd2c46e34fe328b130404be143469e41bc366c807448979362", size = 59427, upload-time = "2025-11-22T08:28:38.373Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" },
+]
+
+[[package]]
+name = "markdown-it-py"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
+[[package]]
+name = "packaging"
+version = "26.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
+]
+
+[[package]]
+name = "pefile"
+version = "2024.8.26"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/03/4f/2750f7f6f025a1507cd3b7218691671eecfd0bbebebe8b39aa0fe1d360b8/pefile-2024.8.26.tar.gz", hash = "sha256:3ff6c5d8b43e8c37bb6e6dd5085658d658a7a0bdcd20b6a07b1fcfc1c4e9d632", size = 76008, upload-time = "2024-08-26T20:58:38.155Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/16/12b82f791c7f50ddec566873d5bdd245baa1491bac11d15ffb98aecc8f8b/pefile-2024.8.26-py3-none-any.whl", hash = "sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f", size = 74766, upload-time = "2024-08-26T21:01:02.632Z" },
+]
+
+[[package]]
+name = "pluggy"
+version = "1.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" },
+]
+
+[[package]]
+name = "psutil"
+version = "7.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" },
+ { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" },
+ { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" },
+ { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" },
+ { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" },
+ { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" },
+ { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" },
+ { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },
+]
+
+[[package]]
+name = "pygments"
+version = "2.21.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
+]
+
+[[package]]
+name = "pyinstaller"
+version = "6.22.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "altgraph" },
+ { name = "macholib", marker = "sys_platform == 'darwin'" },
+ { name = "packaging" },
+ { name = "pefile", marker = "sys_platform == 'win32'" },
+ { name = "pyinstaller-hooks-contrib" },
+ { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" },
+ { name = "setuptools" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/63/41/f90302845945abd4ed647933ff5ee7c6ac93983187be67f897b6cb613331/pyinstaller-6.22.3.tar.gz", hash = "sha256:05eb2f5615503e72939a7224d68b4aff572c6b0438ee4a17d0a4b481f399362d", size = 4437180, upload-time = "2026-09-12T21:54:09.669Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ec/af/898f70947e27f8e65d55183c780e77112e023c0b4a6fba6255d4d563a27d/pyinstaller-6.22.3-py3-none-macosx_10_13_universal2.whl", hash = "sha256:052f4a1cd4f81092ccb7a18fe8ebc9ecf832a5917317e39fb3775af4e959b253", size = 1071847, upload-time = "2026-09-12T21:53:01.711Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/96/99f5184985141c2b024bfa61335e9142ae444555224f303186e59b7bb438/pyinstaller-6.22.3-py3-none-manylinux2014_aarch64.whl", hash = "sha256:312da84b4b31ab9750066a823734c11b7c68757fdd67c9f038bf19c330a954e4", size = 758172, upload-time = "2026-09-12T21:53:06.171Z" },
+ { url = "https://files.pythonhosted.org/packages/69/9f/9ccb12cc1e6617042cb028fe79f0a756f5f03305bd14b584a4e043fe3844/pyinstaller-6.22.3-py3-none-manylinux2014_i686.whl", hash = "sha256:020d4fe0627f5c73dfbcfad1a6578ef354d5fe4bdccd9d8e5a615528f5a45d2b", size = 772135, upload-time = "2026-09-12T21:53:10.291Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/43/4b1d5193a88628c052db89f064433681076959a9f41d0d9f660001b49079/pyinstaller-6.22.3-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:9e4f7bd64b2103f14b4a6240fb9155e9fe7bc61391b4043bbddb7d3ebc8ab0fa", size = 770461, upload-time = "2026-09-12T21:53:14.592Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/83/f173f8757c618d83e116fa2b8e57c5cd796e5ad09792e664eabd6ac5edae/pyinstaller-6.22.3-py3-none-manylinux2014_s390x.whl", hash = "sha256:f82d0fb89f21c3ed6f482ee16f341bc59e8a31dbabb9bae9ef04e53ade4dc0d9", size = 764997, upload-time = "2026-09-12T21:53:19.079Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/b6/dd21d61fc5e25377be24eabf13e99e4e46548a5abe2bf7b15d8b3d9cc74a/pyinstaller-6.22.3-py3-none-manylinux2014_x86_64.whl", hash = "sha256:451a4ae14b719365bf1a2f0a99dae7b3463060061c3a394c70d5264cfb439528", size = 764974, upload-time = "2026-09-12T21:53:23.176Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/fd/d9590942972b1fc205519f7ccffb0d5cd8eb1d6fa61edad319c71d25baed/pyinstaller-6.22.3-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:ea240b5dfa831ff673c97505eee0ec24670bccf71396c83109440348944c83d0", size = 764450, upload-time = "2026-09-12T21:53:27.419Z" },
+ { url = "https://files.pythonhosted.org/packages/72/d6/f22c55d1768433b65c460b19a3136dd9769b6c74b786149b829344654c7d/pyinstaller-6.22.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:a2b6fc26601e8c2596c3d54981566934a3382e85d05d0fe91b55b6a8dcc6b282", size = 763863, upload-time = "2026-09-12T21:53:31.609Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/87/cf28cfd42ceca889171e6dd5e7f1553d4372db83d047049ffb7cf95fcbd4/pyinstaller-6.22.3-py3-none-win32.whl", hash = "sha256:46a3e30a118341a1ec20667a5a95aa7e0aa8c4fa129893c0151b3eb3f801a722", size = 1390905, upload-time = "2026-09-12T21:53:38.133Z" },
+ { url = "https://files.pythonhosted.org/packages/24/83/c5422204772a27aef643280fdc887b7ef55679989096b21dceb1b9625fc4/pyinstaller-6.22.3-py3-none-win_amd64.whl", hash = "sha256:500bd58c7bf7e584a8435adccbd763a0b918d5c12b08d74ff50fd79b2915458b", size = 1454907, upload-time = "2026-09-12T21:53:44.812Z" },
+ { url = "https://files.pythonhosted.org/packages/67/2e/ebc93968bf63f81b122e205da116b16036b653b7ce2cc8ad86e3ddd19586/pyinstaller-6.22.3-py3-none-win_arm64.whl", hash = "sha256:31df3cc4261e804a53d358b7897c293ec8b88b167a7cca06c78018085c855f97", size = 1402956, upload-time = "2026-09-12T21:53:51.369Z" },
+]
+
+[[package]]
+name = "pyinstaller-hooks-contrib"
+version = "2026.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "packaging" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/96/25/e47c6188228281372be7e9911a93931e01ec8798c02c93abd680b9b9521f/pyinstaller_hooks_contrib-2026.9.tar.gz", hash = "sha256:2748767901acb5cecd1304652b6c7add5bffcff1d71d01207fe24a5d42942a56", size = 180783, upload-time = "2026-10-20T15:43:54Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/93/fe/ded0e20de0580257d97dbabb4db7ab4d96ad8ade7d41149e66308057cf52/pyinstaller_hooks_contrib-2026.9-py3-none-any.whl", hash = "sha256:fb3e67dd64122561724c48ad0366ac9e8c16e638b63bf7d85de03bf3fdbf06c3", size = 462931, upload-time = "2026-10-20T15:43:52.632Z" },
+]
+
+[[package]]
+name = "pytest"
+version = "9.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "iniconfig" },
+ { name = "packaging" },
+ { name = "pluggy" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" },
+]
+
+[[package]]
+name = "pywin32-ctypes"
+version = "0.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" },
+]
+
+[[package]]
+name = "rich"
+version = "15.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },
+]
+
+[[package]]
+name = "ruff"
+version = "0.17.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/84/0e/3d154514b5bad104f7e1c13169c2d09aa9959fccdc06eb47610ccdfa83ed/ruff-0.17.4.tar.gz", hash = "sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d", size = 5357750, upload-time = "2026-11-05T18:52:17.638Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e0/61/c83c78bbb6108f6c6270a106cf12b54175f4f42da088b9bb880f18e31289/ruff-0.17.4-py3-none-linux_armv6l.whl", hash = "sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89", size = 10252195, upload-time = "2026-11-05T18:51:36.594Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/12/dd158708378866e8b53e145a465dbc51a7cccb9fa197a74d67eaedde7234/ruff-0.17.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7", size = 10266044, upload-time = "2026-11-05T18:51:39.502Z" },
+ { url = "https://files.pythonhosted.org/packages/28/32/89a94a8eb11fd505a381ae6f04e190d038d9958695209dc1786ce5cfcda3/ruff-0.17.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0", size = 9432227, upload-time = "2026-11-05T18:51:41.968Z" },
+ { url = "https://files.pythonhosted.org/packages/58/de/a392dc38b215798ae72e639d228b7f6c02d826a95d1c0ad7c4c0ee49ef5b/ruff-0.17.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a", size = 10136900, upload-time = "2026-11-05T18:51:44.562Z" },
+ { url = "https://files.pythonhosted.org/packages/b7/8f/a880f60f42005f6ffdf58f77af34c7ee327000b5607f48a2f6a69d8b242c/ruff-0.17.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185", size = 10051245, upload-time = "2026-11-05T18:51:46.7Z" },
+ { url = "https://files.pythonhosted.org/packages/09/55/98844264108af7d5ec27ca3a9cd5a989094ca657a14599c4b69a537a0e9a/ruff-0.17.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e", size = 10704341, upload-time = "2026-11-05T18:51:49.228Z" },
+ { url = "https://files.pythonhosted.org/packages/28/a2/5edf97659c3ac7c73f978003bd314936f671037fdac6b978e9de3e4b2b65/ruff-0.17.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524", size = 11394465, upload-time = "2026-11-05T18:51:51.534Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/8f/51371ae856b2bef4d15a044a574695fbc0f6ae63aafa42a2a22428070fb6/ruff-0.17.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6", size = 10988262, upload-time = "2026-11-05T18:51:53.91Z" },
+ { url = "https://files.pythonhosted.org/packages/af/1b/62874f14c7873f27c7887d2b1ea41de990e14ba9518801ffe8eacb5d51a6/ruff-0.17.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690", size = 10572829, upload-time = "2026-11-05T18:51:56.129Z" },
+ { url = "https://files.pythonhosted.org/packages/98/30/860b9dae67432b16b88558a9cb2d3194825fa62838f8b9cc49f5d9022095/ruff-0.17.4-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1", size = 10617545, upload-time = "2026-11-05T18:51:58.172Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/08/781a4b41a1c83fd6e30fea610d6502a6f94e49cf94693fd37bdcbc6bfe11/ruff-0.17.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5", size = 10111955, upload-time = "2026-11-05T18:52:00.59Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/e9/94b1c7b677120f30839254518924f73a8157e9bcfa200edcd5796fecdb99/ruff-0.17.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90", size = 10058355, upload-time = "2026-11-05T18:52:03.61Z" },
+ { url = "https://files.pythonhosted.org/packages/27/5f/a825910b9f309336dc33cb8c0774126662c1d2f765699b3e0a1bd538d01f/ruff-0.17.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8", size = 10415932, upload-time = "2026-11-05T18:52:06.264Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/b8/0796468423413ea4df1a6e2442ae26cf49b8f7dda0eecf246e0d5d0dde54/ruff-0.17.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496", size = 10826033, upload-time = "2026-11-05T18:52:08.675Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/ab/d8e407669ffe5014429baf780c2df47e001968a6e4c17f615e2e7b13a9ba/ruff-0.17.4-py3-none-win32.whl", hash = "sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf", size = 9931993, upload-time = "2026-11-05T18:52:11.169Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/15/42af8a72d8946e3c9efd2bbf6641e462b6832783b0d043d63ef5b280ba7f/ruff-0.17.4-py3-none-win_amd64.whl", hash = "sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c", size = 10292922, upload-time = "2026-11-05T18:52:13.436Z" },
+ { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" },
+]
+
+[[package]]
+name = "setuptools"
+version = "84.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" },
+]
+
+[[package]]
+name = "video-compression"
+source = { editable = "." }
+dependencies = [
+ { name = "rich" },
+]
+
+[package.optional-dependencies]
+build = [
+ { name = "pyinstaller" },
+]
+dev = [
+ { name = "psutil" },
+ { name = "pytest" },
+ { name = "ruff" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "psutil", marker = "extra == 'dev'", specifier = ">=5.9" },
+ { name = "pyinstaller", marker = "extra == 'build'", specifier = ">=6.0" },
+ { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" },
+ { name = "rich", specifier = ">=13.0" },
+ { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.17,<0.18" },
+]
+provides-extras = ["build", "dev"]
diff --git a/videocompress/cli.py b/videocompress/cli.py
index e0599a9..aaa5999 100644
--- a/videocompress/cli.py
+++ b/videocompress/cli.py
@@ -3,10 +3,14 @@
Usage:
python -m videocompress [output.mp4] [target_mb] [hevc/h264]
+ python -m videocompress --custom [hevc/h264] (asks for the size)
+
+File names need their extension: `20` is always a size, `20.mp4` is a file.
"""
import sys
import os
+import re
import logging
from typing import Optional, List
@@ -25,6 +29,8 @@
log = logging.getLogger(__name__)
DEFAULT_TARGET_MB: float = 100.0
+# A final ".suffix", unless it is the decimals of a size such as 20.5 or 1.5e3.
+FILE_EXTENSION = re.compile(r"\.(?!\d+(e\d+)?$)\w+$", re.IGNORECASE)
def _try_parse_positive_float(value: str) -> Optional[float]:
@@ -43,6 +49,45 @@ def _try_parse_positive_float(value: str) -> Optional[float]:
return None
+def _is_file_name(value: str) -> bool:
+ """Tell whether an argument is a complete file name, with its extension.
+
+ Args:
+ value: Command-line argument.
+
+ Returns:
+ True for a name with an extension that is not an existing folder.
+
+ Example:
+ >>> _is_file_name("20.mp4"), _is_file_name("20"), _is_file_name("20.5")
+ (True, False, False)
+ """
+ return FILE_EXTENSION.search(value) is not None and not os.path.isdir(value)
+
+
+def _prompt_target_mb() -> float:
+ """Ask on the console for a target size until a positive number is given.
+
+ Used by the Windows context menu's "Custom..." entry.
+
+ Returns:
+ The target size in megabytes.
+
+ Raises:
+ SystemExit: When the console input ends without an answer.
+ """
+ while True:
+ try:
+ answer = input("Target size in MB: ")
+ except EOFError:
+ sys.stderr.write("Error: no target size given.\n")
+ sys.exit(1)
+ target = _try_parse_positive_float(answer.strip())
+ if target is not None:
+ return target
+ sys.stdout.write("Enter a number greater than 0, for example 25.\n")
+
+
def main() -> None:
"""Entry point for the command-line interface.
@@ -50,7 +95,7 @@ def main() -> None:
compression engine.
"""
if len(sys.argv) < 2:
- sys.stdout.write("Usage: videocompress [output.mp4] [size_in_mb] [hevc/h264] [--verbose]\n")
+ sys.stdout.write("Usage: videocompress [output.mp4] [size_in_mb | --custom] [hevc/h264] [--verbose]\n")
sys.exit(1)
verbose = "--verbose" in sys.argv or "-v" in sys.argv or os.environ.get("DEBUG") == "1"
@@ -62,7 +107,8 @@ def main() -> None:
target_mb: float = DEFAULT_TARGET_MB
codec_type: str = "hevc"
- raw_args = [a for a in sys.argv[1:] if a not in ("--verbose", "-v")]
+ custom_size = "--custom" in sys.argv
+ raw_args = [a for a in sys.argv[1:] if a not in ("--verbose", "-v", "--custom")]
potential_paths: List[str] = []
for arg_s in raw_args:
@@ -70,14 +116,17 @@ def main() -> None:
if arg_lower in ("hevc", "h264"):
codec_type = arg_lower
- elif os.path.exists(arg_s):
+ elif _is_file_name(arg_s):
potential_paths.append(arg_s)
else:
num = _try_parse_positive_float(arg_s)
- if num is not None:
- target_mb = num
- else:
- potential_paths.append(arg_s)
+ if num is None:
+ sys.stderr.write(
+ f"Error: '{arg_s}' is not a size, a codec or a complete file name "
+ "with its extension (for example video.mp4).\n"
+ )
+ sys.exit(1)
+ target_mb = num
# First pass: Identify input file (must exist)
for path in potential_paths:
@@ -98,6 +147,8 @@ def main() -> None:
inp_path = str(input_file)
try:
+ if custom_size:
+ target_mb = _prompt_target_mb()
success, result = compress_video(
input_path=inp_path,
output_path=output_file,
@@ -105,7 +156,7 @@ def main() -> None:
codec_type=codec_type,
)
if not success:
- if result and "Cancelled" not in result:
+ if result:
sys.stderr.write(f"Compression failed: {result}\n")
_save_error_log(log_buffer, inp_path)
sys.exit(1)
diff --git a/videocompress/core.py b/videocompress/core.py
index a90fd30..75e65f7 100644
--- a/videocompress/core.py
+++ b/videocompress/core.py
@@ -7,13 +7,14 @@
import os
import math
import json
+import re
import logging
import shutil
from functools import lru_cache
from pathlib import Path
from typing import Tuple, Optional, List, Sequence, Mapping
-from videocompress.hwpipeline import Tier, backend_for_encoder, build_video_args
+from videocompress.hwpipeline import HdrSource, Tier, backend_for_encoder, build_video_args, hdr_handling
log = logging.getLogger(__name__)
@@ -21,6 +22,11 @@
MB_TO_BYTES = 1024 * 1024
MB_TO_BITS = 8 * 1024 * 1024
BITRATE_SAFETY_FACTOR = 0.90
+LOSSLESS_AUDIO_CODECS = ("flac", "alac", "truehd", "mlp", "wavpack", "tta", "ape")
+AUDIO_REENCODE_KBPS = 128
+AUDIO_REENCODE_MIN_KBPS = 160 # at or below this, 128k saves too little to be worth the time
+AUDIO_MAX_TARGET_SHARE = 0.10
+AUDIO_SAMPLE_S = 30
MIN_BPP = 0.04 # Target Bits Per Pixel threshold
LOG_FILES_TO_CLEAN = ["ffmpeg2pass.log", "ffmpeg2pass-0.log", "ffmpeg2pass-0.log.mbtree"]
@@ -31,6 +37,8 @@
VAAPI_NODE_TIMEOUT_S = 10
PIPELINE_PROBE_TIMEOUT_S = 20
PIPELINE_PROBE_TIERS = (Tier.ZERO_COPY, Tier.UPLOAD)
+HDR_TRANSFERS = ("smpte2084", "arib-std-b67")
+UNTAGGED_COLOR = ("", "unknown", "reserved")
ENCODER_PRIORITY = {
"hevc": {
@@ -221,7 +229,7 @@ def calculate_video_bitrate(target_mb: float, duration: float, audio_kbps: int)
Args:
target_mb: Desired target file size in megabytes.
duration: Video duration in seconds.
- audio_kbps: Probed audio bitrate in kbps.
+ audio_kbps: Audio bitrate of the output in kbps.
Returns:
Target video bitrate in kbps (integer).
@@ -241,7 +249,7 @@ def calculate_split_bitrates(target_mb: float, durations: Sequence[float], audio
Args:
target_mb: Total desired target file size in megabytes.
durations: Sequence of segment durations in seconds.
- audio_kbps: Probed audio bitrate in kbps.
+ audio_kbps: Audio bitrate of the output in kbps.
Returns:
List of target video bitrates in kbps for each segment.
@@ -483,11 +491,128 @@ def check_audio_encoder_available(encoder_name: str = "aac") -> bool:
text=True,
env=get_clean_env(),
)
- return f"A..... {encoder_name}" in res.stdout or f"A...D. {encoder_name}" in res.stdout
+ # Rows are ""; the flag layout differs between FFmpeg versions.
+ return any(
+ len(parts) >= 2 and parts[0].startswith("A") and parts[1] == encoder_name
+ for parts in (line.split() for line in res.stdout.splitlines())
+ )
except (subprocess.SubprocessError, OSError):
return False
+def check_audio_decoder_available(codec_name: str) -> bool:
+ """Check if the active FFmpeg binary can decode an audio codec.
+
+ Args:
+ codec_name: Codec name as ffprobe reports it (e.g., `flac`).
+
+ Returns:
+ True if `ffmpeg -codecs` lists the codec as decodable, else False.
+
+ Example:
+ >>> check_audio_decoder_available("not-a-codec")
+ False
+ """
+ try:
+ res = subprocess.run(
+ [get_resource_path("ffmpeg"), "-hide_banner", "-codecs"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ env=get_clean_env(),
+ )
+ except (subprocess.SubprocessError, OSError) as e:
+ log.debug("Codec listing failed: %s", e)
+ return False
+ return any(
+ len(parts) >= 2 and parts[0].startswith("D") and parts[1] == codec_name
+ for parts in (line.split() for line in res.stdout.splitlines())
+ )
+
+
+def plan_audio(codec_name: str, source_kbps: int, target_mb: float, duration: float) -> Tuple[int, bool]:
+ """Decide between copying and re-encoding the audio.
+
+ Audio is copied unless it is lossless, or is above 160 kbps and would take
+ more than 10% of the target. Audio FFmpeg cannot decode is always copied.
+
+ Args:
+ codec_name: Source audio codec.
+ source_kbps: Source audio bitrate in kbps (0 for silent video).
+ target_mb: Target file size in megabytes.
+ duration: Video duration in seconds.
+
+ Returns:
+ (audio bitrate of the output in kbps, whether to re-encode).
+
+ Example:
+ >>> plan_audio("aac", 192, target_mb=110, duration=183)
+ (192, False)
+ """
+ if not source_kbps:
+ return 0, False
+ lossless = codec_name.startswith("pcm_") or codec_name in LOSSLESS_AUDIO_CODECS
+ over_budget = (
+ source_kbps > AUDIO_REENCODE_MIN_KBPS
+ and source_kbps * 1000 * duration > AUDIO_MAX_TARGET_SHARE * target_mb * MB_TO_BITS
+ )
+ if (
+ (lossless or over_budget)
+ and check_audio_encoder_available("aac")
+ and check_audio_decoder_available(codec_name)
+ ):
+ return AUDIO_REENCODE_KBPS, True
+ return source_kbps, False
+
+
+def estimate_bitrate(packets: Sequence[Tuple[float, int]]) -> int:
+ """Estimate a bitrate in bits per second from (timestamp, size) packets.
+
+ Args:
+ packets: Timestamps in seconds with packet sizes in bytes.
+
+ Returns:
+ Bits per second, or 0 when the packets span no time.
+
+ Example:
+ >>> estimate_bitrate([(0.0, 1000), (1.0, 1000)])
+ 8000
+ """
+ ordered = sorted(packets)
+ span = ordered[-1][0] - ordered[0][0] if ordered else 0.0
+ if span <= 0:
+ return 0
+ # The last packet's duration lies outside the span, so its size is left out.
+ return round(sum(size for _, size in ordered[:-1]) * 8 / span)
+
+
+def measure_audio_bitrate(input_path: str) -> int:
+ """Measure the first audio track's bitrate, for files that don't report one (MKV, WebM).
+
+ Args:
+ input_path: Path to the input media file.
+
+ Returns:
+ Bits per second, or 0 if it can't be measured.
+
+ Example:
+ >>> measure_audio_bitrate("missing.mkv")
+ 0
+ """
+ # shortcut: samples the first 30 s, read the whole track if VBR audio causes overshoot.
+ cmd = [
+ get_resource_path("ffprobe"), "-v", "error", "-read_intervals", f"%+{AUDIO_SAMPLE_S}",
+ "-select_streams", "a:0", "-show_entries", "packet=pts_time,size", "-of", "json", input_path,
+ ]
+ try:
+ out = subprocess.check_output(cmd, text=True, stderr=subprocess.PIPE, env=get_clean_env())
+ packets = [(float(p["pts_time"]), int(p["size"])) for p in json.loads(out)["packets"] if "pts_time" in p]
+ except (subprocess.CalledProcessError, OSError, ValueError, KeyError) as e:
+ log.debug("Audio bitrate measurement failed: %r", e)
+ return 0
+ return estimate_bitrate(packets)
+
+
@lru_cache(maxsize=4)
def check_bsf_available(bsf_name: str) -> bool:
"""Check if a bitstream filter is compiled into the active FFmpeg binary.
@@ -517,8 +642,75 @@ def check_bsf_available(bsf_name: str) -> bool:
return bsf_name in (line.strip() for line in res.stdout.splitlines())
-def build_concat_cmd(ffmpeg_exe: str, list_path: str, output_path: str, annexb_available: bool) -> List[str]:
- """Build the stream-copy command that stitches split segments.
+def build_audio_args(audio_kbps: int, input_index: int = 0, reencode: bool = False) -> List[str]:
+ """Build the audio mapping and codec arguments for an output.
+
+ Args:
+ audio_kbps: Audio bitrate of the output in kbps (0 for silent video, which drops audio).
+ input_index: FFmpeg input number that carries the source audio.
+ reencode: Re-encode to stereo AAC instead of copying (see `plan_audio`).
+
+ Returns:
+ Arguments to append to an FFmpeg output.
+
+ Example:
+ >>> build_audio_args(0)
+ ['-an']
+ >>> build_audio_args(128, input_index=1)
+ ['-map', '1:a:0?', '-c:a', 'copy']
+ """
+ if audio_kbps == 0:
+ return ["-an"]
+ if reencode:
+ codec = ["-c:a", "aac", "-b:a", f"{audio_kbps}k", "-ac", "2"]
+ else:
+ codec = ["-c:a", "copy"]
+ return ["-map", f"{input_index}:a:0?", *codec]
+
+
+def build_concat_list(first_path: str, second_path: str, split_time: float) -> str:
+ """Build the concat demuxer list for the two split segments.
+
+ The first segment's length is stated as the split time. Its reported
+ duration also counts its start offset (the encoder's reorder delay, which
+ grows with the duration of the first source frame), so when the two
+ segments start at different offsets the second one would otherwise be
+ placed late or early, leaving a gap or overlap at the split.
+
+ Args:
+ first_path: Segment covering 0 to the split time.
+ second_path: Segment covering the split time to the end.
+ split_time: Split timestamp in seconds.
+
+ Returns:
+ The list file contents.
+
+ Example:
+ >>> build_concat_list("a.mp4", "b.mp4", 1.5)
+ "file 'a.mp4'\\nduration 1.500000\\nfile 'b.mp4'\\n"
+ """
+ def quoted(path: str) -> str:
+ # Inside quotes, the concat demuxer only needs ' itself escaped: close, \', reopen.
+ return "'" + path.replace("'", "'\\''") + "'"
+
+ return f"file {quoted(first_path)}\nduration {split_time:.6f}\nfile {quoted(second_path)}\n"
+
+
+def build_concat_cmd(
+ ffmpeg_exe: str,
+ list_path: str,
+ output_path: str,
+ annexb_available: bool,
+ source_path: str,
+ audio_kbps: int,
+ reencode_audio: bool = False,
+) -> List[str]:
+ """Build the command that stitches video-only split segments and adds the source audio.
+
+ Segments are encoded without audio and the audio track is taken from the
+ source in one piece. Audio cut per segment ends on its own packet boundary,
+ which made the first segment longer than its video and opened a gap in the
+ video at the split.
The concat demuxer converts H.264 through `h264_mp4toannexb`, which also
tolerates differing parameter sets between segments. When the binary lacks
@@ -529,30 +721,76 @@ def build_concat_cmd(ffmpeg_exe: str, list_path: str, output_path: str, annexb_a
list_path: Concat list file naming the segments in order.
output_path: Destination video path.
annexb_available: Whether `h264_mp4toannexb` exists in the binary.
+ source_path: Original input video, used for its audio track.
+ audio_kbps: Audio bitrate of the output in kbps (0 for silent video).
+ reencode_audio: Re-encode the audio instead of copying it.
Returns:
A command list ready for subprocess execution.
Example:
- >>> build_concat_cmd("ffmpeg", "list.txt", "out.mp4", annexb_available=False)[6:9]
+ >>> build_concat_cmd("ffmpeg", "list.txt", "out.mp4", False, "in.mp4", 0)[6:9]
['-safe', '0', '-auto_convert']
"""
convert_args = [] if annexb_available else ["-auto_convert", "0"]
return [
ffmpeg_exe, "-hide_banner", "-v", "error",
"-f", "concat", "-safe", "0", *convert_args, "-i", list_path,
- "-c", "copy", "-movflags", "+faststart", "-y", output_path,
+ "-i", source_path, "-map", "0:v:0", *build_audio_args(audio_kbps, input_index=1, reencode=reencode_audio),
+ "-c:v", "copy", "-movflags", "+faststart", "-y", output_path,
]
-def get_video_info(input_path: str) -> Optional[Tuple[float, int, float, int, int, int]]:
+LOADER_ERROR_MARKER = "error while loading shared libraries"
+RUNTIME_LIBRARY_HINT = (
+ "Install the VA-API runtime libraries and try again:\n"
+ " Debian/Ubuntu: sudo apt install libva2 libva-drm2 libdrm2\n"
+ " Fedora: sudo dnf install libva libdrm\n"
+ " Arch: sudo pacman -S libva libdrm\n"
+ " openSUSE: sudo zypper install libva2 libva-drm2 libdrm2"
+)
+
+
+def find_missing_runtime_library(ffprobe_exe: str) -> Optional[str]:
+ """Return a user-facing message when FFmpeg cannot start for lack of a system library.
+
+ The Linux FFmpeg build links the VA-API libraries dynamically, so on systems
+ without them every FFmpeg call fails in the dynamic loader before it runs.
+
+ Args:
+ ffprobe_exe: Path to the ffprobe executable (linked like ffmpeg).
+
+ Returns:
+ The message naming the missing library with install commands, or None.
+
+ Example:
+ >>> find_missing_runtime_library("/nonexistent/ffprobe") is None
+ True
+ """
+ try:
+ res = subprocess.run(
+ [ffprobe_exe, "-version"], capture_output=True, text=True, timeout=10, env=get_clean_env(),
+ )
+ except (subprocess.TimeoutExpired, OSError) as e:
+ log.debug("ffprobe start check skipped: %s", e)
+ return None
+ stderr = res.stderr or ""
+ if res.returncode == 0 or LOADER_ERROR_MARKER not in stderr:
+ return None
+ detail = stderr.split(LOADER_ERROR_MARKER, 1)[1].strip(": \n").split(":", 1)[0]
+ log.error("FFmpeg cannot start: %s", stderr.strip())
+ return f"FFmpeg cannot start: missing system library {detail}.\n{RUNTIME_LIBRARY_HINT}"
+
+
+def get_video_info(input_path: str) -> Optional[Tuple[float, int, float, int, int, int, str]]:
"""Probe video metadata.
Args:
input_path: Path to the input media file.
Returns:
- Tuple of (duration_seconds, file_size_bytes, fps, audio_kbps, width, height), or None on failure.
+ Tuple of (duration_seconds, file_size_bytes, fps, audio_kbps, width, height, audio_codec),
+ or None on failure.
"""
ffprobe_exe = get_resource_path("ffprobe")
clean_env = get_clean_env()
@@ -581,23 +819,25 @@ def get_video_info(input_path: str) -> Optional[Tuple[float, int, float, int, in
# Audio probe: verify stream presence first to avoid phantom bitrate reservation
cmd_aud = [
ffprobe_exe, "-v", "error", "-select_streams", "a:0",
- "-show_entries", "stream=bit_rate", "-of", "json", input_path
+ "-show_entries", "stream=bit_rate,codec_name", "-of", "json", input_path
]
audio_bps = 0
+ audio_codec = ""
try:
aud_res = json.loads(subprocess.check_output(cmd_aud, text=True, env=clean_env))
aud_streams = aud_res.get('streams', [])
if aud_streams:
+ audio_codec = aud_streams[0].get('codec_name', '')
raw_br = aud_streams[0].get('bit_rate')
if raw_br and str(raw_br).isdigit():
audio_bps = int(raw_br)
else:
- audio_bps = 128000 # Default fallback if bitrate is VBR/unspecified
+ audio_bps = measure_audio_bitrate(input_path) or 128000 # fallback if it can't be measured
except (subprocess.CalledProcessError, ValueError, OSError, KeyError, IndexError):
audio_bps = 0
audio_kbps = math.ceil(audio_bps / 1000) if audio_bps > 0 else 0
- info = (float(dur_out), get_file_size(input_path), fps, audio_kbps, width, height)
+ info = (float(dur_out), get_file_size(input_path), fps, audio_kbps, width, height, audio_codec)
log.debug(
"Input: %dx%d @ %.3f fps, %.2f s, %d bytes, audio %d kbps",
width, height, fps, info[0], info[1], audio_kbps,
@@ -611,6 +851,76 @@ def get_video_info(input_path: str) -> Optional[Tuple[float, int, float, int, in
return None
+def get_hdr_source(input_path: str) -> Optional[HdrSource]:
+ """Return the HDR transfer and bit depth of the first video stream, or None for SDR.
+
+ Only PQ (`smpte2084`, HDR10) and HLG (`arib-std-b67`) count as HDR; BT.2020
+ primaries alone do not.
+
+ Example:
+ >>> get_hdr_source("sdr.mp4") is None # doctest: +SKIP
+ True
+ """
+ cmd = [
+ get_resource_path("ffprobe"), "-v", "error", "-select_streams", "v:0",
+ "-show_entries", "stream=color_transfer,pix_fmt,color_primaries,color_space", "-of", "json", input_path,
+ ]
+ try:
+ out = subprocess.check_output(cmd, text=True, stderr=subprocess.PIPE, env=get_clean_env())
+ stream = json.loads(out)["streams"][0]
+ except (subprocess.CalledProcessError, OSError, ValueError, KeyError, IndexError) as e:
+ log.debug("Could not read color transfer: %r", e)
+ return None
+ transfer = stream.get("color_transfer", "")
+ if transfer not in HDR_TRANSFERS:
+ return None
+ tags = read_first_frame_color(input_path) or stream
+ return HdrSource(
+ transfer,
+ is_high_bit_depth(stream.get("pix_fmt", "")),
+ has_transfer=tags.get("color_transfer", "") not in UNTAGGED_COLOR,
+ has_primaries=tags.get("color_primaries", "") not in UNTAGGED_COLOR,
+ has_matrix=tags.get("color_space", "") not in UNTAGGED_COLOR,
+ )
+
+
+def read_first_frame_color(input_path: str) -> Optional[Mapping[str, str]]:
+ """Return the first decoded frame's colour tags, which are what FFmpeg filters see.
+
+ The stream entry can show the container's tags while the frames have none.
+
+ Args:
+ input_path: Path to the input media file.
+
+ Returns:
+ The frame's fields, or None if no frame could be decoded.
+
+ Example:
+ >>> read_first_frame_color("missing.mp4") is None
+ True
+ """
+ cmd = [
+ get_resource_path("ffprobe"), "-v", "error", "-read_intervals", "%+#1", "-select_streams", "v:0",
+ "-show_entries", "frame=color_transfer,color_primaries,color_space", "-of", "json", input_path,
+ ]
+ try:
+ out = subprocess.check_output(cmd, text=True, stderr=subprocess.PIPE, env=get_clean_env())
+ return json.loads(out)["frames"][0]
+ except (subprocess.CalledProcessError, OSError, ValueError, KeyError, IndexError) as e:
+ log.debug("Could not read the first frame's colour tags: %r", e)
+ return None
+
+
+def is_high_bit_depth(pix_fmt: str) -> bool:
+ """Return True for pixel formats with more than 8 bits per sample.
+
+ Example:
+ >>> is_high_bit_depth("yuv420p10le"), is_high_bit_depth("p010le"), is_high_bit_depth("yuvj420p")
+ (True, True, False)
+ """
+ return bool(re.search(r"p1[0246]|1[0246](le|be)$", pix_fmt))
+
+
def get_smart_split_point(input_path: str, duration: float) -> float:
"""Find a keyframe-aligned split point at 50% of the video's total byte weight.
@@ -742,8 +1052,10 @@ def build_single_pass_cmd(
tgt_h: int,
tgt_fps: float,
audio_kbps: int = 128,
+ reencode_audio: bool = False,
tier: Tier = Tier.LEGACY,
vaapi_node: Optional[str] = None,
+ hdr: Optional[HdrSource] = None,
) -> List[str]:
"""Build a single-pass FFmpeg command for hardware encoders.
@@ -760,9 +1072,11 @@ def build_single_pass_cmd(
output_path: Destination video path.
tgt_h: Target height for scaling. Set to 0 or equal to src_h to skip scaling.
tgt_fps: Target frames per second. Set equal to src_fps to skip FPS conversion.
- audio_kbps: Probed audio bitrate in kbps (0 for silent video).
+ audio_kbps: Audio bitrate of the output in kbps (0 for silent video).
+ reencode_audio: Re-encode the audio instead of copying it.
tier: Hardware pipeline tier; LEGACY reproduces the pre-v1.2 arguments.
vaapi_node: Optional VA-API render node (e.g., `/dev/dri/renderD128`).
+ hdr: HDR properties of the source, else None.
Returns:
A command list ready for subprocess execution.
@@ -773,7 +1087,7 @@ def build_single_pass_cmd(
True
"""
video = build_video_args(
- backend_for_encoder(encoder), tier, src_h, tgt_h, src_fps, tgt_fps, codec_type, vaapi_node
+ backend_for_encoder(encoder), tier, src_h, tgt_h, src_fps, tgt_fps, codec_type, vaapi_node, hdr
)
cmd: List[str] = [ffmpeg_exe, "-y", *video.pre_input]
@@ -833,15 +1147,7 @@ def build_single_pass_cmd(
# Stream mapping
cmd.extend(["-map", "0:v:0"])
- # Audio Handling
- if audio_kbps == 0:
- cmd.append("-an")
- else:
- cmd.extend(["-map", "0:a:0?"])
- if audio_kbps > 160 and check_audio_encoder_available("aac"):
- cmd.extend(["-c:a", "aac", "-b:a", "128k", "-ac", "2"])
- else:
- cmd.extend(["-c:a", "copy"])
+ cmd.extend(build_audio_args(audio_kbps, reencode=reencode_audio))
# Single-pipe progress streaming on stderr
cmd.extend([
@@ -868,6 +1174,7 @@ def build_probe_cmd(
src_fps: float,
tgt_fps: float,
vaapi_node: Optional[str] = None,
+ hdr: Optional[HdrSource] = None,
) -> List[str]:
"""Build a one-second null-output encode of the real input for one tier.
@@ -882,6 +1189,7 @@ def build_probe_cmd(
src_fps: Source frames per second.
tgt_fps: Target frames per second.
vaapi_node: Optional VA-API render node.
+ hdr: HDR properties of the source, else None.
Returns:
A command list ready for subprocess execution.
@@ -892,7 +1200,7 @@ def build_probe_cmd(
'1'
"""
video = build_video_args(
- backend_for_encoder(encoder), tier, src_h, tgt_h, src_fps, tgt_fps, codec_type, vaapi_node
+ backend_for_encoder(encoder), tier, src_h, tgt_h, src_fps, tgt_fps, codec_type, vaapi_node, hdr
)
cmd: List[str] = [ffmpeg_exe, "-hide_banner", "-v", "error", *video.pre_input]
cmd.extend(["-t", "1", "-i", input_path, *video.post_input])
@@ -912,6 +1220,7 @@ def probe_pipeline_tier(
src_fps: float,
tgt_fps: float,
vaapi_node: Optional[str] = None,
+ hdr: Optional[HdrSource] = None,
) -> Tier:
"""Select the most GPU-resident pipeline tier that works on the real input.
@@ -928,6 +1237,8 @@ def probe_pipeline_tier(
src_fps: Source frames per second.
tgt_fps: Target frames per second.
vaapi_node: Optional VA-API render node.
+ hdr: HDR properties of the source, else None. Tone-mapped
+ sources always use LEGACY (the tone mapping runs on the CPU).
Returns:
The first tier whose probe encode succeeds, else `Tier.LEGACY`.
@@ -936,12 +1247,13 @@ def probe_pipeline_tier(
>>> probe_pipeline_tier("ffmpeg", "in.mp4", "libx265", "hevc", 1080, 720, 60.0, 30.0)
"""
- if backend_for_encoder(encoder) is None:
+ backend = backend_for_encoder(encoder)
+ if backend is None or hdr_handling(backend, codec_type, hdr) == "tonemap":
return Tier.LEGACY
for tier in PIPELINE_PROBE_TIERS:
cmd = build_probe_cmd(
ffmpeg_exe, input_path, encoder, codec_type, tier,
- src_h, tgt_h, src_fps, tgt_fps, vaapi_node,
+ src_h, tgt_h, src_fps, tgt_fps, vaapi_node, hdr,
)
if _run_probe(cmd, PIPELINE_PROBE_TIMEOUT_S, f"{encoder} {tier.label} pipeline"):
log.debug("Pipeline tier: %s", tier.label)
diff --git a/videocompress/encode.py b/videocompress/encode.py
index 86a5f6d..90b5669 100644
--- a/videocompress/encode.py
+++ b/videocompress/encode.py
@@ -14,8 +14,9 @@
import tempfile
import subprocess
import logging
+from contextlib import contextmanager
from pathlib import Path
-from typing import Callable, Tuple, Optional
+from typing import Callable, Iterator, Tuple, Optional
from rich.rule import Rule
@@ -25,19 +26,23 @@
get_clean_env,
get_file_size,
clean_log_file,
+ get_hdr_source,
get_video_info,
+ find_missing_runtime_library,
get_smart_split_point,
get_optimal_settings,
select_best_encoder,
build_single_pass_cmd,
build_concat_cmd,
+ build_concat_list,
check_bsf_available,
+ plan_audio,
probe_pipeline_tier,
resolve_vaapi_node,
calculate_video_bitrate,
calculate_split_bitrates,
)
-from videocompress.hwpipeline import Tier
+from videocompress.hwpipeline import HdrSource, Tier, backend_for_encoder, hdr_handling
from videocompress.progress import (
console,
show_encoder_detection,
@@ -50,6 +55,42 @@
log = logging.getLogger(__name__)
+@contextmanager
+def _discard_output_on_cancel(output_path: str) -> Iterator[None]:
+ """Delete the output if Ctrl+C interrupts the block after FFmpeg started writing it.
+
+ A file that was already at the path and is still untouched is kept.
+
+ Args:
+ output_path: File written inside the block.
+
+ Yields:
+ Nothing.
+
+ Example:
+ >>> with _discard_output_on_cancel("out.mp4"):
+ ... pass
+ """
+ def state() -> Optional[Tuple[int, int]]:
+ try:
+ info = os.stat(output_path)
+ except OSError:
+ return None
+ return info.st_size, info.st_mtime_ns
+
+ before = state()
+ try:
+ yield
+ except KeyboardInterrupt:
+ after = state()
+ if after and after != before:
+ try:
+ os.remove(output_path)
+ except OSError as e:
+ log.warning("Could not remove the partial output %s: %s", output_path, e)
+ raise
+
+
def _encode_hw_split(
ffmpeg_exe: str,
input_path: str,
@@ -66,6 +107,8 @@ def _encode_hw_split(
opt_fps: float,
tier: Tier = Tier.LEGACY,
vaapi_node: Optional[str] = None,
+ hdr: Optional[HdrSource] = None,
+ reencode_audio: bool = False,
) -> Tuple[bool, str]:
"""Execute parallel split single-pass encoding for hardware encoders.
@@ -78,13 +121,15 @@ def _encode_hw_split(
target_size_mb: Total target size in megabytes.
split_time: Timestamp in seconds marking the segment boundary.
durs: Tuple of (first_segment_duration, second_segment_duration) in seconds.
- audio_kbps: Probed audio bitrate in kbps.
+ audio_kbps: Audio bitrate of the output in kbps.
+ reencode_audio: Re-encode the audio instead of copying it.
fps: Source frames per second.
src_h: Source height in pixels.
opt_h: Target height for scaling.
opt_fps: Target frames per second.
tier: Hardware pipeline tier used for both segment commands.
vaapi_node: Optional VA-API render node.
+ hdr: HDR properties of the source, else None.
Returns:
Tuple of (success flag, error message).
@@ -112,9 +157,10 @@ def _encode_hw_split(
output_path=p1_path,
tgt_h=opt_h,
tgt_fps=opt_fps,
- audio_kbps=audio_kbps,
+ audio_kbps=0, # audio is added from the source when stitching
tier=tier,
vaapi_node=vaapi_node,
+ hdr=hdr,
)
cmd_b = build_single_pass_cmd(
ffmpeg_exe=ffmpeg_exe,
@@ -129,9 +175,10 @@ def _encode_hw_split(
output_path=p2_path,
tgt_h=opt_h,
tgt_fps=opt_fps,
- audio_kbps=audio_kbps,
+ audio_kbps=0, # audio is added from the source when stitching
tier=tier,
vaapi_node=vaapi_node,
+ hdr=hdr,
)
log.debug("Segment bitrates: %s kbps (split at %.3f s)", brs, split_time)
@@ -153,10 +200,13 @@ def _encode_hw_split(
with console.status("[bold cyan] Stitching segments...", spinner="dots"):
with open(list_path, "w", encoding="utf-8") as lf:
- lf.write(f"file '{p1_path}'\nfile '{p2_path}'")
+ lf.write(build_concat_list(p1_path, p2_path, split_time))
concat_cmd = build_concat_cmd(
ffmpeg_exe, list_path, output_path,
annexb_available=check_bsf_available("h264_mp4toannexb"),
+ source_path=input_path,
+ audio_kbps=audio_kbps,
+ reencode_audio=reencode_audio,
)
log.debug("Stitch command: %s", shlex.join(concat_cmd))
subprocess.run(
@@ -229,6 +279,8 @@ def _encode_cpu_single(
src_h: int,
opt_h: int,
opt_fps: float,
+ hdr: Optional[HdrSource] = None,
+ reencode_audio: bool = False,
) -> Tuple[bool, str]:
"""Execute serial single-pass encoding for CPU software fallback (libx265, libx264).
@@ -240,11 +292,13 @@ def _encode_cpu_single(
codec_type: "hevc" or "h264".
target_size_mb: Target size in megabytes.
duration: Total duration in seconds.
- audio_kbps: Probed audio bitrate in kbps.
+ audio_kbps: Audio bitrate of the output in kbps.
+ reencode_audio: Re-encode the audio instead of copying it.
fps: Input frames per second.
src_h: Source height in pixels.
opt_h: Target height for scaling.
opt_fps: Target frames per second.
+ hdr: HDR properties of the source (tone-mapped to SDR), else None.
Returns:
Tuple of (success flag, error message).
@@ -273,6 +327,8 @@ def _encode_cpu_single(
tgt_h=opt_h,
tgt_fps=opt_fps,
audio_kbps=audio_kbps,
+ reencode_audio=reencode_audio,
+ hdr=hdr,
)
log.debug("Bitrate: %s kbps", bitrate_k)
log.debug("Encode command: %s", shlex.join(cmd))
@@ -291,7 +347,7 @@ def _encode_cpu_single(
return (True, "") if success else (False, "CPU Encode Failed")
except KeyboardInterrupt:
console.print("\n[bold red]Cancelling...[/]")
- return False, "Cancelled by user"
+ raise
except Exception as e:
log.exception("CPU single-pass encode error")
return False, f"CPU encode error: {e}"
@@ -331,14 +387,25 @@ def compress_video(
if not os.path.exists(input_path):
return False, f"Input not found: {input_path}"
+ missing_library = find_missing_runtime_library(get_resource_path("ffprobe"))
+ if missing_library:
+ return False, missing_library
+
info = get_video_info(input_path)
if not info:
return False, f"Failed to extract video info from: {input_path}"
- duration, orig_bytes, fps, audio_kbps, src_w, src_h = info
-
+ duration, orig_bytes, fps, source_audio_kbps, src_w, src_h, audio_codec = info
if (orig_bytes / MB_TO_BYTES) <= target_size_mb:
return False, f"Already smaller than target: {orig_bytes / MB_TO_BYTES:.2f} MB <= {target_size_mb} MB"
+ audio_kbps, reencode_audio = plan_audio(audio_codec, source_audio_kbps, target_size_mb, duration)
+ log.debug(
+ "Audio: %s %d kbps -> %s at %d kbps",
+ audio_codec or "none", source_audio_kbps, "AAC stereo" if reencode_audio else "copy", audio_kbps,
+ )
+ hdr = get_hdr_source(input_path)
+ log.debug("HDR source: %s", hdr or "none (SDR)")
+
if output_path is None:
input_p = Path(input_path)
sz_str = f"{int(target_size_mb)}" if float(target_size_mb).is_integer() else f"{target_size_mb}"
@@ -363,60 +430,71 @@ def compress_video(
show_encoder_detection(detection_results)
split_info: Optional[str] = None
+ hdr_info = ""
+ if hdr:
+ keep = hdr_handling(backend_for_encoder(active_encoder), codec_type, hdr) == "keep"
+ depth = "10-bit" if hdr.ten_bit else "8-bit"
+ hdr_info = f" \u00b7 HDR kept ({depth})" if keep else " \u00b7 HDR tone-mapped to SDR"
# Branch 1: Hardware Encoders (Parallel Split Single-Pass)
if active_encoder not in ("libx265", "libx264"):
vaapi_node = resolve_vaapi_node(active_encoder) if "vaapi" in active_encoder else None
tier = probe_pipeline_tier(
ffmpeg_exe, input_path, active_encoder, codec_type,
- src_h, opt_h, fps, opt_fps, vaapi_node,
+ src_h, opt_h, fps, opt_fps, vaapi_node, hdr,
)
split_time = get_smart_split_point(input_path, duration)
durs_tuple = (split_time, duration - split_time)
split_info = f"{durs_tuple[0]:.1f}s + {durs_tuple[1]:.1f}s"
- ok, err, tier = _encode_hw_with_fallback(
- lambda t: _encode_hw_split(
+ with _discard_output_on_cancel(output_path):
+ ok, err, tier = _encode_hw_with_fallback(
+ lambda t: _encode_hw_split(
+ ffmpeg_exe=ffmpeg_exe,
+ input_path=input_path,
+ output_path=output_path,
+ active_encoder=active_encoder,
+ codec_type=codec_type,
+ target_size_mb=target_size_mb,
+ split_time=split_time,
+ durs=durs_tuple,
+ audio_kbps=audio_kbps,
+ reencode_audio=reencode_audio,
+ fps=fps,
+ src_h=src_h,
+ opt_h=opt_h,
+ opt_fps=opt_fps,
+ tier=t,
+ vaapi_node=vaapi_node,
+ hdr=hdr,
+ ),
+ tier,
+ )
+ mode_str = f"parallel split \u00b7 {tier.label}{hdr_info}"
+ if not ok:
+ clean_log_file()
+ return False, err
+
+ # Branch 2: CPU Fallback (Serial Single-Pass)
+ else:
+ mode_str = f"CPU single-pass{hdr_info}"
+ with _discard_output_on_cancel(output_path):
+ ok, err = _encode_cpu_single(
ffmpeg_exe=ffmpeg_exe,
input_path=input_path,
output_path=output_path,
active_encoder=active_encoder,
codec_type=codec_type,
target_size_mb=target_size_mb,
- split_time=split_time,
- durs=durs_tuple,
+ duration=duration,
audio_kbps=audio_kbps,
+ reencode_audio=reencode_audio,
fps=fps,
src_h=src_h,
opt_h=opt_h,
opt_fps=opt_fps,
- tier=t,
- vaapi_node=vaapi_node,
- ),
- tier,
- )
- mode_str = f"parallel split \u00b7 {tier.label}"
- if not ok:
- clean_log_file()
- return False, err
-
- # Branch 2: CPU Fallback (Serial Single-Pass)
- else:
- mode_str = "CPU single-pass"
- ok, err = _encode_cpu_single(
- ffmpeg_exe=ffmpeg_exe,
- input_path=input_path,
- output_path=output_path,
- active_encoder=active_encoder,
- codec_type=codec_type,
- target_size_mb=target_size_mb,
- duration=duration,
- audio_kbps=audio_kbps,
- fps=fps,
- src_h=src_h,
- opt_h=opt_h,
- opt_fps=opt_fps,
- )
+ hdr=hdr,
+ )
if not ok:
clean_log_file()
return False, err
diff --git a/videocompress/hwpipeline.py b/videocompress/hwpipeline.py
index 07ce2a9..32f36a3 100644
--- a/videocompress/hwpipeline.py
+++ b/videocompress/hwpipeline.py
@@ -6,7 +6,7 @@
from dataclasses import dataclass
from enum import Enum
-from typing import Callable, Dict, Optional, Tuple
+from typing import Callable, Dict, NamedTuple, Optional, Tuple
class Tier(Enum):
@@ -298,7 +298,7 @@ def _upload_args(
backend: HwBackend, node: Optional[str], tgt_h: Optional[int],
pix_fmt: str, src_fps: float, tgt_fps: float,
) -> VideoArgs:
- upload = ("format=nv12", backend.upload_filter)
+ upload = ("format=p010" if pix_fmt == "p010" else "format=nv12", backend.upload_filter)
return VideoArgs(
pre_input=backend.device_args(node),
filters=_fps_filters(backend, src_fps, tgt_fps) + upload + _scaler(backend, tgt_h, pix_fmt),
@@ -307,22 +307,24 @@ def _upload_args(
def _cpu_filters(
- src_h: int, tgt_h: int, src_fps: float, tgt_fps: float, codec_type: str,
+ src_h: int, tgt_h: int, src_fps: float, tgt_fps: float, codec_type: str, ten_bit: bool = False,
) -> Tuple[str, ...]:
filters = []
if tgt_fps < src_fps:
filters.append(f"fps={tgt_fps}")
if _needs_scale(src_h, tgt_h):
filters.append(f"scale=-2:{tgt_h}:flags=lanczos")
- if codec_type == "h264":
+ if ten_bit:
+ filters.append("format=p010le")
+ elif codec_type == "h264":
filters.append("format=yuv420p")
return tuple(filters)
def _legacy_nvenc_args(
- src_h: int, tgt_h: int, src_fps: float, tgt_fps: float, codec_type: str,
+ src_h: int, tgt_h: int, src_fps: float, tgt_fps: float, codec_type: str, ten_bit: bool = False,
) -> VideoArgs:
- pix_fmt = "yuv420p" if codec_type == "h264" else "nv12"
+ pix_fmt = "p010" if ten_bit else "yuv420p" if codec_type == "h264" else "nv12"
filters: Tuple[str, ...] = ()
if _needs_scale(src_h, tgt_h):
filters = (f"scale_cuda=-2:{tgt_h}:interp_algo=lanczos:format={pix_fmt}",)
@@ -336,26 +338,127 @@ def _legacy_nvenc_args(
def _legacy_vaapi_args(
- node: Optional[str], src_h: int, tgt_h: int, src_fps: float, tgt_fps: float,
+ node: Optional[str], src_h: int, tgt_h: int, src_fps: float, tgt_fps: float, ten_bit: bool = False,
) -> VideoArgs:
filters = list(_cpu_filters(src_h, tgt_h, src_fps, tgt_fps, "hevc"))
- filters.append("format=nv12,hwupload")
+ filters.append("format=p010,hwupload" if ten_bit else "format=nv12,hwupload")
return VideoArgs(pre_input=_vaapi_devices(node), filters=tuple(filters))
def _legacy_args(
backend: Optional[HwBackend], node: Optional[str], src_h: int, tgt_h: int,
- src_fps: float, tgt_fps: float, codec_type: str,
+ src_fps: float, tgt_fps: float, codec_type: str, ten_bit: bool = False,
) -> VideoArgs:
if backend is None:
return VideoArgs(filters=_cpu_filters(src_h, tgt_h, src_fps, tgt_fps, codec_type))
if backend.name == "nvenc":
- return _legacy_nvenc_args(src_h, tgt_h, src_fps, tgt_fps, codec_type)
+ return _legacy_nvenc_args(src_h, tgt_h, src_fps, tgt_fps, codec_type, ten_bit)
if backend.name == "vaapi":
- return _legacy_vaapi_args(node, src_h, tgt_h, src_fps, tgt_fps)
+ return _legacy_vaapi_args(node, src_h, tgt_h, src_fps, tgt_fps, ten_bit)
return VideoArgs(
pre_input=("-hwaccel", "auto"),
- filters=_cpu_filters(src_h, tgt_h, src_fps, tgt_fps, codec_type),
+ filters=_cpu_filters(src_h, tgt_h, src_fps, tgt_fps, codec_type, ten_bit),
+ )
+
+
+class HdrSource(NamedTuple):
+ """HDR properties of the source video stream.
+
+ Attributes:
+ transfer: `smpte2084` (PQ, HDR10) or `arib-std-b67` (HLG).
+ ten_bit: True when the source has more than 8 bits per sample.
+ has_transfer: False when only the container, not the frames, carries the transfer.
+ has_primaries: False when the frames' colour primaries are untagged.
+ has_matrix: False when the frames' YCbCr matrix is untagged.
+ """
+
+ transfer: str
+ ten_bit: bool
+ has_transfer: bool = True
+ has_primaries: bool = True
+ has_matrix: bool = True
+
+
+# HDR (PQ or HLG) to SDR BT.709, run on the CPU after scaling so it touches fewer pixels.
+TONEMAP_FILTERS = (
+ "zscale=t=linear:npl=100",
+ "format=gbrpf32le",
+ "zscale=p=bt709",
+ "tonemap=hable:desat=0",
+ "zscale=t=bt709:m=bt709:r=tv",
+)
+
+
+# Hardware decode into system memory for the CPU tone mapper. Explicit, because
+# `-hwaccel auto` can pick DXVA2, which fails without a desktop session.
+_TONEMAP_DECODE: Dict[str, Tuple[str, ...]] = {
+ "nvenc": ("-hwaccel", "cuda"),
+ "amf": ("-hwaccel", "d3d11va"),
+ "qsv": ("-hwaccel", "d3d11va"),
+ "videotoolbox": ("-hwaccel", "videotoolbox"),
+}
+
+
+def _tonemap_filters(hdr: HdrSource) -> Tuple[str, ...]:
+ """Return the tone-mapping chain adjusted to the source's transfer and tags.
+
+ Example:
+ >>> _tonemap_filters(HdrSource("arib-std-b67", True))[0]
+ 'zscale=t=linear:npl=100:agamma=0'
+ """
+ linearize, *rest = TONEMAP_FILTERS
+ if hdr.transfer == "arib-std-b67":
+ # The default agamma=1 applies HLG's system gamma per channel. Not for PQ: no gain, 2.5x slower.
+ linearize += ":agamma=0"
+ # zscale refuses untagged sources; HDR10 and HLG are BT.2020.
+ if not hdr.has_transfer:
+ linearize += f":tin={hdr.transfer}"
+ if not hdr.has_primaries:
+ linearize += ":pin=bt2020:p=bt2020"
+ if not hdr.has_matrix:
+ linearize += ":min=bt2020nc"
+ return (linearize, *rest)
+
+
+def hdr_handling(backend: Optional[HwBackend], codec_type: str, hdr: Optional[HdrSource]) -> str:
+ """Decide what happens to an HDR source.
+
+ Hardware HEVC keeps HDR at the source's bit depth (8 or 10). H.264 has no 10-bit hardware
+ encoders, and the bundled x265 is 8-bit on Linux and macOS, so every other
+ case is tone-mapped to SDR.
+
+ Example:
+ >>> hdr_handling(BACKENDS["nvenc"], "hevc", HdrSource("smpte2084", True))
+ 'keep'
+ >>> hdr_handling(BACKENDS["nvenc"], "h264", HdrSource("smpte2084", True))
+ 'tonemap'
+ >>> hdr_handling(None, "hevc", None)
+ 'sdr'
+ """
+ if not hdr:
+ return "sdr"
+ return "keep" if backend is not None and codec_type == "hevc" else "tonemap"
+
+
+def _keep_hdr_output(hdr: HdrSource) -> Tuple[str, ...]:
+ profile = ("-profile:v", "main10") if hdr.ten_bit else ()
+ return profile + ("-color_primaries", "bt2020", "-color_trc", hdr.transfer, "-colorspace", "bt2020nc")
+
+
+def _tonemap_args(
+ backend: Optional[HwBackend], node: Optional[str], src_h: int, tgt_h: int,
+ src_fps: float, tgt_fps: float, hdr: HdrSource,
+) -> VideoArgs:
+ filters = _cpu_filters(src_h, tgt_h, src_fps, tgt_fps, "hevc") + _tonemap_filters(hdr)
+ sdr_tags = ("-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709")
+ if backend is None:
+ return VideoArgs(filters=filters + ("format=yuv420p",), post_input=sdr_tags)
+ if backend.name == "vaapi":
+ return VideoArgs(
+ pre_input=_vaapi_devices(node), filters=filters + ("format=nv12", "hwupload"), post_input=sdr_tags,
+ )
+ return VideoArgs(
+ pre_input=_TONEMAP_DECODE[backend.name], filters=filters + ("format=nv12",), post_input=sdr_tags,
)
@@ -368,6 +471,7 @@ def build_video_args(
tgt_fps: float,
codec_type: str,
vaapi_node: Optional[str] = None,
+ hdr: Optional[HdrSource] = None,
) -> VideoArgs:
"""Build the decode, filter and upload arguments for one pipeline tier.
@@ -380,6 +484,7 @@ def build_video_args(
tgt_fps: Target frames per second. Not below `src_fps` disables fps limiting.
codec_type: `hevc` or `h264`.
vaapi_node: Optional VA-API render node (e.g. `/dev/dri/renderD128`).
+ hdr: HDR properties of the source, else None. See `hdr_handling` for what happens to it.
Returns:
The video arguments split into pre-input, filters and post-input parts.
@@ -389,10 +494,18 @@ def build_video_args(
>>> ",".join(args.filters)
'fps=30.0,scale_vaapi=w=-2:h=720:format=nv12'
"""
- if backend is None or tier is Tier.LEGACY:
- return _legacy_args(backend, vaapi_node, src_h, tgt_h, src_fps, tgt_fps, codec_type)
+ handling = hdr_handling(backend, codec_type, hdr)
+ if handling == "tonemap" and hdr is not None:
+ return _tonemap_args(backend, vaapi_node, src_h, tgt_h, src_fps, tgt_fps, hdr)
+ ten_bit = handling == "keep" and hdr is not None and hdr.ten_bit
- scaled_h = tgt_h if _needs_scale(src_h, tgt_h) else None
- pix_fmt = _target_pix_fmt(backend, codec_type)
- builder = _zero_copy_args if tier is Tier.ZERO_COPY else _upload_args
- return builder(backend, vaapi_node, scaled_h, pix_fmt, src_fps, tgt_fps)
+ if backend is None or tier is Tier.LEGACY:
+ args = _legacy_args(backend, vaapi_node, src_h, tgt_h, src_fps, tgt_fps, codec_type, ten_bit)
+ else:
+ scaled_h = tgt_h if _needs_scale(src_h, tgt_h) else None
+ pix_fmt = "p010" if ten_bit else _target_pix_fmt(backend, codec_type)
+ builder = _zero_copy_args if tier is Tier.ZERO_COPY else _upload_args
+ args = builder(backend, vaapi_node, scaled_h, pix_fmt, src_fps, tgt_fps)
+ if handling == "keep" and hdr:
+ args = VideoArgs(args.pre_input, args.filters, args.post_input + _keep_hdr_output(hdr))
+ return args
diff --git a/videocompress/progress.py b/videocompress/progress.py
index d654505..f83c3f6 100644
--- a/videocompress/progress.py
+++ b/videocompress/progress.py
@@ -16,6 +16,7 @@
from collections import deque
from typing import List, Tuple, Optional
+from rich import box
from rich.console import Console, RenderableType
from rich.live import Live
from rich.table import Table
@@ -28,7 +29,8 @@
log = logging.getLogger(__name__)
-console = Console(safe_box=True)
+# safe_box would turn rounded corners square in the console the right-click menu opens.
+console = Console(safe_box=False)
PROGRESS_KEYS = frozenset({"frame", "fps", "bitrate", "total_size", "out_time_us", "out_time", "speed", "progress"})
@@ -317,6 +319,7 @@ def build_dual_display(
bar_w = get_bar_width()
table = Table(
+ box=box.ROUNDED,
show_header=True,
header_style="bold dim",
border_style="dim",
@@ -382,6 +385,7 @@ def build_single_display(
bar_w = get_bar_width()
table = Table(
+ box=box.ROUNDED,
show_header=True,
header_style="bold dim",
border_style="dim",
@@ -422,6 +426,7 @@ def show_encoder_detection(results: List[Tuple[str, str]]) -> None:
console.print()
table = Table(
+ box=box.ROUNDED,
border_style="dim",
show_header=True,
header_style="bold dim",