diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..9aea878 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,4 @@ +# The C runtime is linked into the executable: without it, the program needs Microsoft's Visual C++ +# Redistributable (VCRUNTIME140.dll), which a fresh Windows does not have. One .exe, nothing to install. +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f14bd9c..89e9f97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,10 +52,17 @@ jobs: shell: pwsh run: choco install ffmpeg --yes --no-progress + # The executable embeds the third-party notices, generated by cargo-about. + - uses: taiki-e/install-action@v2 + with: + tool: cargo-about@0.9 + fallback: none + # The same checklist a developer runs: fmt, clippy -D warnings, rustdoc -D warnings, tests, - # documentation links, no video or personal path tracked, the release build and its zip. One script, - # so CI and a developer's machine cannot drift apart. - - name: Test, build and zip + # documentation links, no video or personal path tracked, then the release executable (with its + # commit and third-party notices inside) and its checksum. One script, so CI and a developer's + # machine cannot drift apart. + - name: Test and build the release executable shell: pwsh run: .\scripts\build.ps1 release @@ -66,10 +73,10 @@ jobs: $version = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"([^"]+)"').Matches[0].Groups[1].Value "version=$version" >> $env:GITHUB_OUTPUT - # GitHub serves every artifact as a zip of its own: level 0 keeps it a plain container around the zip. - uses: actions/upload-artifact@v7 with: name: quick-video-transcoder-${{ steps.version.outputs.version }}-windows-x64 - path: dist/*.zip - compression-level: 0 + path: | + dist/quick-video-transcoder.exe + dist/SHA256SUMS.txt if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4056138..2984e52 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,20 +1,18 @@ name: Release # A tag alone produces the release: push vX.Y.Z and this runs the same checklist a developer runs, builds -# the zip from that exact commit, attests it, and publishes it with its checksum. Nothing is built or -# uploaded by hand. +# the executable from that exact commit, attests it, and publishes it with its checksum. Nothing is built +# or uploaded by hand. on: push: tags: ['v*'] -# Publishing, and the attestation: the OIDC token signs it, the others store it with the files it vouches -# for. +# Publishing, and the attestation: the OIDC token signs it, `attestations` stores it. permissions: contents: write id-token: write attestations: write - artifact-metadata: write concurrency: group: release-${{ github.ref }} @@ -48,22 +46,22 @@ jobs: } "QVT_VERSION=$version" | Add-Content $env:GITHUB_ENV - - name: Test, build and zip + - uses: taiki-e/install-action@v2 + with: + tool: cargo-about@0.9 + fallback: none + + # quick-video-transcoder.exe, SHA256SUMS.txt and notes.md (the changelog section of this version), + # all in dist\. + - name: Test, build and package shell: pwsh run: .\scripts\build.ps1 release - # The section of the changelog for this version is the release's notes; no section, no release. - - name: Checksum and notes + # No dated changelog section, no release: the tag stays without one until it is fixed. + - name: The changelog has this version's notes shell: pwsh run: | - $zip = "dist\quick-video-transcoder-$env:QVT_VERSION-windows-x64.zip" - $hash = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLowerInvariant() - "$hash $(Split-Path -Leaf $zip)" | Set-Content -NoNewline -Encoding ascii dist\SHA256SUMS.txt - $changelog = Get-Content CHANGELOG.md -Raw - $pattern = "(?ms)^## \[$([regex]::Escape($env:QVT_VERSION))\] - \d{4}-\d{2}-\d{2}\s*$(.*?)(?=^## \[|\z)" - $match = [regex]::Match($changelog, $pattern) - if (-not $match.Success) { throw "CHANGELOG.md has no dated section for $env:QVT_VERSION" } - $match.Groups[1].Value.Trim() | Set-Content -Encoding utf8 dist\notes.md + if (-not (Test-Path dist\notes.md)) { throw "CHANGELOG.md has no dated section for $env:QVT_VERSION" } - name: Attest the release files uses: actions/attest@v4 @@ -76,7 +74,7 @@ jobs: GH_TOKEN: ${{ github.token }} run: | gh release create $env:GITHUB_REF_NAME ` - "dist\quick-video-transcoder-$env:QVT_VERSION-windows-x64.zip" ` + dist\quick-video-transcoder.exe ` dist\SHA256SUMS.txt ` --title "Quick Video Transcoder $env:QVT_VERSION" ` --notes-file dist\notes.md ` diff --git a/AGENTS.md b/AGENTS.md index 20206b3..3c9d5be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,6 +43,9 @@ src/plan.rs frame rates, sizes, ladder, budget src/estimate.rs si src/encode.rs encode, size check, retry src/naming.rs output and partial names src/ffmpeg/ probe, encoders, filters, hardware, decoder (preview), audio src/player.rs preview playback src/audio.rs cpal output and clock src/thumbnails.rs strip +src/main.rs arguments, log file, crash box, window src/instance.rs one window, later launches' files +src/sendto.rs the Send to shortcut src/build_info.rs + build.rs version, commit, icon +assets/icon/ the icon: SVG source, .ico and .png from scripts/render-icon.ps1 tests/pipeline.rs end to end on synthetic clips examples/transcode.rs measurement on a video ``` @@ -57,6 +60,8 @@ tests/pipeline.rs end to end on synthetic clips examples/transcode.rs - egui: `lost_focus()` lasts two frames, apply a text field only if the user typed in it (`time_edit`); sliders use `SliderClamping::Edits`. Some symbols are missing from egui's fonts (arrows, most emoji): check a screenshot after adding one. +- `QVT_PRETEND_NO_FFMPEG=1` (debug builds) shows the *FFmpeg is needed* window without uninstalling + FFmpeg. Never click *Install FFmpeg for me* while testing: it really runs winget. - Checking the UI without driving it: `QVT_SCREENSHOT=` saves the window once the queue is estimated and the preview shows a frame, then quits. Run it on synthetic clips in a scratch folder. @@ -65,9 +70,16 @@ tests/pipeline.rs end to end on synthetic clips examples/transcode.rs ```powershell .\scripts\build.ps1 # fmt, clippy -D warnings, rustdoc -D warnings, tests, doc links, no video / personal path .\scripts\build.ps1 build # + release build -.\scripts\build.ps1 release # + clean tree, zip in dist\ +.\scripts\build.ps1 release # + clean tree, notices, the .exe, SHA256SUMS.txt and notes.md in dist\ (needs cargo-about) ``` +- **One file.** A release is `quick-video-transcoder.exe` alone: static C runtime, icon, third-party + notices (`--licenses`, *About*) inside. FFmpeg stays outside, found on the `PATH` or installed with + winget on the user's request. Keep it that way: nothing a user must unpack or install beside it. +- **Documentation ships at its commit.** `build.rs` stamps the commit into the executable; *About* and + `--version` link the documentation *of that commit*. A change updates the README, `docs/` and module doc + comments in the same commit, or the build that carries it links stale pages forever. + - Run `test` before every commit and read its whole output; never pipe it into `Select-Object -First`. - Commit only when asked. Messages say what and why, ending with the `Co-Authored-By` line. - **The changelog is the agent's to write**: each line is something the user sees or does, under *Added*, @@ -81,7 +93,11 @@ tests/pipeline.rs end to end on synthetic clips examples/transcode.rs ## Pitfalls that have already cost time - Shell heredocs and inline strings eat backslashes: any script with a backslash goes through a file - written by an editing tool, never a heredoc. + written by an editing tool, never a heredoc. A Python heredoc editing a workflow turned `\b` into a + backspace and `\n` into a line break in `release.yml` (2026-11-23). +- A PowerShell regex built in a double-quoted string runs `$(...)` as a subexpression: the release notes + pattern did, and would have failed the first tag. Build patterns from single-quoted pieces; `build.ps1` + tests the extraction on a sample changelog every run. - A shell started by the Claude desktop app may read `%APPDATA%` through the package's private copy: the profiles file seen from such a shell may not be the one the application reads. - `-hwaccel vulkan` silently falls back to software decoding for a codec Vulkan cannot decode, and diff --git a/CHANGELOG.md b/CHANGELOG.md index a13ba7d..ed1e8a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,9 +36,26 @@ refuses a tag without one. is read as 59.94 fps and encoded at 29.97 fps, not 28. - *Copy* puts encoded files on the clipboard, ready to paste into a conversation; *Show* opens their folder. -- `install-sendto.ps1` adds the application to Explorer's *Send to* menu. +- *File → Add to Explorer's Send to menu* adds the application to *Send to*, no script needed; *Remove* + takes it away. +- One window at a time: videos sent while the window is open join its queue. +- An icon, for the program, its window, the taskbar and *Send to*, and a version in the file's + properties. +- *Help → About* shows the version and the commit it was built from, and *Help → Documentation* opens the + documentation as it was for that build. +- If FFmpeg is missing or too old, a window says how to install it, offers to do it with winget, and + checks again; FFmpeg installed while Windows was running is found without signing out. +- A log of the last two runs in the data folder, and a message naming it if the window cannot open or + the application stops. +- One file, nothing to install: the release is `quick-video-transcoder.exe` alone, the C runtime and the + third-party licences inside (*Help → About*). Replacing the file updates it. ### Fixed - The buttons' symbols are monochrome again, drawn with the window's own fonts instead of the system's colour emoji. +- A GPU encoder is only used if it accepts the options the encode needs (B-frames, lookahead, + multipass), so an older GPU no longer fails every estimate. +- AV1 on the CPU (SVT-AV1) works: its encode was refused for a peak rate it does not support. +- With only CPU encoders, the queue no longer pauses for minutes to measure parallel encodes: one encode + at a time, which already uses every core. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 662aada..0fdd6db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,10 +11,16 @@ FFmpeg on the `PATH` for the end-to-end test. Before committing, run the same ch ```powershell .\scripts\build.ps1 # fmt, clippy, rustdoc, tests, doc links, no video or personal path tracked .\scripts\build.ps1 build # the same, then a release build -.\scripts\build.ps1 release # from a clean tree: the same, then the zip in dist\ +.\scripts\build.ps1 release # from a clean tree: the same, then the release .exe and its checksum in dist\ ``` -Warnings are errors, in clippy and in rustdoc. +Warnings are errors, in clippy and in rustdoc. The C runtime is linked statically (`.cargo/config.toml`), +so the executable runs without the Visual C++ Redistributable. The third-party notices it embeds need +[cargo-about](https://github.com/EmbarkStudios/cargo-about) (`cargo install cargo-about --locked --features cli`); +`about.toml` lists the licences accepted. The icon and the version block are compiled in by `build.rs` +with `rc.exe` from the Windows SDK (installed with the MSVC build tools); without it the build still works, +without an icon. After editing `assets/icon/quick-video-transcoder.svg`, run `.\scripts\render-icon.ps1` +(needs Microsoft Edge) and commit the three files. Measuring the size fitting on a real video, without the window (the video is only read; the output folder must exist and differ from the video's): diff --git a/README.md b/README.md index 815df98..8303fd1 100644 --- a/README.md +++ b/README.md @@ -30,24 +30,35 @@ Nothing is ever overwritten: an output name that exists gets ` (2)`, and the sou ## Requirements -- Windows 10 or 11 (64-bit). Linux and macOS build, but are not tested. -- [FFmpeg](https://ffmpeg.org/download.html) 7 or later on the `PATH`, for instance the *full* build from - [gyan.dev](https://www.gyan.dev/ffmpeg/builds/) or `winget install Gyan.FFmpeg`. GPU tone mapping needs - an FFmpeg built with libplacebo and Vulkan (the gyan.dev full build is); without it the CPU filters are - used. -- A GPU encoder makes it fast: NVIDIA NVENC, Intel Quick Sync or AMD AMF. The CPU encoders work too. +- Windows 10 or 11 (64-bit), with a graphics driver supporting DirectX 12 or Vulkan. Linux and macOS + build, but are not tested. +- [FFmpeg](https://ffmpeg.org/download.html) 7 or later, a separate free program. If it is missing, the + application says so and, when Windows' package manager winget is there, offers to install it for you + (the `Gyan.FFmpeg` package, for your account only); it is then found without signing out. To install it + yourself: `winget install --id Gyan.FFmpeg -e` in Terminal, or the *release full* build from + [gyan.dev](https://www.gyan.dev/ffmpeg/builds/) with its `bin` folder added to the `Path`. GPU tone + mapping needs an FFmpeg built with libplacebo and Vulkan (the gyan.dev full build is); without it the + CPU filters are used. +- A GPU encoder makes it fast: NVIDIA NVENC, Intel Quick Sync or AMD AMF. The CPU encoders work too, + slowly. **Tested on NVIDIA GPUs only**: Quick Sync and AMF are detected and used, but have not been + tried on real hardware yet. ## Install -1. Download the zip from the [latest release](https://github.com/Geeooff/quick-video-transcoder/releases/latest) - and extract it where you keep your tools. -2. To add it to Explorer's *Send to* menu, run the script that comes with it: +Nothing to install: the program is one file. - ```powershell - .\install-sendto.ps1 - ``` +1. Download `quick-video-transcoder.exe` from the + [latest release](https://github.com/Geeooff/quick-video-transcoder/releases/latest) and put it where + you keep your tools. +2. Start it. The program is not signed, so the first time Windows may show *Windows protected your PC*: + click *More info*, then *Run anyway*. To check the download first, compare it with `SHA256SUMS.txt` on + the release page, or verify where it was built with + `gh attestation verify quick-video-transcoder.exe --repo Geeooff/quick-video-transcoder`. +3. *File → Add to Explorer's Send to menu*. Moved the file? Do it again: the shortcut follows. + *File → Remove from Explorer's Send to menu* takes it away. - `.\install-sendto.ps1 -Remove` takes it away. +To update, replace the file with the new one (same name: the *Send to* shortcut keeps working). Only one +window opens: videos sent while it is open join its queue. ## Use @@ -59,7 +70,15 @@ Nothing is ever overwritten: an output name that exists gets ` (2)`, and the sou application measures it once, in a few seconds, the first time it runs on a GPU. 5. *Copy* on an encoded video, then paste it into the conversation. -Keyboard shortcuts are under *Help*. +Keyboard shortcuts are under *Help*, with *About* (the version, and this documentation as it was for +that version). + +## When something goes wrong + +The application keeps a log of its last two runs in its data folder (*Profiles → Open profiles.toml +folder*): `quick-video-transcoder.log` and `quick-video-transcoder.previous.log`. *View → Log* shows the +current one in the window. If the window cannot open or the application stops, a message says why and +names the log; attach it to an [issue](https://github.com/Geeooff/quick-video-transcoder/issues). ## Profiles @@ -109,4 +128,6 @@ for what is documented and how to measure it. ## License -MIT. See [LICENSE](LICENSE). FFmpeg is not included; it has its own licenses. +MIT. See [LICENSE](LICENSE). The libraries built in are listed with their licences in the program +(*Help → About*, *third-party libraries and their licences*). FFmpeg is not included; it has its own +licenses. diff --git a/about.hbs b/about.hbs new file mode 100644 index 0000000..e196048 --- /dev/null +++ b/about.hbs @@ -0,0 +1,34 @@ + + + + + Quick Video Transcoder: third-party notices + + + +

