From 5e6fd5a4fdb0cba339e193f676b6ca10a1d5e3bd Mon Sep 17 00:00:00 2001 From: SimpNick6703 Date: Sat, 21 Nov 2026 15:09:43 +0530 Subject: [PATCH 01/41] fix(split): encode segments video-only and add source audio when stitching Segment A copied its audio, which ends on an AAC packet boundary past its last video frame. The concat demuxer offsets segment B by A's full duration, leaving a 40-100 ms video gap at the split and video lagging audio for the second half. Segments are now encoded without audio and the stitch maps the source audio in one piece, via a shared build_audio_args. --- docs/index.html | 8 +++--- tests/test_concat.py | 26 ++++++++++++++++-- videocompress/core.py | 61 ++++++++++++++++++++++++++++++++--------- videocompress/encode.py | 6 ++-- 4 files changed, 79 insertions(+), 22 deletions(-) diff --git a/docs/index.html b/docs/index.html index 2cc080b..6c18115 100644 --- a/docs/index.html +++ b/docs/index.html @@ -883,15 +883,15 @@

Two workers in parallel

  • Step 4 · Stitch

    Join without re-encoding

    -
    ffmpeg -f concat -safe 0 -i list.txt
    -  -c copy -movflags +faststart
    -

    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.

    +
    ffmpeg -f concat -safe 0 -i list.txt -i input
    +  -map 0:v:0 -map 1:a:0? -c:v copy -movflags +faststart
    +

    Both halves are encoded without audio. The concat demuxer joins the video halves without re-encoding, takes the audio from the source in one piece (so nothing shifts at T), 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. + up to the current release, the stitch leaves a 40–100 ms gap in video timestamps at T, so playback stutters briefly there and video runs slightly behind audio for the second half. The stitch above fixes this and ships in the next release; see Known Issues.

    diff --git a/tests/test_concat.py b/tests/test_concat.py index ebe9078..f14e31c 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", "aac_available", "expected_audio"), + [ + (128, True, ["-map", "1:a:0?", "-c:a", "copy"]), + (320, 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( + monkeypatch: pytest.MonkeyPatch, audio_kbps: int, aac_available: 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. + monkeypatch.setattr(core, "check_audio_encoder_available", lambda encoder_name="aac": aac_available) + cmd = core.build_concat_cmd("ffmpeg", "list.txt", "out.mp4", annexb_available=True, source_path="in.mp4", audio_kbps=audio_kbps) + 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"), [ diff --git a/videocompress/core.py b/videocompress/core.py index a90fd30..ef306d0 100644 --- a/videocompress/core.py +++ b/videocompress/core.py @@ -517,8 +517,48 @@ 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) -> List[str]: + """Build the audio mapping and codec arguments for an output. + + Audio above 160 kbps is re-encoded to 128 kbps stereo AAC when the encoder + exists; otherwise the source audio is copied. Silent video drops audio. + + Args: + audio_kbps: Probed audio bitrate in kbps (0 for silent video). + input_index: FFmpeg input number that carries the source 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 audio_kbps > 160 and check_audio_encoder_available("aac"): + codec = ["-c:a", "aac", "-b:a", "128k", "-ac", "2"] + else: + codec = ["-c:a", "copy"] + return ["-map", f"{input_index}:a:0?", *codec] + + +def build_concat_cmd( + ffmpeg_exe: str, + list_path: str, + output_path: str, + annexb_available: bool, + source_path: str, + audio_kbps: int, +) -> 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,19 +569,22 @@ 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: Probed audio bitrate in kbps (0 for silent video). 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), + "-c:v", "copy", "-movflags", "+faststart", "-y", output_path, ] @@ -833,15 +876,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)) # Single-pipe progress streaming on stderr cmd.extend([ diff --git a/videocompress/encode.py b/videocompress/encode.py index 86a5f6d..d886604 100644 --- a/videocompress/encode.py +++ b/videocompress/encode.py @@ -112,7 +112,7 @@ 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, ) @@ -129,7 +129,7 @@ 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, ) @@ -157,6 +157,8 @@ def _encode_hw_split( 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, ) log.debug("Stitch command: %s", shlex.join(concat_cmd)) subprocess.run( From 6a10bab0824363dddecea0e34cc902c072451ea9 Mon Sep 17 00:00:00 2001 From: SimpNick6703 Date: Sat, 21 Nov 2026 15:09:51 +0530 Subject: [PATCH 02/41] feat(linux): explain missing VA-API runtime libraries before probing The Linux FFmpeg build links libva/libdrm dynamically. On minimal installs without them every FFmpeg call failed in the loader and the user saw only 'Failed to extract video info'. compress_video now starts ffprobe once and, on a loader error, stops with the missing library and install commands. --- tests/test_runtime_libs.py | 46 ++++++++++++++++++++++++++++++++++++++ videocompress/core.py | 41 +++++++++++++++++++++++++++++++++ videocompress/encode.py | 5 +++++ 3 files changed, 92 insertions(+) create mode 100644 tests/test_runtime_libs.py 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/videocompress/core.py b/videocompress/core.py index ef306d0..4e7cc72 100644 --- a/videocompress/core.py +++ b/videocompress/core.py @@ -588,6 +588,47 @@ def build_concat_cmd( ] +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]]: """Probe video metadata. diff --git a/videocompress/encode.py b/videocompress/encode.py index d886604..f28b7cd 100644 --- a/videocompress/encode.py +++ b/videocompress/encode.py @@ -26,6 +26,7 @@ get_file_size, clean_log_file, get_video_info, + find_missing_runtime_library, get_smart_split_point, get_optimal_settings, select_best_encoder, @@ -333,6 +334,10 @@ 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}" From fe965da7e6ade2f4a7380faeb5aad7a77b943b6e Mon Sep 17 00:00:00 2001 From: SimpNick6703 Date: Sat, 21 Nov 2026 15:09:51 +0530 Subject: [PATCH 03/41] feat(windows): right-click menu installer and --custom size prompt installer/windows.iss adds a per-user Video-Compression submenu for video files (20 MB, 50 MB, 100 MB, 1 GB, Custom...). The codec is chosen on a setup page; silent installs (WinGet) use HEVC unless /CODEC=h264 is given. --custom asks for the target size on the console. The release workflow builds the installer on the Windows job. --- .github/workflows/release.yml | 13 +++++ installer/windows.iss | 92 +++++++++++++++++++++++++++++++++++ tests/test_cli_custom.py | 54 ++++++++++++++++++++ videocompress/cli.py | 31 +++++++++++- 4 files changed, 188 insertions(+), 2 deletions(-) create mode 100644 installer/windows.iss create mode 100644 tests/test_cli_custom.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b51d9e2..da7fdca 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,6 +44,19 @@ 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" } + $version = $env:BUILD_VERSION.TrimStart('v') + & "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" "/DAppVersion=$version" "/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/installer/windows.iss b/installer/windows.iss new file mode 100644 index 0000000..400a623 --- /dev/null +++ b/installer/windows.iss @@ -0,0 +1,92 @@ +; 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; silent installs (WinGet) use HEVC unless +; `/CODEC=h264` is passed. Reinstall to change it. + +#ifndef AppVersion + #error Pass /DAppVersion= +#endif +#ifndef SourceExe + #error Pass /DSourceExe= +#endif + +#define AppName "Video-Compression" +#define AppUrl "https://github.com/SimpNick6703/Video-Compression" +#define MenuKey "Software\Classes\SystemFileAssociations\video\shell\VideoCompression" + +[Setup] +AppId={{004B68D8-64A4-46FA-8982-4B69DF87D66F} +AppName={#AppName} +AppVersion={#AppVersion} +AppPublisher=SimpNick6703 +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] +Root: HKA; Subkey: "{#MenuKey}"; ValueType: string; ValueName: "MUIVerb"; ValueData: "{#AppName}"; Flags: uninsdeletekey +Root: HKA; Subkey: "{#MenuKey}"; ValueType: string; ValueName: "SubCommands"; ValueData: "" +Root: HKA; Subkey: "{#MenuKey}"; ValueType: string; ValueName: "Icon"; ValueData: "{app}\videocompress.exe,0" +; 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 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'); + if CompareText(ExpandConstant('{param:CODEC|hevc}'), 'h264') = 0 then + CodecPage.SelectedValueIndex := 1 + else + CodecPage.SelectedValueIndex := 0; +end; + +function GetCodec(Param: string): string; +begin + if CodecPage.SelectedValueIndex = 1 then + Result := 'h264' + else + Result := 'hevc'; +end; diff --git a/tests/test_cli_custom.py b/tests/test_cli_custom.py new file mode 100644 index 0000000..cdc97b6 --- /dev/null +++ b/tests/test_cli_custom.py @@ -0,0 +1,54 @@ +"""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 diff --git a/videocompress/cli.py b/videocompress/cli.py index e0599a9..7e58c45 100644 --- a/videocompress/cli.py +++ b/videocompress/cli.py @@ -3,6 +3,7 @@ Usage: python -m videocompress [output.mp4] [target_mb] [hevc/h264] + python -m videocompress --custom [hevc/h264] (asks for the size) """ import sys @@ -43,6 +44,29 @@ def _try_parse_positive_float(value: str) -> Optional[float]: return None +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 +74,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 +86,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: @@ -96,6 +121,8 @@ def main() -> None: sys.exit(1) inp_path = str(input_file) + if custom_size: + target_mb = _prompt_target_mb() try: success, result = compress_video( From 54dc86d0635df1be9575c923ca804680a75bb9ec Mon Sep 17 00:00:00 2001 From: SimpNick6703 Date: Sat, 21 Nov 2026 15:09:51 +0530 Subject: [PATCH 04/41] chore: ignore launch film and local benchmark reports; drop bench_vitals --- .gitignore | 15 ++- tools/bench_vitals.py | 268 ------------------------------------------ 2 files changed, 11 insertions(+), 272 deletions(-) delete mode 100644 tools/bench_vitals.py diff --git a/.gitignore b/.gitignore index 405e9d0..a128817 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,11 @@ 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 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() From 8266b36b7f9d0371a4f8d033310f7e040cc609ba Mon Sep 17 00:00:00 2001 From: SimpNick6703 Date: Sat, 21 Nov 2026 15:09:51 +0530 Subject: [PATCH 05/41] docs: update known issues, add roadmap, captions for the launch film --- README.md | 33 ++++++------------- docs/assets/captions.vtt | 68 ++++++++++++++++++++++++++++++++-------- 2 files changed, 65 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index fb14f81..f5b0213 100644 --- a/README.md +++ b/README.md @@ -136,14 +136,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 @@ -180,25 +180,6 @@ 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 | @@ -239,8 +220,14 @@ If a compression fails, a `