From 2c9c3a24d0c9dd6e9afd9691d9aaf35d25665f58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 02:37:24 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(export):=20ExportSettings=20fo?= =?UTF-8?q?r=20bitrate=20and=20software-encoder=20pin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/export.rs | 46 +++++++++++++++++++++++++++++------ crates/engine/src/playback.rs | 16 +++++++++++- crates/engine/tests/export.rs | 34 ++++++++++++++++++++++++-- 3 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 6d1a127..108ec9e 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -36,6 +36,20 @@ const BITS_PER_PIXEL: f64 = 0.1; const MIN_BITRATE: u64 = 1_000_000; const MAX_BITRATE: u64 = 20_000_000; +/// What the caller gets to decide about the output. The codec and container are +/// not among it: H.264 in mp4 is the only pair with both an encoder and a +/// decoder under this project's no-install rule, so offering a choice would be +/// offering files we cannot read back. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ExportSettings { + /// Bits per second, clamped to the same sane range the automatic value uses. + /// `None` picks it from the picture size and frame rate. + pub bitrate: Option, + /// Skip the hardware encoder even where it is available -- an escape hatch + /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin. + pub force_sw: bool, +} + struct Shared { progress: AtomicU32, cancel: AtomicBool, @@ -80,7 +94,13 @@ impl ExportHandle { /// returned, so a caller has exactly one place to look. The files to read are /// the project's own [`sources`](Project::sources) -- every clip names one -- /// so nothing but the edit list decides what is decoded. -pub fn start(project: Project, meta: VideoMeta, out: &Path) -> ExportHandle { +pub fn start( + project: Project, + meta: VideoMeta, + out: &Path, + settings: &ExportSettings, +) -> ExportHandle { + let settings = *settings; let shared = Arc::new(Shared { progress: AtomicU32::new(0), cancel: AtomicBool::new(false), @@ -98,7 +118,7 @@ pub fn start(project: Project, meta: VideoMeta, out: &Path) -> ExportHandle { // The rename is the last step and the only one that publishes a file // under the name the caller asked for; it stays on the same directory, // so it is atomic. - let result = run(&project, &meta, &part, &worker) + let result = run(&project, &meta, &part, &worker, &settings) .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); if result.is_err() { // The muxer -- and with it the file handle -- died with `run`. @@ -118,7 +138,13 @@ fn settle(shared: &Shared, result: crate::Result<()>) { shared.finished.store(true, Ordering::Release); } -fn run(project: &Project, meta: &VideoMeta, out: &Path, shared: &Shared) -> crate::Result<()> { +fn run( + project: &Project, + meta: &VideoMeta, + out: &Path, + shared: &Shared, + settings: &ExportSettings, +) -> crate::Result<()> { let total = project.timeline_frames(); let sources = project.sources(); // Audio first: a track has to be declared when the muxer is created, which @@ -140,7 +166,7 @@ fn run(project: &Project, meta: &VideoMeta, out: &Path, shared: &Shared) -> crat chan_conf: track.chan_conf, }); - let mut encoder = Enc::open(meta)?; + let mut encoder = Enc::open(meta, settings)?; let mut muxer = None; let mut done = 0u32; for clip in project.clips() { @@ -255,12 +281,18 @@ enum Enc { } impl Enc { - fn open(meta: &VideoMeta) -> crate::Result { - let bitrate = bitrate_for(meta); + fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { + // A caller's number goes through the same clamp as the computed one: a + // zero bitrate switches the software encoder's lookahead on, which would + // break the one-picture-per-call contract `encode` documents below. + let bitrate = settings + .bitrate + .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); // The plugin wants an exact rational; a thousandth of a frame per second // is finer than any container fps we can read back. let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32; - if !forced("VE_SW_ENC") + if !settings.force_sw + && !forced("VE_SW_ENC") && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, 1_000, bitrate) { eprintln!("export encoder: hardware (VA-API plugin)"); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 390309d..3a3b652 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -562,8 +562,22 @@ impl PlaybackSession { /// /// Later edits do not reach a running export: it works from a snapshot of /// the edit list taken here. + /// + /// ponytail: this defaults the settings; the app still calls it that way, + /// and the export options card replaces the call with + /// [`export_to_with`](PlaybackSession::export_to_with). pub fn export_to(&self, out: &Path) -> crate::ExportHandle { - crate::export::start(self.project.clone(), self.meta, out) + self.export_to_with(out, &crate::export::ExportSettings::default()) + } + + /// [`export_to`](PlaybackSession::export_to) with the output settings spelled + /// out rather than defaulted. + pub fn export_to_with( + &self, + out: &Path, + settings: &crate::export::ExportSettings, + ) -> crate::ExportHandle { + crate::export::start(self.project.clone(), self.meta, out, settings) } /// Moves the clock forward; the caller runs this once per rendered frame. diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index c0b5bc1..164adff 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -19,6 +19,7 @@ use std::path::{Path, PathBuf}; use std::sync::Once; use std::time::{Duration, Instant}; +use engine::export::ExportSettings; use engine::hw::HwEncoder; use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; @@ -202,7 +203,7 @@ fn multi_source_round_trip(name: &str, limit: Duration) { let out = out_path(name); let started = Instant::now(); - let handle = engine::export::start(project.clone(), meta, &out); + let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default()); wait(&handle, limit).expect("export"); println!( "{name}: {total} frames of two sources in {:.2} s", @@ -274,6 +275,35 @@ fn exports_two_sources_as_one_timeline_in_hardware() { multi_source_round_trip("multi_hw", Duration::from_secs(60)); } +/// The bitrate setting is the one knob a user turns for quality, so it has to +/// reach the encoder: the same 120-frame timeline at 1, 4 and 8 Mbps has to come +/// back as three strictly growing files. `force_sw` pins the software encoder, +/// whose rate control is the one every machine has. +#[test] +fn a_higher_bitrate_writes_a_bigger_file() { + pin_software(); + let mut sizes = Vec::new(); + for bitrate in [1_000_000u64, 4_000_000, 8_000_000] { + let mut session = edited(&asset("test_baseline.mp4")); + session.pause(); + let out = out_path(&format!("bitrate_{bitrate}")); + let settings = ExportSettings { + bitrate: Some(bitrate), + force_sw: true, + }; + let handle = session.export_to_with(&out, &settings); + wait(&handle, Duration::from_secs(180)).expect("export"); + let size = std::fs::metadata(&out).expect("export exists").len(); + println!("{} Mbps: {size} bytes", bitrate / 1_000_000); + sizes.push(size); + std::fs::remove_file(&out).unwrap(); + } + assert!( + sizes[0] < sizes[1] && sizes[1] < sizes[2], + "file sizes {sizes:?} are not strictly growing with the bitrate" + ); +} + /// A source that disappears between the edit and the export fails the export /// rather than silently writing a shorter file -- and leaves neither an output /// nor a `.part`. Both sources are silent, so the failure is the per-clip open @@ -298,7 +328,7 @@ fn a_vanished_source_fails_the_export() { std::fs::remove_file(&doomed).expect("unlink the second source"); let out = out_path("vanished"); - let handle = engine::export::start(project, meta, &out); + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); let result = wait(&handle, Duration::from_secs(60)); let error = result.expect_err("an export of a missing file cannot succeed"); println!("vanished source: {error}");