Third-party notices

+

Quick Video Transcoder is built with the open-source libraries below, under the licences that + follow. FFmpeg is not included: it is a separate program, installed by the user.

+

Licences used

+ + {{#each licenses}} +

{{name}}

+

Used by:

+ +
{{text}}
+ {{/each}} + + diff --git a/about.toml b/about.toml new file mode 100644 index 0000000..e144f8c --- /dev/null +++ b/about.toml @@ -0,0 +1,22 @@ +# cargo-about: the licences the third-party notices may contain (scripts\build.ps1 release fails on any +# other, so a dependency under a new licence is a decision, not an accident). +accepted = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-2-Clause", + "BSD-3-Clause", + "BSL-1.0", + "ISC", + "Zlib", + "Unicode-3.0", + "Unicode-DFS-2016", + "OFL-1.1", + "Ubuntu-font-1.0", + "MPL-2.0", + "CC0-1.0", + "MIT-0", +] +targets = ["x86_64-pc-windows-msvc"] +ignore-build-dependencies = true +ignore-dev-dependencies = true diff --git a/assets/icon/quick-video-transcoder-256.png b/assets/icon/quick-video-transcoder-256.png new file mode 100644 index 0000000..133cc94 Binary files /dev/null and b/assets/icon/quick-video-transcoder-256.png differ diff --git a/assets/icon/quick-video-transcoder.ico b/assets/icon/quick-video-transcoder.ico new file mode 100644 index 0000000..57afa82 Binary files /dev/null and b/assets/icon/quick-video-transcoder.ico differ diff --git a/assets/icon/quick-video-transcoder.svg b/assets/icon/quick-video-transcoder.svg new file mode 100644 index 0000000..c94daeb --- /dev/null +++ b/assets/icon/quick-video-transcoder.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..cadb3e4 --- /dev/null +++ b/build.rs @@ -0,0 +1,243 @@ +//! Stamps the commit the executable is built from, embeds the third-party notices, and gives the +//! executable its icon and version block: everything a user needs is in the one `.exe`. +//! +//! The commit makes a documentation link that cannot rot: the *About* window and `--version` link the +//! documentation of the exact revision that is running. +//! +//! The notices are generated by `cargo about` (`scripts/build.ps1`, which passes their path in +//! `QVT_NOTICES`); a build without them embeds a page saying where they come from, and the release +//! refuses such an executable. +//! +//! Nothing here fails a build. Source unpacked from an archive has no `.git`, a machine without git or +//! without the Windows SDK still builds: the commit then reads "unknown" and the executable has no icon. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn main() { + watch_head(); + println!("cargo:rerun-if-changed=src"); + println!("cargo:rerun-if-changed=Cargo.toml"); + + let commit = git(&["rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".to_owned()); + let known = commit != "unknown"; + let short = if known { + commit[..8].to_owned() + } else { + commit.clone() + }; + // Untracked files count: a source file nobody added yet is still a difference from that commit. + let dirty = known && git(&["status", "--porcelain"]).is_some_and(|s| !s.is_empty()); + + println!("cargo:rustc-env=QVT_COMMIT={commit}"); + println!("cargo:rustc-env=QVT_COMMIT_SHORT={short}"); + println!( + "cargo:rustc-env=QVT_DIRTY={}", + if dirty { "-dirty" } else { "" } + ); + // Documentation of an unknown build points at `main`, the best guess left. + println!( + "cargo:rustc-env=QVT_DOC_REF={}", + if known { commit.as_str() } else { "main" } + ); + + embed_notices(); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + embed_resources(&short, dirty); + } +} + +/// Copies the notices named by `QVT_NOTICES` to `OUT_DIR/third-party-notices.html`, where the program +/// includes them, or writes a placeholder; `QVT_NOTICES_COMPLETE` tells which. +fn embed_notices() { + println!("cargo:rerun-if-env-changed=QVT_NOTICES"); + let out = PathBuf::from(std::env::var("OUT_DIR").expect("cargo sets this")); + let target = out.join("third-party-notices.html"); + let notices = std::env::var_os("QVT_NOTICES").map(PathBuf::from); + if let Some(source) = ¬ices { + println!("cargo:rerun-if-changed={}", source.display()); + } + let copied = notices + .as_deref() + .is_some_and(|source| std::fs::copy(source, &target).is_ok()); + if !copied { + if notices.is_some() { + println!("cargo:warning=cannot read QVT_NOTICES, embedding a placeholder"); + } + let placeholder = "Third-party notices\ +

This build was made without its third-party notices. Releases carry them; to generate \ + them, run cargo about generate about.hbs in the source.

"; + std::fs::write(&target, placeholder).expect("OUT_DIR is writable"); + } + println!("cargo:rustc-env=QVT_NOTICES_COMPLETE={copied}"); +} + +/// The icon Explorer, the taskbar and *Send to* show, and the version block of the file's properties. +/// +/// Compiled by `rc.exe` from the Windows SDK, which every MSVC toolchain installs with the linker: both +/// are PE resources, which no code can set at run time. `FileVersion` carries the commit, +/// `ProductVersion` the plain version, and a tree with uncommitted changes is flagged a private build. +fn embed_resources(commit: &str, dirty: bool) { + let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets this")); + let icon = manifest + .join("assets") + .join("icon") + .join("quick-video-transcoder.ico"); + let license = manifest.join("LICENSE"); + println!("cargo:rerun-if-changed={}", icon.display()); + println!("cargo:rerun-if-changed={}", license.display()); + let Some(rc) = find_resource_compiler() else { + println!("cargo:warning=rc.exe not found, building without icon or version block"); + return; + }; + + let version = std::env::var("CARGO_PKG_VERSION").expect("cargo sets this"); + let mut numbers = version + .split(['.', '-']) + .map(|part| part.parse::().unwrap_or(0)); + let mut next = || numbers.next().unwrap_or(0); + let (major, minor, patch) = (next(), next(), next()); + let author = std::env::var("CARGO_PKG_AUTHORS").unwrap_or_default(); + let repository = std::env::var("CARGO_PKG_REPOSITORY").unwrap_or_default(); + // The LICENSE file holds the one copyright line; the resource repeats it. + let copyright = std::fs::read_to_string(&license) + .ok() + .and_then(|text| { + text.lines() + .find(|line| line.starts_with("Copyright")) + .map(str::to_owned) + }) + .unwrap_or_default(); + let (flags, private) = if dirty { + ( + "0x8", // VS_FF_PRIVATEBUILD + " VALUE \"PrivateBuild\", \"Built from a tree with uncommitted changes\\0\"\n", + ) + } else { + ("0x0", "") + }; + + // Resource id 1 is the application icon. FILEOS 0x40004 is VOS_NT_WINDOWS32, FILETYPE 1 VFT_APP, + // the string block en-US Unicode. In rc.exe's language `\` starts an escape inside a quoted string: + // every value goes through `rc_string`, and each `\0` written here is the terminator rc.exe expects. + let script = format!( + r#"1 ICON "{icon}" +1 VERSIONINFO +FILEVERSION {major},{minor},{patch},0 +PRODUCTVERSION {major},{minor},{patch},0 +FILEFLAGSMASK 0x3f +FILEFLAGS {flags} +FILEOS 0x40004 +FILETYPE 0x1 +FILESUBTYPE 0x0 +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "{author}\0" + VALUE "FileDescription", "Quick Video Transcoder\0" + VALUE "FileVersion", "{version} ({commit})\0" + VALUE "InternalName", "quick-video-transcoder\0" + VALUE "LegalCopyright", "{copyright}. MIT License.\0" + VALUE "OriginalFilename", "quick-video-transcoder.exe\0" + VALUE "ProductName", "Quick Video Transcoder\0" + VALUE "ProductVersion", "{version}\0" + VALUE "Comments", "{repository}\0" +{private} END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +"#, + icon = rc_string(&icon.display().to_string()), + author = rc_string(&author), + version = rc_string(&version), + commit = rc_string(commit), + copyright = rc_string(©right), + repository = rc_string(&repository), + ); + let out = PathBuf::from(std::env::var("OUT_DIR").expect("cargo sets this")); + let source = out.join("quick-video-transcoder.rc"); + let compiled = out.join("quick-video-transcoder.res"); + if std::fs::write(&source, script).is_err() { + println!("cargo:warning=cannot write the resource script, building without resources"); + return; + } + let status = Command::new(&rc) + .args(["/nologo", "/fo"]) + .arg(&compiled) + .arg(&source) + .status(); + match status { + // The executable only: the examples and tests have no use for it. + Ok(status) if status.success() => println!( + "cargo:rustc-link-arg-bin=quick-video-transcoder={}", + compiled.display() + ), + _ => println!("cargo:warning=rc.exe failed, building without resources"), + } +} + +/// A value for a quoted string of an rc.exe script: `\` escapes as in C, a quote is doubled. +fn rc_string(value: &str) -> String { + value.replace('\\', r"\\").replace('"', r#""""#) +} + +/// The SDK's resource compiler: the developer prompt's variable first, then the newest Windows Kit. +fn find_resource_compiler() -> Option { + if let Some(dir) = std::env::var_os("WindowsSdkVerBinPath") { + let candidate = Path::new(&dir).join("x64").join("rc.exe"); + if candidate.exists() { + return Some(candidate); + } + } + let program_files = + std::env::var_os("ProgramFiles(x86)").or_else(|| std::env::var_os("ProgramFiles"))?; + let bin = Path::new(&program_files) + .join("Windows Kits") + .join("10") + .join("bin"); + // Version folders are zero-padded (10.0.NNNNN.0): sorted, the last is the newest. + let mut versions: Vec = std::fs::read_dir(bin) + .ok()? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path.is_dir()) + .collect(); + versions.sort(); + versions.iter().rev().find_map(|version| { + ["x64", "x86"] + .iter() + .map(|arch| version.join(arch).join("rc.exe")) + .find(|candidate| candidate.exists()) + }) +} + +/// Re-runs this script when the checked-out commit changes. `.git/HEAD` alone is not enough: on a +/// branch it holds `ref: refs/heads/` and does not change on commit, the ref file does (or +/// `packed-refs` once packed). +fn watch_head() { + println!("cargo:rerun-if-changed=.git/HEAD"); + let Ok(head) = std::fs::read_to_string(".git/HEAD") else { + return; + }; + if let Some(reference) = head.trim().strip_prefix("ref: ") { + println!("cargo:rerun-if-changed=.git/{reference}"); + println!("cargo:rerun-if-changed=.git/packed-refs"); + } +} + +/// Runs git and returns its trimmed output, or `None` for any failure. +fn git(args: &[&str]) -> Option { + let output = Command::new("git").args(args).output().ok()?; + output + .status + .success() + .then(|| String::from_utf8(output.stdout).ok()) + .flatten() + .map(|s| s.trim().to_owned()) +} diff --git a/docs/architecture.md b/docs/architecture.md index 5e652a6..6e7dbd9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,6 +19,10 @@ on the GPU by libplacebo. | `src/ffmpeg/` | Probe, encoders, filters, hardware detection, preview decoder, audio decoder. | | `src/player.rs`, `src/audio.rs` | Preview playback with the sound as master clock (`cpal`). | | `src/thumbnails.rs` | The thumbnail strip, by parallel seeks. | +| `src/instance.rs` | One window: a second launch hands its files to the open one. | +| `src/sendto.rs` | The *Send to* shortcut. | +| `src/build_info.rs`, `build.rs` | The version, the commit, links to the documentation of that commit; the icon and version block. | +| `src/main.rs` | Arguments, the log file, the crash message, the window. | ## The filters @@ -111,7 +115,37 @@ out 0.03 % over the limit and was re-encoded once, to 97.4 % of it. ## Files written -Only the output and its partial file. FFmpeg writes `.qvt-partial`, checked by +Next to the videos, only the output and its partial file. FFmpeg writes `.qvt-partial`, checked by `naming::check_partial` (same folder, marker extension, not the source) before every run; it is renamed once the size is checked, deleted otherwise. An output name that exists gets ` (2)`, ` (3)`…: nothing is ever overwritten. Source metadata (titles, encoder tags, chapters) is not copied. + +In the data folder (`eframe::storage_dir`): `profiles.toml`, eframe's saved preferences, the logs of the +last two runs (`quick-video-transcoder.log`, `.previous.log`) and `instance.txt`, the loopback port and +random token through which a second launch hands its files to the open window (`instance`). In the user's +*Send to* folder, `Quick Video Transcoder.lnk`, only when the user adds or removes it from the *File* +menu (`sendto`). + +## Startup + +FFmpeg is checked first (`ffmpeg::Install::check`): `ffmpeg` and `ffprobe` must run and be version 7 or +later. When they are not on the inherited `PATH`, the `PATH` is read again from the user's and the +system's settings, so FFmpeg installed after Explorer started is found without signing out. Then every +encoder FFmpeg was built with is tried in parallel with the options the estimate and the encode use +(constant QP, then the bitrate rate control with B-frames, lookahead and multipass) on a small picture: +a bare encode test passes on GPUs that then refuse those options. The parallel encodes are measured for +GPU encoders only; with a CPU encoder, one at a time. + +## Releases + +A release is one file, `quick-video-transcoder.exe`. `build.rs` stamps the commit into it, embeds the +third-party notices that `scripts/build.ps1 release` generates with `cargo about` (passed in +`QVT_NOTICES`), and compiles in the icon and the version block (`rc.exe`); the C runtime is linked +statically (`.cargo/config.toml`). The script then asks the built executable for its commit +(`--version`) and notices (`--licenses`), refuses a commit that differs from the checkout or missing +notices, and writes the executable, `SHA256SUMS.txt` and `notes.md` (the changelog section) to `dist\`. +`release.yml` runs it on a `v*` tag, requires `notes.md`, attests `SHA256SUMS.txt` and publishes. + +When FFmpeg is missing and winget runs, the *FFmpeg is needed* window offers to run +`winget install --id Gyan.FFmpeg --exact --silent` with the package and source agreements accepted (the +window says so), then checks again with the `PATH` re-read. diff --git a/scripts/build.ps1 b/scripts/build.ps1 index 8398d1c..9f604f3 100644 --- a/scripts/build.ps1 +++ b/scripts/build.ps1 @@ -5,7 +5,7 @@ # # .\scripts\build.ps1 # test (the default) # .\scripts\build.ps1 build # test, then the release build -# .\scripts\build.ps1 release # test, release build, zip into dist\ (from a clean tree outside CI) +# .\scripts\build.ps1 release # test, notices, release build, the .exe and its checksum in dist\ (from a clean tree outside CI) # # Never pipe it into Select-Object -First: that stops the pipeline mid-run, and a truncated run can look # like a success. Read the whole output, or the last line. @@ -39,6 +39,20 @@ function Run([string] $command, [string[]] $commandArgs) { if ($LASTEXITCODE -ne 0) { Fail "$command $($commandArgs -join ' ') exited $LASTEXITCODE" } } +function Get-Version { + (Select-String -Path (Join-Path $root 'Cargo.toml') -Pattern '^version\s*=\s*"([^"]+)"').Matches[0].Groups[1].Value +} + +# The changelog section of a version, which is the release's notes: everything under +# "## [] - YYYY-MM-DD" up to the next "## [" heading. $null when there is no dated section. +# The pattern is built from single-quoted pieces: in a double-quoted string PowerShell would run +# "$(.*?)" as a subexpression. +function Get-ChangelogSection([string] $text, [string] $version) { + $pattern = '(?ms)^## \[' + [regex]::Escape($version) + '\] - \d{4}-\d{2}-\d{2}[^\r\n]*\r?\n(.*?)(?=^## \[|\z)' + $match = [regex]::Match($text, $pattern) + if ($match.Success) { $match.Groups[1].Value.Trim() } else { $null } +} + function Invoke-Tests { Step "Formatting" Run 'cargo' @('fmt', '--all', '--check') @@ -56,6 +70,17 @@ function Invoke-Tests { Step "Tests (the end-to-end one needs FFmpeg on the PATH)" Run 'cargo' @('test', '--locked') + # The release takes its notes from the changelog; a broken extraction would only show on a tag. + Step "Release notes come from the changelog" + $sample = "# Changelog`n`n## [Unreleased]`n`n- next`n`n## [1.2.0] - 2026-01-02`n`n### Added`n`n- one`n- two`n`n## [1.1.0] - 2025-12-01`n`n- old`n" + $notes = Get-ChangelogSection $sample '1.2.0' + if ($notes -ne "### Added`n`n- one`n- two") { Fail "the notes of a sample changelog came out as: $notes" } + if ($null -ne (Get-ChangelogSection $sample '1.3.0')) { Fail "an undated version must have no notes" } + if ($null -ne (Get-ChangelogSection $sample 'Unreleased')) { Fail "[Unreleased] must have no notes" } + $version = Get-Version + $section = Get-ChangelogSection (Get-Content (Join-Path $root 'CHANGELOG.md') -Raw) $version + Write-Host " $(if ($section) { "$version has a dated section" } else { "$version has no dated section yet (needed only for its release)" })" + Step "Documentation links resolve" # Sections too: a link to a renamed heading lands at the top of the page, which looks fine and is not. # GitHub's anchors: lower case, punctuation dropped, spaces to hyphens, a repeated heading numbered. @@ -130,9 +155,34 @@ function Invoke-Tests { Write-Host " $(@($tracked).Count) tracked files, no video, no personal path" } -function Invoke-Build { +# A release build embeds the third-party notices: generated here by cargo-about into target\, handed to +# build.rs through QVT_NOTICES. A plain build embeds a placeholder. +function Invoke-Build([switch] $WithNotices) { + if ($WithNotices) { + Step "Third-party notices" + if (-not (Get-Command cargo-about -ErrorAction SilentlyContinue)) { + Fail "cargo-about is needed: cargo install cargo-about --locked --features cli" + } + $notices = Join-Path $root 'target\THIRD-PARTY-NOTICES.html' + New-Item -ItemType Directory -Force (Split-Path -Parent $notices) | Out-Null + Run 'cargo' @('about', 'generate', '--locked', '--fail', '--output-file', $notices, (Join-Path $root 'about.hbs')) + Write-Host " $([math]::Round((Get-Item $notices).Length / 1KB)) KB" + $env:QVT_NOTICES = $notices + } Step "Release build" - Run 'cargo' @('build', '--release', '--locked') + try { Run 'cargo' @('build', '--release', '--locked') } finally { Remove-Item Env:\QVT_NOTICES -ErrorAction SilentlyContinue } +} + +# Starts the built executable with one argument and returns what it printed. A windowed program: +# PowerShell does not wait for it when capturing its output, so it is waited for explicitly, its output +# going to a file in target\. +function Invoke-Executable([string] $exe, [string] $argument) { + $output = Join-Path $root "target\qvt-output-$([guid]::NewGuid().ToString('N')).txt" + $process = Start-Process -FilePath $exe -ArgumentList $argument -RedirectStandardOutput $output -NoNewWindow -Wait -PassThru + $text = Get-Content $output -Raw + Remove-Item $output + if ($process.ExitCode -ne 0) { Fail "quick-video-transcoder $argument exited $($process.ExitCode)" } + $text } # A release ships what a commit holds, so that commit must hold everything. CI checks out a commit. @@ -148,26 +198,52 @@ function Assert-CleanTree { Write-Host " clean" } -function Invoke-Zip { - Step "Zip" - $version = (Select-String -Path (Join-Path $root 'Cargo.toml') -Pattern '^version\s*=\s*"([^"]+)"').Matches[0].Groups[1].Value +# A release is one file: quick-video-transcoder.exe, with the third-party notices and the links to its +# documentation inside (About, --licenses, --version). Its name carries no version, so replacing the file +# updates it and the Send to shortcut keeps working. Next to it in dist\: SHA256SUMS.txt, and notes.md +# (the changelog section) when the version has a dated one. +function Invoke-Package { + $version = Get-Version $dist = Join-Path $root 'dist' - $stage = Join-Path $dist "quick-video-transcoder-$version" - if (Test-Path $stage) { Remove-Item -Recurse -Force $stage } - New-Item -ItemType Directory -Force $stage | Out-Null - Copy-Item (Join-Path $root 'target\release\quick-video-transcoder.exe') $stage - Copy-Item (Join-Path $root 'README.md'), (Join-Path $root 'LICENSE'), (Join-Path $root 'CHANGELOG.md') $stage - Copy-Item (Join-Path $root 'scripts\install-sendto.ps1') $stage - $zip = Join-Path $dist "quick-video-transcoder-$version-windows-x64.zip" - if (Test-Path $zip) { Remove-Item -Force $zip } - Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip - Remove-Item -Recurse -Force $stage - Write-Host " $zip" + $exe = Join-Path $root 'target\release\quick-video-transcoder.exe' + + # Asked of the executable rather than of git: it is what users run. + Step "The executable names its commit and carries its notices" + $stamp = Invoke-Executable $exe '--version' + $commit = [regex]::Match($stamp, '(?m)^commit:\s+(\S+)').Groups[1].Value + $docLink = [regex]::Match($stamp, '(?m)^documentation:\s+(\S+)').Groups[1].Value + $head = (& git -C $root rev-parse HEAD).Trim() + if ($commit -ne $head) { Fail "the executable says commit '$commit', the checkout is $head (rebuild, and commit first)" } + $repository = $docLink -replace '/blob/.*$', '' + $notices = Invoke-Executable $exe '--licenses' + if ($notices -notmatch 'SIL Open Font License' -or $notices.Length -lt 50KB) { + Fail "the executable carries no third-party notices (build it with build.ps1 release)" + } + Write-Host " $commit, notices $([math]::Round($notices.Length / 1KB)) KB" + + Step "Checksum and notes" + if (Test-Path $dist) { Remove-Item -Recurse -Force $dist } + New-Item -ItemType Directory -Force $dist | Out-Null + $published = Join-Path $dist 'quick-video-transcoder.exe' + Copy-Item $exe $published + $hash = (Get-FileHash $published -Algorithm SHA256).Hash.ToLowerInvariant() + "$hash quick-video-transcoder.exe" | Set-Content -NoNewline -Encoding ascii (Join-Path $dist 'SHA256SUMS.txt') + $section = Get-ChangelogSection (Get-Content (Join-Path $root 'CHANGELOG.md') -Raw) $version + if ($section) { + $slug = $repository -replace '^https://github.com/', '' + $footer = "`n`n---`n`nOne file, nothing to install: download ``quick-video-transcoder.exe`` and run it. It needs " + + "FFmpeg, and offers to install it if it is missing. Built from $commit; documentation of this " + + "version: $docLink. Check the download with ``gh attestation verify quick-video-transcoder.exe --repo $slug``." + Set-Content -Path (Join-Path $dist 'notes.md') -Encoding utf8 -NoNewline -Value ($section + $footer) + } + Write-Host " $published" + Write-Host " sha256 $hash" + Write-Host " $(if ($section) { 'notes.md from the changelog' } else { "no notes: CHANGELOG.md has no dated section for $version" })" } if ($Task -eq 'release') { Assert-CleanTree } Invoke-Tests -if ($Task -in 'build', 'release') { Invoke-Build } -if ($Task -eq 'release') { Invoke-Zip } +if ($Task -eq 'build') { Invoke-Build } +if ($Task -eq 'release') { Invoke-Build -WithNotices; Invoke-Package } Write-Host "" Write-Host "$Task OK" -ForegroundColor Green diff --git a/scripts/install-sendto.ps1 b/scripts/install-sendto.ps1 deleted file mode 100644 index 7d9eece..0000000 --- a/scripts/install-sendto.ps1 +++ /dev/null @@ -1,39 +0,0 @@ -# Adds "Quick Video Transcoder" to Explorer's Send to menu: select captures, right-click, Send to, and they -# open in the queue. -# -# .\install-sendto.ps1 # the quick-video-transcoder.exe next to this script -# .\install-sendto.ps1 -Exe 'D:\Tools\quick-video-transcoder.exe' -# .\install-sendto.ps1 -Remove -# -# It writes one shortcut in your own Send to folder and nothing else; no administrator rights. - -param( - [string] $Exe = (Join-Path $PSScriptRoot 'quick-video-transcoder.exe'), - [switch] $Remove -) - -$ErrorActionPreference = 'Stop' -$sendTo = [Environment]::GetFolderPath('SendTo') -$shortcut = Join-Path $sendTo 'Quick Video Transcoder.lnk' - -if ($Remove) { - if (Test-Path $shortcut) { - Remove-Item $shortcut - Write-Host "Removed $shortcut" - } else { - Write-Host "No shortcut to remove." - } - exit 0 -} - -if (-not (Test-Path $Exe -PathType Leaf)) { - throw "$Exe not found: pass -Exe with the path of quick-video-transcoder.exe" -} -$Exe = (Resolve-Path $Exe).Path -$shell = New-Object -ComObject WScript.Shell -$link = $shell.CreateShortcut($shortcut) -$link.TargetPath = $Exe -$link.WorkingDirectory = Split-Path -Parent $Exe -$link.Description = 'Trim and re-encode videos to fit a size limit' -$link.Save() -Write-Host "Created $shortcut -> $Exe" diff --git a/scripts/render-icon.ps1 b/scripts/render-icon.ps1 new file mode 100644 index 0000000..7b08291 --- /dev/null +++ b/scripts/render-icon.ps1 @@ -0,0 +1,85 @@ +# Renders assets\icon\quick-video-transcoder.svg into the files the build uses: the .ico compiled into the +# executable (build.rs) and the 256 px .png the window shows (main.rs). +# +# .\scripts\render-icon.ps1 +# +# Run it after editing the SVG and commit the three files together. Microsoft Edge renders the SVG once at +# 1024 px (so the result matches a browser's rendering exactly); each size is then downsampled from that +# render, never from another size, and the .ico stores every size as a PNG frame. + +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +$dir = Join-Path $root 'assets\icon' +$svg = Join-Path $dir 'quick-video-transcoder.svg' +$ico = Join-Path $dir 'quick-video-transcoder.ico' +$png = Join-Path $dir 'quick-video-transcoder-256.png' +if (-not (Test-Path $svg)) { throw "no SVG at $svg" } + +$edge = @( + (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe'), + (Join-Path $env:ProgramFiles 'Microsoft\Edge\Application\msedge.exe') +) | Where-Object { Test-Path $_ } | Select-Object -First 1 +if (-not $edge) { throw 'Microsoft Edge is needed to render the SVG' } + +# The render happens in a fresh temporary folder, deleted at the end: nothing else is written. +$work = Join-Path ([System.IO.Path]::GetTempPath()) ("qvt-icon-" + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $work | Out-Null +try { + $page = Join-Path $work 'icon.html' + $render = Join-Path $work 'render.png' + $svgUrl = ([System.Uri]$svg).AbsoluteUri + Set-Content -Path $page -Encoding utf8 -Value @" + + + +"@ + $userData = Join-Path $work 'profile' + & $edge --headless --disable-gpu --hide-scrollbars --no-first-run "--user-data-dir=$userData" ` + --default-background-color=00000000 --window-size=1024,1024 "--screenshot=$render" ` + ([System.Uri]$page).AbsoluteUri 2>$null | Out-Null + for ($i = 0; $i -lt 50 -and -not (Test-Path $render); $i++) { Start-Sleep -Milliseconds 200 } + if (-not (Test-Path $render)) { throw 'Edge produced no render' } + + Add-Type -AssemblyName System.Drawing + $source = [System.Drawing.Bitmap]::FromFile($render) + function Resize([int] $size) { + $bitmap = New-Object System.Drawing.Bitmap $size, $size, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb) + $graphics = [System.Drawing.Graphics]::FromImage($bitmap) + $graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic + $graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality + $graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality + $graphics.DrawImage($source, 0, 0, $size, $size) + $graphics.Dispose() + $stream = New-Object System.IO.MemoryStream + $bitmap.Save($stream, [System.Drawing.Imaging.ImageFormat]::Png) + $bitmap.Dispose() + , $stream.ToArray() + } + + # The sizes Windows asks for between 100 % and 300 % scaling. + $sizes = 16, 20, 24, 32, 40, 48, 64, 256 + $frames = foreach ($size in $sizes) { , (Resize $size) } + [System.IO.File]::WriteAllBytes($png, $frames[-1]) + + # ICO: a 6-byte header, a 16-byte entry per frame, then the PNG frames. + $out = New-Object System.IO.MemoryStream + $writer = New-Object System.IO.BinaryWriter $out + $writer.Write([uint16]0); $writer.Write([uint16]1); $writer.Write([uint16]$sizes.Count) + $offset = 6 + 16 * $sizes.Count + for ($i = 0; $i -lt $sizes.Count; $i++) { + $side = if ($sizes[$i] -ge 256) { 0 } else { $sizes[$i] } + $writer.Write([byte]$side); $writer.Write([byte]$side) + $writer.Write([byte]0); $writer.Write([byte]0) + $writer.Write([uint16]1); $writer.Write([uint16]32) + $writer.Write([uint32]$frames[$i].Length); $writer.Write([uint32]$offset) + $offset += $frames[$i].Length + } + foreach ($frame in $frames) { $writer.Write($frame) } + $writer.Flush() + [System.IO.File]::WriteAllBytes($ico, $out.ToArray()) + $source.Dispose() + Write-Host "wrote $ico ($($out.Length) bytes) and $png" +} +finally { + Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue +} diff --git a/src/app/help.rs b/src/app/help.rs new file mode 100644 index 0000000..3fa7b12 --- /dev/null +++ b/src/app/help.rs @@ -0,0 +1,298 @@ +//! The windows that explain rather than edit: *About*, and what to do when FFmpeg is missing. Also the +//! *Send to* menu items and the files later launches hand over. + +use std::sync::Arc; + +use crossbeam_channel::Receiver; +use eframe::egui; + +use super::TranscoderApp; +use crate::build_info; +use crate::ffmpeg::{Install, MIN_MAJOR_VERSION}; + +/// Where FFmpeg builds for Windows are downloaded (the "release full" build). +const FFMPEG_BUILDS: &str = "https://www.gyan.dev/ffmpeg/builds/"; +/// The one command that installs FFmpeg for the current user. +const WINGET_COMMAND: &str = "winget install --id Gyan.FFmpeg -e"; + +impl TranscoderApp { + /// Queues the files later launches sent, and brings the window forward. + pub(super) fn poll_incoming(&mut self, ctx: &egui::Context) { + let files = self.incoming.as_ref().map(|i| i.take()).unwrap_or_default(); + if files.is_empty() { + return; + } + self.info(format!("{} file(s) received from Send to", files.len())); + self.add_files(files); + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + // Windows may refuse the focus to a background window: the taskbar button flashes instead. + ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention( + egui::UserAttentionType::Informational, + )); + } + + /// *File* menu: add the application to Explorer's *Send to* menu, or take it away. + pub(super) fn sendto_menu(&mut self, ui: &mut egui::Ui) { + let label = if self.sendto_installed { + "Update the Send to shortcut" + } else { + "Add to Explorer's Send to menu" + }; + if ui + .button(label) + .on_hover_text( + "Select videos in Explorer, right-click, Send to, Quick Video Transcoder", + ) + .clicked() + { + ui.close(); + match crate::sendto::install() { + Ok(link) => self.info(format!("Send to shortcut written: {}", link.display())), + Err(error) => self.error(format!("{error:#}")), + } + self.sendto_installed = crate::sendto::is_installed(); + } + if ui + .add_enabled( + self.sendto_installed, + egui::Button::new("Remove from Explorer's Send to menu"), + ) + .clicked() + { + ui.close(); + match crate::sendto::remove() { + Ok(()) => self.info("Send to shortcut removed"), + Err(error) => self.error(format!("{error:#}")), + } + self.sendto_installed = crate::sendto::is_installed(); + } + } + + pub(super) fn about_window(&mut self, ctx: &egui::Context) { + let mut show_notices = false; + egui::Window::new("About Quick Video Transcoder") + .open(&mut self.show_about) + .resizable(false) + .collapsible(false) + .show(ctx, |ui| { + ui.heading(format!("Quick Video Transcoder {}", build_info::VERSION)); + ui.label("Trims game captures and re-encodes them to fit a size limit."); + ui.add_space(8.0); + egui::Grid::new("about").num_columns(2).show(ui, |ui| { + ui.label("Commit"); + ui.monospace(format!("{}{}", build_info::COMMIT_SHORT, build_info::DIRTY)); + ui.end_row(); + ui.label("Documentation"); + ui.hyperlink_to("for this version", build_info::documentation()); + ui.end_row(); + ui.label("Changes"); + ui.hyperlink_to("CHANGELOG.md", build_info::doc_url("CHANGELOG.md")); + ui.end_row(); + ui.label("Licence"); + ui.hyperlink_to("MIT", build_info::doc_url("LICENSE")); + ui.end_row(); + ui.label("Built with"); + if ui + .link("third-party libraries and their licences") + .clicked() + { + show_notices = true; + } + ui.end_row(); + }); + }); + if show_notices { + self.open_notices(); + } + } + + /// Writes the notices built into the executable to the data folder and opens them in the browser. + fn open_notices(&mut self) { + let Some(dir) = crate::profile::data_dir() else { + self.error("no data folder to open the third-party notices from"); + return; + }; + let path = dir.join("THIRD-PARTY-NOTICES.html"); + let written = + std::fs::create_dir_all(&dir).and_then(|()| std::fs::write(&path, build_info::NOTICES)); + match written { + Ok(()) => super::open_file(&path), + Err(error) => self.error(format!("cannot write {}: {error}", path.display())), + } + } + + /// Shown when FFmpeg is missing or too old: what to install, a button that installs it with winget + /// when winget is there, and a button to look again. + pub(super) fn ffmpeg_window(&mut self, ctx: &egui::Context) { + let Some(help) = &mut self.ffmpeg_help else { + return; + }; + help.poll(); + let mut open = true; + let mut action = None; + egui::Window::new("FFmpeg is needed") + .open(&mut open) + .resizable(false) + .collapsible(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .default_width(540.0) + .show(ctx, |ui| action = help.ui(ui)); + match action { + Some(Action::CheckAgain) if self.detection.is_none() => { + self.ffmpeg_help = None; + self.detection = Some(super::spawn_detection(Arc::clone(&self.notify))); + } + Some(Action::Install) => help_install(self), + _ if !open => self.ffmpeg_help = None, + _ => {} + } + } +} + +/// Starts winget, and checks again once it is done. +fn help_install(app: &mut TranscoderApp) { + let Some(help) = &mut app.ffmpeg_help else { + return; + }; + let (sender, receiver) = crossbeam_channel::bounded(1); + let notify = Arc::clone(&app.notify); + std::thread::spawn(move || { + let _ = sender.send(crate::ffmpeg::install_with_winget().map_err(|e| format!("{e:#}"))); + notify(); + }); + help.installing = Some(receiver); + help.failure = None; + app.info(format!( + "installing FFmpeg with winget ({})…", + crate::ffmpeg::WINGET_PACKAGE + )); +} + +/// What the user asked for in the FFmpeg window. +enum Action { + CheckAgain, + Install, +} + +/// The state of the *FFmpeg is needed* window. +pub(super) struct FfmpegHelp { + problem: Install, + /// Whether winget runs here: checked once, in the background. + winget: Option, + winget_check: Option>, + /// A running `winget install`. + installing: Option>>, + /// Why the last install failed. + failure: Option, + /// An install finished: look for FFmpeg again. + installed: bool, +} + +impl FfmpegHelp { + pub(super) fn new(problem: Install, notify: Arc) -> Self { + let (sender, receiver) = crossbeam_channel::bounded(1); + std::thread::spawn(move || { + let _ = sender.send(crate::ffmpeg::winget_available()); + notify(); + }); + Self { + problem, + winget: None, + winget_check: Some(receiver), + installing: None, + failure: None, + installed: false, + } + } + + fn poll(&mut self) { + if let Some(available) = self.winget_check.as_ref().and_then(|r| r.try_recv().ok()) { + self.winget = Some(available); + self.winget_check = None; + } + if let Some(result) = self.installing.as_ref().and_then(|r| r.try_recv().ok()) { + self.installing = None; + match result { + Ok(()) => self.installed = true, + Err(error) => self.failure = Some(error), + } + } + } + + fn ui(&mut self, ui: &mut egui::Ui) -> Option { + let mut action = None; + ui.label(match &self.problem { + Install::Missing(program) => format!( + "Quick Video Transcoder reads and encodes videos with FFmpeg, a free program it does \ + not include, and {program} cannot be found on this computer." + ), + Install::TooOld(version) => format!( + "The FFmpeg found is too old ({version}). Version {MIN_MAJOR_VERSION} or later is needed." + ), + Install::Ready(_) => String::new(), + }); + ui.add_space(10.0); + if self.installed { + // Checked right away: the window goes once FFmpeg is found. + return Some(Action::CheckAgain); + } + match (self.winget, &self.installing) { + (_, Some(_)) => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label("Installing FFmpeg with winget: a minute or two…"); + }); + } + (Some(true), None) => { + ui.label(format!( + "It can be installed for you with winget, Windows' package manager: the {} \ + package (gyan.dev's full build, about 100 MB, for your account only).", + crate::ffmpeg::WINGET_PACKAGE + )); + if ui.button("Install FFmpeg for me").clicked() { + action = Some(Action::Install); + } + ui.label( + egui::RichText::new( + "Installing accepts the package's licence (GPL) and the winget source's terms.", + ) + .small() + .weak(), + ); + if let Some(failure) = &self.failure { + ui.colored_label(ui.visuals().error_fg_color, failure); + } + ui.add_space(10.0); + ui.label("Or install it yourself:"); + } + (None, None) => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label("Looking for winget…"); + }); + } + (Some(false), None) => {} + } + ui.horizontal(|ui| { + ui.label("In Terminal:"); + ui.code(WINGET_COMMAND); + if ui.small_button("Copy").clicked() { + ui.ctx().copy_text(WINGET_COMMAND.to_owned()); + } + }); + ui.horizontal(|ui| { + ui.label("Or download the \"release full\" build from"); + ui.hyperlink(FFMPEG_BUILDS); + }); + ui.label("unzip it, and add its bin folder to the Path environment variable."); + ui.add_space(12.0); + if ui + .add_enabled(self.installing.is_none(), egui::Button::new("Check again")) + .clicked() + { + action = Some(Action::CheckAgain); + } + action + } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 24a4fa0..32df62e 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -9,6 +9,7 @@ //! - a setting edited with several videos selected changes that setting on every selected video, and only //! that one. +mod help; mod preview; mod queue_panel; mod settings; @@ -24,9 +25,11 @@ use crossbeam_channel::{Receiver, Sender, unbounded}; use eframe::egui; use serde::{Deserialize, Serialize}; +use crate::ffmpeg::Install; use crate::ffmpeg::decoder::DecodeConfig; use crate::ffmpeg::encoders::EncoderBackend; use crate::ffmpeg::hardware::{self, Capabilities}; +use crate::instance::Incoming; use crate::plan; use crate::player::{AudioSource, Player}; use crate::profile::{self, ProfileSet}; @@ -126,7 +129,14 @@ pub struct TranscoderApp { thumbnail_sender: Sender, thumbnail_receiver: Receiver, - detection: Option>, + detection: Option>, + /// FFmpeg is missing or too old: the help window, until closed. + ffmpeg_help: Option, + /// Files from later launches ([`crate::instance`]). + incoming: Option, + /// The *Send to* shortcut exists (checked at start and after each change). + sendto_installed: bool, + show_about: bool, /// The GPU drawing the window and its driver: with the encoder, the key of a parallelism measurement. gpu: String, /// A running measurement of encodes at once, and its key. @@ -145,7 +155,11 @@ pub struct TranscoderApp { impl TranscoderApp { /// Creates the application and queues `files`. - pub fn new(cc: &eframe::CreationContext<'_>, files: Vec) -> Self { + pub fn new( + cc: &eframe::CreationContext<'_>, + files: Vec, + incoming: Option, + ) -> Self { let prefs: Preferences = cc .storage .and_then(|s| eframe::get_value(s, PREFERENCES_KEY)) @@ -157,12 +171,7 @@ impl TranscoderApp { let ctx = cc.egui_ctx.clone(); let notify: Arc = Arc::new(move || ctx.request_repaint()); let capabilities = prefs.capabilities.clone().unwrap_or_default(); - let (sender, detection) = crossbeam_channel::bounded(1); - let repaint = Arc::clone(¬ify); - std::thread::spawn(move || { - let _ = sender.send(Capabilities::detect()); - repaint(); - }); + let detection = spawn_detection(Arc::clone(¬ify)); let profiles_path = profile::data_dir().map(|dir| dir.join(ProfileSet::FILE_NAME)); let mut log = VecDeque::new(); let profiles = match profiles_path.as_deref().map(ProfileSet::load) { @@ -177,6 +186,10 @@ impl TranscoderApp { None => ProfileSet::default(), }; let (thumbnail_sender, thumbnail_receiver) = unbounded(); + if let Some(incoming) = &incoming { + let wake = Arc::clone(¬ify); + incoming.set_waker(move || wake()); + } let mut app = Self { queue: Queue::new(capabilities, prefs.queue_settings(), Arc::clone(¬ify)), profiles, @@ -193,6 +206,10 @@ impl TranscoderApp { thumbnail_sender, thumbnail_receiver, detection: Some(detection), + ffmpeg_help: None, + incoming, + sendto_installed: crate::sendto::is_installed(), + show_about: false, gpu: cc .wgpu_render_state .as_ref() @@ -356,13 +373,26 @@ impl TranscoderApp { } fn poll_detection(&mut self) { - let Some(capabilities) = self.detection.as_ref().and_then(|r| r.try_recv().ok()) else { + let Some((install, capabilities)) = self.detection.as_ref().and_then(|r| r.try_recv().ok()) + else { return; }; self.detection = None; + match &install { + Install::Ready(version) => self.info(version.clone()), + Install::Missing(program) => self.error(format!("{program} is not on the PATH")), + Install::TooOld(version) => self.error(format!( + "{version}: FFmpeg {} or later is needed", + crate::ffmpeg::MIN_MAJOR_VERSION + )), + } + if !matches!(install, Install::Ready(_)) { + self.ffmpeg_help = Some(help::FfmpegHelp::new(install, Arc::clone(&self.notify))); + return; + } self.info(format!("hardware: {}", capabilities.summary())); if capabilities.encoders.is_empty() { - self.error("no working video encoder: is FFmpeg on the PATH?"); + self.error("FFmpeg runs, but none of its video encoders works on this computer"); } self.prefs.capabilities = Some(capabilities.clone()); if capabilities != self.queue.capabilities { @@ -378,6 +408,15 @@ impl TranscoderApp { let Some(spec) = self.queue.capabilities.choose(&codecs, self.prefs.backend) else { return; }; + if spec.backend == EncoderBackend::Software { + // A CPU encoder already uses every core: two at once only share them. Not measured, since + // a CPU encode of the synthetic picture can take minutes. + if !self.prefs.parallel_manual && self.prefs.parallel_encodes != 1 { + self.prefs.parallel_encodes = 1; + self.queue.set_settings(self.prefs.queue_settings()); + } + return; + } let key = format!("{} / {}", self.gpu, spec.name); let known = self .prefs @@ -732,6 +771,8 @@ impl TranscoderApp { self.remove_selected(); } ui.separator(); + self.sendto_menu(ui); + ui.separator(); if ui.button("Quit").clicked() { ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); } @@ -759,6 +800,16 @@ impl TranscoderApp { ui.close(); self.show_shortcuts = true; } + if ui.button("Documentation").clicked() { + ui.close(); + ui.ctx() + .open_url(egui::OpenUrl::new_tab(crate::build_info::documentation())); + } + ui.separator(); + if ui.button("About Quick Video Transcoder").clicked() { + ui.close(); + self.show_about = true; + } }); }); } @@ -951,6 +1002,25 @@ impl TranscoderApp { } } +/// Checks FFmpeg and tries its encoders on a background thread (about a second). +fn spawn_detection(notify: Arc) -> Receiver<(Install, Capabilities)> { + let (sender, detection) = crossbeam_channel::bounded(1); + std::thread::spawn(move || { + let install = Install::check(); + let capabilities = match install { + Install::Ready(_) => Capabilities::detect(), + _ => Capabilities { + encoders: Vec::new(), + placebo: false, + detected: true, + }, + }; + let _ = sender.send((install, capabilities)); + notify(); + }); + detection +} + /// A path written with Windows' own separators: Windows accepts `/`, but a path given with them (from a /// shell) would reach the clipboard and the output names mixed with `\`. fn native_separators(path: PathBuf) -> PathBuf { @@ -960,6 +1030,18 @@ fn native_separators(path: PathBuf) -> PathBuf { } } +/// Opens a file with its default program (the browser for a page). +fn open_file(path: &Path) { + let opener = if cfg!(windows) { + "explorer.exe" + } else if cfg!(target_os = "macos") { + "open" + } else { + "xdg-open" + }; + let _ = std::process::Command::new(opener).arg(path).spawn(); +} + /// Shows a folder in Explorer, with `file` selected when given. fn reveal(dir: &Path, file: Option<&Path>) { #[cfg(windows)] @@ -1008,6 +1090,7 @@ impl eframe::App for TranscoderApp { self.poll_parallel_measurement(); self.handle_dropped_files(&ctx); self.handle_shortcuts(&ctx); + self.poll_incoming(&ctx); self.poll_queue(); self.poll_thumbnails(&ctx); self.update_player(&ctx); @@ -1039,6 +1122,8 @@ impl eframe::App for TranscoderApp { self.shortcuts_window(&ctx); self.profiles_window(&ctx); + self.about_window(&ctx); + self.ffmpeg_window(&ctx); self.take_screenshot(&ctx); } diff --git a/src/build_info.rs b/src/build_info.rs new file mode 100644 index 0000000..21a5511 --- /dev/null +++ b/src/build_info.rs @@ -0,0 +1,67 @@ +//! What this executable is: its version and the commit it was built from (stamped by `build.rs`), and +//! links to the documentation *of that commit*. +//! +//! The documentation is linked at the commit rather than at `main`, so a link always describes the build +//! that is running, however old. That is also why every change updates its documentation in the same +//! commit: a link to a commit whose pages are stale stays stale forever. + +/// The version from `Cargo.toml`. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// The full commit hash, or `unknown` outside a git checkout. +pub const COMMIT: &str = env!("QVT_COMMIT"); + +/// The commit's first eight characters. +pub const COMMIT_SHORT: &str = env!("QVT_COMMIT_SHORT"); + +/// `-dirty` when built from a tree with uncommitted changes, else empty. +pub const DIRTY: &str = env!("QVT_DIRTY"); + +/// The third-party notices (an HTML page): the libraries built in and their licences. +pub const NOTICES: &str = include_str!(concat!(env!("OUT_DIR"), "/third-party-notices.html")); + +/// `true` when [`NOTICES`] are the generated ones, not the placeholder of a development build. +pub const NOTICES_COMPLETE: bool = matches!(env!("QVT_NOTICES_COMPLETE").as_bytes(), b"true"); + +/// The repository on GitHub. +pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); + +/// A file of the repository as it is at this build's commit (`main` for an unknown build). +pub fn doc_url(path: &str) -> String { + format!("{REPOSITORY}/blob/{}/{path}", env!("QVT_DOC_REF")) +} + +/// The documentation's entry point at this build's commit. +pub fn documentation() -> String { + doc_url("README.md") +} + +/// The answer to `--version`, also what the release script checks the commit with: name and version, then +/// `commit:` and `documentation:` lines. +pub fn version_text() -> String { + format!( + "Quick Video Transcoder {VERSION}\ncommit: {COMMIT}{DIRTY}\ndocumentation: {}", + documentation() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn links_the_documentation_of_the_build() { + let text = version_text(); + assert!(text.starts_with(&format!("Quick Video Transcoder {VERSION}\n"))); + let link = text + .lines() + .find_map(|l| l.strip_prefix("documentation: ")) + .unwrap(); + assert!(link.starts_with(REPOSITORY), "{link}"); + assert!(link.ends_with("/README.md"), "{link}"); + if COMMIT != "unknown" { + assert!(link.contains(COMMIT), "{link}"); + assert_eq!(COMMIT_SHORT, &COMMIT[..8]); + } + } +} diff --git a/src/ffmpeg/encoders.rs b/src/ffmpeg/encoders.rs index 2d622a4..2c17f9f 100644 --- a/src/ffmpeg/encoders.rs +++ b/src/ffmpeg/encoders.rs @@ -231,14 +231,17 @@ impl EncoderSpec { } EncoderBackend::Qsv | EncoderBackend::Software => {} } - args.extend([ - "-b:v".into(), - rate(1.0), - "-maxrate:v".into(), - rate(2.0), - "-bufsize:v".into(), - rate(4.0), - ]); + args.extend(["-b:v".into(), rate(1.0)]); + // SVT-AV1 refuses a peak rate outside its CRF mode ("Max Bitrate only supported with CRF mode"): + // its VBR keeps the average alone. + if !(self.backend == EncoderBackend::Software && self.codec == VideoCodec::Av1) { + args.extend([ + "-maxrate:v".into(), + rate(2.0), + "-bufsize:v".into(), + rate(4.0), + ]); + } args } } @@ -282,4 +285,19 @@ mod tests { "{qp}" ); } + + #[test] + fn svt_av1_gets_no_peak_rate() { + let svt = find(VideoCodec::Av1, EncoderBackend::Software) + .bitrate_args(1e6, 60, Depth::Sdr8) + .join(" "); + assert!(svt.ends_with("-b:v 1000000"), "{svt}"); + let x265 = find(VideoCodec::H265, EncoderBackend::Software) + .bitrate_args(1e6, 60, Depth::Sdr8) + .join(" "); + assert!( + x265.ends_with("-maxrate:v 2000000 -bufsize:v 4000000"), + "{x265}" + ); + } } diff --git a/src/ffmpeg/hardware.rs b/src/ffmpeg/hardware.rs index 2e4e56f..96c826d 100644 --- a/src/ffmpeg/hardware.rs +++ b/src/ffmpeg/hardware.rs @@ -55,7 +55,7 @@ impl Capabilities { std::thread::scope(|scope| { let tests: Vec<_> = candidates .iter() - .map(|spec| scope.spawn(move || (spec, test_encoder(spec.name)))) + .map(|spec| scope.spawn(move || (spec, test_encoder(spec)))) .collect(); let placebo = scope.spawn(test_placebo); Self { @@ -208,21 +208,21 @@ pub fn run_test(args: &[&str], timeout: Duration) -> bool { } } -fn test_encoder(name: &str) -> bool { - run_test( - &[ - "-f", - "lavfi", - "-i", - "color=c=gray:s=256x256:r=30:d=0.1", - "-c:v", - name, - "-f", - "null", - "-", - ], - Duration::from_secs(10), - ) +/// Tries an encoder with the options the estimate and the encode really use (constant QP, then the +/// bitrate rate control with its lookahead, B-frames and multipass), on a tiny picture. A bare `-c:v` +/// test passes on GPUs that then refuse those options (older NVENC generations have no B-frames for +/// H.265), and every estimate would fail. +fn test_encoder(spec: &EncoderSpec) -> bool { + use super::encoders::Depth; + let mut args: Vec = ["-f", "lavfi", "-i", "testsrc2=s=320x240:r=30:d=0.5"] + .map(String::from) + .to_vec(); + args.extend(spec.constant_qp_args(26.0, 30, Depth::Sdr8)); + args.extend(["-f", "null", "-"].map(String::from)); + args.extend(spec.bitrate_args(1_000_000.0, 30, Depth::Sdr8)); + args.extend(["-f", "null", "-"].map(String::from)); + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + run_test(&args, Duration::from_secs(15)) } /// Most encodes the measurement tries at once. diff --git a/src/ffmpeg/mod.rs b/src/ffmpeg/mod.rs index 0e1f334..4f03491 100644 --- a/src/ffmpeg/mod.rs +++ b/src/ffmpeg/mod.rs @@ -7,6 +7,10 @@ //! process has exited, never with a sleep; //! - stop a process with [`kill_tree`]: `ffmpeg` on the `PATH` may be a Chocolatey or Scoop shim that runs //! the real one as its child. +//! +//! FFmpeg installed while the application (or Explorer, which starts it) was running is not on the `PATH` +//! the process inherited: [`Install::check`] then reads the current `PATH` from the user's and the +//! system's settings, and every tool started afterwards gets it. pub mod audio; pub mod decoder; @@ -16,18 +20,29 @@ pub mod hardware; pub mod probe; use std::collections::VecDeque; +use std::ffi::OsString; use std::io::{BufRead, BufReader}; use std::process::{Child, Command}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError, RwLock}; use std::thread::JoinHandle; #[cfg(windows)] const CREATE_NO_WINDOW: u32 = 0x0800_0000; +/// The `PATH` read from the settings by [`refresh_path`], when the inherited one lacks FFmpeg. +static FRESH_PATH: RwLock> = RwLock::new(None); + /// A [`Command`] for an FFmpeg tool that does not open a console window on Windows. pub fn tool(program: &str) -> Command { - #[allow(unused_mut)] let mut command = Command::new(program); + // Set on the command, the PATH is also where Rust looks the program up. + if let Some(path) = FRESH_PATH + .read() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + command.env("PATH", path); + } #[cfg(windows)] { use std::os::windows::process::CommandExt; @@ -118,3 +133,172 @@ impl StderrTail { Vec::from(lines.clone()).join("\n") } } + +/// The oldest FFmpeg release the filters and encoder options are written for. +pub const MIN_MAJOR_VERSION: u32 = 7; + +/// Whether the FFmpeg tools the application needs are on the `PATH`, and recent enough. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Install { + /// `ffmpeg` and `ffprobe` run; the version line `ffmpeg -version` prints. + Ready(String), + /// This tool does not start: not installed, or not on the `PATH` this process inherited. + Missing(&'static str), + /// Older than [`MIN_MAJOR_VERSION`]; the version line. + TooOld(String), +} + +impl Install { + /// Runs `ffmpeg -version` and `ffprobe -version`, with the current `PATH` from the settings if the + /// inherited one has no FFmpeg. + pub fn check() -> Self { + // Debug builds: `QVT_PRETEND_NO_FFMPEG=1` shows what a machine without FFmpeg gets. + #[cfg(debug_assertions)] + if std::env::var_os("QVT_PRETEND_NO_FFMPEG").is_some() { + return Self::Missing("ffmpeg"); + } + let install = Self::check_once(); + if matches!(install, Self::Missing(_)) && refresh_path() { + return Self::check_once(); + } + install + } + + fn check_once() -> Self { + let version = |program: &'static str| { + let output = tool(program) + .arg("-version") + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .filter(|o| o.status.success())?; + Some( + String::from_utf8_lossy(&output.stdout) + .lines() + .next() + .unwrap_or_default() + .to_owned(), + ) + }; + let Some(line) = version("ffmpeg") else { + return Self::Missing("ffmpeg"); + }; + if version("ffprobe").is_none() { + return Self::Missing("ffprobe"); + } + match major_version(&line) { + Some(major) if major < MIN_MAJOR_VERSION => Self::TooOld(line), + _ => Self::Ready(line), + } + } +} + +/// Reads the `PATH` as the user's and the system's settings now define it (what a new sign-in would +/// get) and gives it to the tools started from now on. `false` when it cannot be read. +pub fn refresh_path() -> bool { + if !cfg!(windows) { + return false; + } + let script = concat!( + "[Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + ", + "[Environment]::GetEnvironmentVariable('Path', 'User')" + ); + let Ok(output) = tool("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", script]) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + else { + return false; + }; + let path = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + if !output.status.success() || path.trim_matches(';').is_empty() { + return false; + } + log::info!("FFmpeg not on the inherited PATH: using the PATH from the settings"); + *FRESH_PATH.write().unwrap_or_else(PoisonError::into_inner) = Some(path.into()); + true +} + +/// The winget package of the FFmpeg build the application is tested with (gyan.dev's static full build: +/// libplacebo, Vulkan, NVENC, Quick Sync, AMF). +pub const WINGET_PACKAGE: &str = "Gyan.FFmpeg"; + +/// `true` when Windows' package manager, winget, runs here. +pub fn winget_available() -> bool { + cfg!(windows) + && tool("winget") + .arg("--version") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) +} + +/// Installs FFmpeg with winget, for the current user, accepting the package's agreements (the user asked +/// for it from the *FFmpeg is needed* window, which says so). Takes a minute or two; the error carries +/// winget's last lines. +pub fn install_with_winget() -> anyhow::Result<()> { + use anyhow::Context; + let output = tool("winget") + .args(["install", "--id", WINGET_PACKAGE, "--exact", "--silent"]) + .args(["--accept-package-agreements", "--accept-source-agreements"]) + .arg("--disable-interactivity") + .stdin(std::process::Stdio::null()) + .output() + .context("cannot start winget")?; + if output.status.success() { + return Ok(()); + } + // winget redraws its progress with carriage returns: keep the last real lines. + let text = String::from_utf8_lossy(&output.stdout); + let lines: Vec<&str> = text + .split(['\r', '\n']) + .map(str::trim) + .filter(|l| l.chars().any(char::is_alphanumeric)) + .collect(); + let tail = lines[lines.len().saturating_sub(3)..].join(" / "); + anyhow::bail!("winget failed ({}): {tail}", output.status) +} + +/// The major version in `ffmpeg -version`'s first line (`ffmpeg version 9.0.2-full_build-www.gyan.dev +/// Copyright…`, `ffmpeg version n7.1`). `None` for a build from git (`N-118000-g…`, `2026-11-01-git-…`), +/// which is newer than any release. +pub fn major_version(line: &str) -> Option { + let word = line + .split_whitespace() + .skip_while(|w| *w != "version") + .nth(1)?; + let word = word.strip_prefix('n').unwrap_or(word); + let (major, rest) = word.split_once('.')?; + let major: u32 = major.parse().ok()?; + // A date-named git build has no dot after its year, and its "major" would be the year. + (rest.chars().next().is_some_and(|c| c.is_ascii_digit()) && major < 1000).then_some(major) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_the_major_version() { + let gyan = "ffmpeg version 9.0.2-full_build-www.gyan.dev Copyright (c) 2000-2026 the FFmpeg developers"; + assert_eq!(major_version(gyan), Some(9)); + assert_eq!(major_version("ffmpeg version n7.1 Copyright"), Some(7)); + assert_eq!( + major_version("ffmpeg version 6.1.1-3ubuntu5 Copyright"), + Some(6) + ); + assert_eq!( + major_version("ffmpeg version N-118000-g1234abcd Copyright"), + None + ); + assert_eq!( + major_version("ffmpeg version 2026-11-01-git-abcdef-full_build"), + None + ); + assert_eq!(major_version(""), None); + } +} diff --git a/src/instance.rs b/src/instance.rs new file mode 100644 index 0000000..5472c2d --- /dev/null +++ b/src/instance.rs @@ -0,0 +1,207 @@ +//! One window at a time: a second launch (another *Send to*, a double-click) hands its files to the +//! window already open and exits, so two queues never compete for the same hardware encoder. +//! +//! The first instance listens on a loopback TCP port chosen by the system and writes the port with a +//! random token to `instance.txt` in the data folder. A later launch reads it, connects, sends the token +//! and its files one per line, and exits once the first instance acknowledges. Anything unexpected (no +//! file, a stale port, a wrong token, a path that is not UTF-8) makes the launch open its own window: a +//! second window is the worst outcome, never lost files. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crossbeam_channel::{Receiver, Sender, unbounded}; + +/// The file naming the port and token of the running instance. +pub const FILE_NAME: &str = "instance.txt"; + +/// A callback waking the window when files arrive. +type Waker = Arc>>>; + +/// How a launch goes on. +pub enum Launch { + /// This is the first instance: open the window and receive later launches' files. + Primary(Incoming), + /// The files went to the running instance: exit. + Forwarded, +} + +/// Files sent by later launches. +pub struct Incoming { + receiver: Receiver>, + waker: Waker, + /// Why later launches cannot reach this one, to log once the log is open. + problem: Option, +} + +impl Incoming { + /// Why later launches will open windows of their own, if they will. + pub fn problem(&self) -> Option<&str> { + self.problem.as_deref() + } + + /// Calls `wake` whenever files arrive (to repaint the window, which then calls [`Incoming::take`]). + pub fn set_waker(&self, wake: impl Fn() + Send + 'static) { + if let Ok(mut waker) = self.waker.lock() { + *waker = Some(Box::new(wake)); + } + } + + /// Files received since the last call, in arrival order. + pub fn take(&self) -> Vec { + self.receiver.try_iter().flatten().collect() + } +} + +/// Hands `files` to the running instance whose details are in `dir`, or becomes that instance. +pub fn claim(dir: &Path, files: &[PathBuf]) -> Launch { + if forward(dir, files).is_some() { + return Launch::Forwarded; + } + match listen(dir) { + Ok(incoming) => Launch::Primary(incoming), + Err(error) => Launch::Primary(Incoming { + receiver: unbounded().1, + waker: Arc::default(), + problem: Some(format!("{error:#}")), + }), + } +} + +/// Sends the files to a running instance; `Some` once it acknowledged them. +fn forward(dir: &Path, files: &[PathBuf]) -> Option<()> { + let text = std::fs::read_to_string(dir.join(FILE_NAME)).ok()?; + let (port, token) = text.trim().split_once(' ')?; + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port.parse::().ok()?)); + let mut stream = TcpStream::connect_timeout(&address, Duration::from_millis(500)).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(3))).ok()?; + stream + .set_write_timeout(Some(Duration::from_secs(3))) + .ok()?; + let mut message = format!("{token}\n"); + for file in files { + // A line per path: a path holding a line break or invalid UTF-8 opens its own window instead. + let path = file.to_str().filter(|p| !p.contains(['\n', '\r']))?; + message.push_str(path); + message.push('\n'); + } + message.push('\n'); + stream.write_all(message.as_bytes()).ok()?; + let mut reply = String::new(); + BufReader::new(stream).read_line(&mut reply).ok()?; + (reply.trim() == "ok").then_some(()) +} + +/// Listens for later launches and publishes the port and a fresh token in `dir`. +fn listen(dir: &Path) -> anyhow::Result { + use anyhow::Context; + let listener = + TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).context("cannot listen on loopback")?; + let port = listener.local_addr()?.port(); + let token = token(); + std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?; + // Written whole then renamed, so a launch never reads half a file. + let path = dir.join(FILE_NAME); + let temporary = dir.join(format!("{FILE_NAME}.tmp")); + std::fs::write(&temporary, format!("{port} {token}\n")) + .with_context(|| format!("cannot write {}", temporary.display()))?; + std::fs::rename(&temporary, &path) + .with_context(|| format!("cannot write {}", path.display()))?; + let (sender, receiver) = unbounded(); + let waker: Waker = Arc::default(); + let wake = Arc::clone(&waker); + std::thread::Builder::new() + .name("single instance".to_owned()) + .spawn(move || { + for stream in listener.incoming().flatten() { + serve(stream, &token, &sender, &wake); + } + })?; + Ok(Incoming { + receiver, + waker, + problem: None, + }) +} + +/// Reads one launch's files; anything malformed is dropped without an answer. +fn serve(stream: TcpStream, token: &str, sender: &Sender>, waker: &Waker) { + let _ = stream.set_read_timeout(Some(Duration::from_secs(3))); + let Ok(mut reply) = stream.try_clone() else { + return; + }; + // A launch sends a few paths: a megabyte is far more than any real message. + let mut lines = BufReader::new(stream.take(1 << 20)).lines(); + if lines.next().and_then(Result::ok).as_deref() != Some(token) { + return; + } + let mut files = Vec::new(); + for line in lines { + match line { + Ok(line) if line.is_empty() => break, + Ok(line) => files.push(PathBuf::from(line)), + Err(_) => return, + } + } + if sender.send(files).is_ok() { + let _ = reply.write_all(b"ok\n"); + if let Ok(waker) = waker.lock() + && let Some(wake) = waker.as_ref() + { + wake(); + } + } +} + +/// A token no other program can guess: two hashes seeded by the system's per-process random keys. +fn token() -> String { + use std::hash::{BuildHasher, RandomState}; + let seed = (std::process::id(), std::time::SystemTime::now()); + let first = RandomState::new().hash_one(seed); + let second = RandomState::new().hash_one((seed, first)); + format!("{first:016x}{second:016x}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_second_launch_hands_its_files_to_the_first() { + let dir = tempfile::tempdir().unwrap(); + let Launch::Primary(incoming) = claim(dir.path(), &[]) else { + panic!("the first launch must open the window"); + }; + let woken = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = Arc::clone(&woken); + incoming.set_waker(move || { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }); + let files = vec![ + PathBuf::from(r"C:\Vidéos\clip 1.mp4"), + PathBuf::from("b.mkv"), + ]; + assert!(matches!(claim(dir.path(), &files), Launch::Forwarded)); + assert_eq!(incoming.take(), files); + assert_eq!(woken.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[test] + fn a_wrong_token_or_a_stale_file_opens_a_window() { + let dir = tempfile::tempdir().unwrap(); + let Launch::Primary(incoming) = claim(dir.path(), &[]) else { + panic!("the first launch must open the window"); + }; + let path = dir.path().join(FILE_NAME); + let text = std::fs::read_to_string(&path).unwrap(); + let port = text.split_once(' ').unwrap().0.to_owned(); + std::fs::write(&path, format!("{port} wrong\n")).unwrap(); + assert!(forward(dir.path(), &[PathBuf::from("a.mp4")]).is_none()); + assert!(incoming.take().is_empty()); + std::fs::write(&path, "1 stale\n").unwrap(); + assert!(forward(dir.path(), &[PathBuf::from("a.mp4")]).is_none()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 9efe898..a459924 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,14 +8,17 @@ pub mod app; pub mod audio; +pub mod build_info; pub mod clipboard; pub mod encode; pub mod estimate; pub mod ffmpeg; +pub mod instance; pub mod naming; pub mod plan; pub mod player; pub mod profile; pub mod queue; +pub mod sendto; pub mod thumbnails; pub mod timecode; diff --git a/src/main.rs b/src/main.rs index b924f63..fc5deb7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,29 +1,149 @@ //! The `quick-video-transcoder` executable: every argument is a video to queue (Explorer's *Send to* -//! passes the selected files this way). +//! passes the selected files this way), except `--version` and `--licenses` (the third-party notices), +//! which print and exit. +//! +//! A release build has no console, so what would go to one goes to `quick-video-transcoder.log` in the +//! data folder (the previous run's log is kept beside it), and a crash or a window that cannot open is +//! told in a message box naming that log. A second launch hands its files to the open window +//! ([`instance`]). #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] -use std::path::PathBuf; +use std::fs::File; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; use eframe::egui; use quick_video_transcoder::app::{APP_ID, TranscoderApp}; +use quick_video_transcoder::{build_info, instance, profile}; -fn main() -> eframe::Result { - env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); - let files: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +/// The log of this run, in the data folder. +const LOG_FILE: &str = "quick-video-transcoder.log"; +/// The log of the run before. +const PREVIOUS_LOG_FILE: &str = "quick-video-transcoder.previous.log"; + +fn main() { + let arguments: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + // A release build has no console of its own, but a redirected output (a file, a pipe) works. A reader + // that already left (PowerShell does not wait for a windowed program) is no error. + let print = |text: &str| { + let _ = writeln!(std::io::stdout(), "{text}"); + }; + match arguments.first().and_then(|a| a.to_str()) { + Some("--version" | "-V") => return print(&build_info::version_text()), + Some("--licenses") => return print(build_info::NOTICES), + _ => {} + } + let data = profile::data_dir(); + // Before the log: a launch that only hands its files over must not rotate the open window's log. + let incoming = match data.as_deref().map(|dir| instance::claim(dir, &arguments)) { + Some(instance::Launch::Forwarded) => return, + Some(instance::Launch::Primary(incoming)) => Some(incoming), + None => None, + }; + let log_path = data.as_deref().and_then(start_log); + install_panic_hook(log_path.clone()); + log::info!("{}", build_info::version_text().replace('\n', ", ")); + if let Some(problem) = incoming.as_ref().and_then(|i| i.problem()) { + log::warn!("videos sent later will open another window: {problem}"); + } + + let icon = eframe::icon_data::from_png_bytes(include_bytes!( + "../assets/icon/quick-video-transcoder-256.png" + )) + .expect("the icon is a valid PNG"); let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_title("Quick Video Transcoder") .with_app_id(APP_ID) + .with_icon(icon) .with_inner_size([1500.0, 900.0]) .with_min_inner_size([1000.0, 620.0]) .with_drag_and_drop(true), renderer: eframe::Renderer::Wgpu, ..Default::default() }; - eframe::run_native( + let result = eframe::run_native( APP_ID, options, - Box::new(move |cc| Ok(Box::new(TranscoderApp::new(cc, files)))), - ) + Box::new(move |cc| Ok(Box::new(TranscoderApp::new(cc, arguments, incoming)))), + ); + if let Err(error) = result { + log::error!("the window could not open: {error}"); + show_error( + "Quick Video Transcoder cannot open its window", + &format!( + "{error}\n\nThe window needs a graphics driver with DirectX 12 or Vulkan. Updating the \ + graphics driver usually fixes this.{}", + log_hint(log_path.as_deref()) + ), + ); + std::process::exit(1); + } +} + +/// Logs to the data folder (and the console in debug builds); returns the log's path. +fn start_log(dir: &Path) -> Option { + std::fs::create_dir_all(dir).ok()?; + let path = dir.join(LOG_FILE); + let _ = std::fs::rename(&path, dir.join(PREVIOUS_LOG_FILE)); + let file = File::create(&path).ok()?; + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) + .target(env_logger::Target::Pipe(Box::new(Tee(Mutex::new(file))))) + .init(); + Some(path) +} + +/// Writes to the log file, and to standard error where there is one (debug builds). +struct Tee(Mutex); + +impl Write for Tee { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if cfg!(debug_assertions) { + let _ = std::io::stderr().write_all(bytes); + } + let mut file = self.0.lock().unwrap_or_else(|e| e.into_inner()); + file.write_all(bytes)?; + file.flush()?; + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.lock().unwrap_or_else(|e| e.into_inner()).flush() + } +} + +/// A panic is logged with its backtrace, and one on the window's thread is told in a message box: the +/// window then closes, and without the box it would vanish without a word. +fn install_panic_hook(log_path: Option) { + let default = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let backtrace = std::backtrace::Backtrace::force_capture(); + log::error!("{info}\n{backtrace}"); + default(info); + if std::thread::current().name() == Some("main") { + show_error( + "Quick Video Transcoder has stopped", + &format!( + "Something went wrong: {info}\n\nEncodes that were running did not finish.{}", + log_hint(log_path.as_deref()) + ), + ); + } + })); +} + +fn log_hint(path: Option<&Path>) -> String { + path.map(|p| format!("\n\nDetails are in {}", p.display())) + .unwrap_or_default() +} + +fn show_error(title: &str, text: &str) { + rfd::MessageDialog::new() + .set_title(title) + .set_description(text) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); } diff --git a/src/sendto.rs b/src/sendto.rs new file mode 100644 index 0000000..e0b9cb0 --- /dev/null +++ b/src/sendto.rs @@ -0,0 +1,75 @@ +//! Explorer's *Send to* menu: one shortcut, `Quick Video Transcoder.lnk`, in the user's own *Send to* +//! folder, pointing at this executable. Select captures, right-click, *Send to*, and they open in the +//! queue. +//! +//! Done from the application, so nobody needs to run a script: Windows blocks downloaded PowerShell +//! scripts by default. The shortcut is written by Windows' own `WScript.Shell` object through an inline +//! PowerShell command (a command is not subject to the script policy); the paths travel in environment +//! variables, never inside the command text, so no quoting can break. Only this one file is ever written +//! or deleted, and only when the user asks. + +use std::path::PathBuf; +use std::process::Stdio; + +use anyhow::{Context, Result, bail}; + +/// The shortcut's file name. +pub const SHORTCUT_NAME: &str = "Quick Video Transcoder.lnk"; + +/// Where the shortcut goes: `%APPDATA%\Microsoft\Windows\SendTo`. `None` off Windows or without +/// `APPDATA`. +pub fn shortcut_path() -> Option { + if !cfg!(windows) { + return None; + } + let roaming = std::env::var_os("APPDATA")?; + Some( + PathBuf::from(roaming) + .join("Microsoft") + .join("Windows") + .join("SendTo") + .join(SHORTCUT_NAME), + ) +} + +/// `true` when the shortcut exists (wherever it points). +pub fn is_installed() -> bool { + shortcut_path().is_some_and(|p| p.is_file()) +} + +/// Writes the shortcut to the running executable, replacing an older one (after a move of the folder). +pub fn install() -> Result { + let link = shortcut_path().context("no Send to folder on this system")?; + let exe = std::env::current_exe().context("cannot find this executable")?; + let folder = exe.parent().context("the executable has no folder")?; + let script = "$link = (New-Object -ComObject WScript.Shell).CreateShortcut($env:QVT_LINK); \ + $link.TargetPath = $env:QVT_TARGET; \ + $link.WorkingDirectory = $env:QVT_FOLDER; \ + $link.Description = 'Trim and re-encode videos to fit a size limit'; \ + $link.Save()"; + let output = crate::ffmpeg::tool("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", script]) + .env("QVT_LINK", &link) + .env("QVT_TARGET", &exe) + .env("QVT_FOLDER", folder) + .stdin(Stdio::null()) + .output() + .context("cannot start PowerShell")?; + if !output.status.success() || !link.is_file() { + bail!( + "cannot create {}: {}", + link.display(), + String::from_utf8_lossy(&output.stderr).trim() + ); + } + Ok(link) +} + +/// Deletes the shortcut, if it is there. +pub fn remove() -> Result<()> { + let link = shortcut_path().context("no Send to folder on this system")?; + if link.is_file() { + std::fs::remove_file(&link).with_context(|| format!("cannot delete {}", link.display()))?; + } + Ok(()) +} diff --git a/tests/edge_cases.rs b/tests/edge_cases.rs new file mode 100644 index 0000000..604d7c0 --- /dev/null +++ b/tests/edge_cases.rs @@ -0,0 +1,167 @@ +//! Videos unlike a game capture, end to end: no sound, shorter than a sample, portrait, an odd size, in a +//! folder whose name has accents, spaces and an apostrophe (and given as typed, not canonicalized). Each is +//! estimated and encoded with the Messenger profile and probed back. Skipped when FFmpeg is missing. +//! +//! Every clip is synthetic and written inside a fresh temporary folder. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use quick_video_transcoder::encode; +use quick_video_transcoder::estimate::{self, EstimateRequest}; +use quick_video_transcoder::ffmpeg::filters::Engine; +use quick_video_transcoder::ffmpeg::hardware::Capabilities; +use quick_video_transcoder::ffmpeg::probe::probe; +use quick_video_transcoder::naming; +use quick_video_transcoder::profile::Profile; +use quick_video_transcoder::queue::Slots; + +fn ffmpeg_available() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .is_ok_and(|o| o.status.success()) +} + +struct Clip { + name: &'static str, + size: (u32, u32), + rate: u32, + seconds: f64, + sound: bool, +} + +fn write_clip(dir: &Path, clip: &Clip) -> PathBuf { + let path = dir.join(clip.name); + assert!(path.starts_with(dir)); + let (width, height) = clip.size; + let mut command = Command::new("ffmpeg"); + command + .args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y"]) + .args(["-f", "lavfi", "-i"]) + .arg(format!( + "testsrc2=s={width}x{height}:r={}:d={}", + clip.rate, clip.seconds + )); + if clip.sound { + command + .args(["-f", "lavfi", "-i"]) + .arg(format!("sine=frequency=440:d={}", clip.seconds)); + } + let status = command + .args(["-vf", "noise=alls=8:allf=t,format=yuv420p"]) + .args(["-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac"]) + .arg(&path) + .status() + .expect("ffmpeg runs"); + assert!(status.success(), "cannot write {}", clip.name); + path +} + +fn encode_clip(dir: &Path, clip: &Clip, capabilities: &Capabilities) { + let source = write_clip(dir, clip); + let media = probe(&source).unwrap_or_else(|e| panic!("{}: {e:#}", clip.name)); + assert_eq!(media.audio.len(), usize::from(clip.sound), "{}", clip.name); + let profile = Profile { + max_size_mb: 2.0, + ..Profile::messenger() + }; + let request = EstimateRequest { + path: source.clone(), + media: media.clone(), + profile: profile.clone(), + start: 0.0, + end: media.duration, + // The software filters: the same on every machine, CI included. + engine: Engine::SOFTWARE, + encoder: capabilities + .choose(&profile.codecs, None) + .expect("an encoder works"), + }; + let slots = Slots::new(2); + let cancel = Arc::new(AtomicBool::new(false)); + let estimate = estimate::run(&request, &slots, &cancel) + .unwrap_or_else(|e| panic!("estimate of {}: {e:#}", clip.name)); + let output = naming::unique_output(dir, &format!("out-{}", clip.name), &source, &[]); + assert!(output.starts_with(dir)); + let encoded = encode::run(&request, &estimate, &output, &cancel, |_| {}) + .unwrap_or_else(|e| panic!("encode of {}: {e:#}", clip.name)); + assert!(encoded.bytes <= profile.max_bytes(), "{}", clip.name); + + let result = probe(&output).unwrap(); + let (width, height) = (result.width, result.height); + assert!( + width % 2 == 0 && height % 2 == 0, + "{}: {width}x{height}", + clip.name + ); + assert!(width.min(height) <= 720, "{}: {width}x{height}", clip.name); + let portrait = clip.size.1 > clip.size.0; + assert_eq!(height > width, portrait, "{}: orientation kept", clip.name); + assert_eq!( + result.audio.len(), + usize::from(clip.sound), + "{}: sound", + clip.name + ); + assert!( + (result.duration - media.duration).abs() < 0.15, + "{}: {} s for {} s", + clip.name, + result.duration, + media.duration + ); + eprintln!( + "{}: {} -> {width}x{height}, {} bytes", + clip.name, + estimate.target.label(), + encoded.bytes + ); +} + +#[test] +fn unusual_videos_encode_within_the_limit() { + if !ffmpeg_available() { + eprintln!("FFmpeg is not on the PATH: skipped"); + return; + } + let capabilities = Capabilities::detect(); + let temporary = tempfile::tempdir().unwrap(); + // As a user's folder would be typed: not canonicalized, with accents, spaces and an apostrophe. + let dir = temporary.path().join("Vidéos de l'été"); + std::fs::create_dir(&dir).unwrap(); + for clip in [ + Clip { + name: "no sound.mp4", + size: (1280, 720), + rate: 30, + seconds: 6.0, + sound: false, + }, + Clip { + name: "shorter than a sample.mp4", + size: (1920, 1080), + rate: 60, + seconds: 2.5, + sound: true, + }, + Clip { + name: "portrait.mp4", + size: (1080, 1920), + rate: 60, + seconds: 5.0, + sound: true, + }, + Clip { + name: "odd size é.mp4", + size: (854, 478), + rate: 25, + seconds: 5.0, + sound: true, + }, + ] { + encode_clip(&dir, &clip, &capabilities); + } +}