Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(export): pass the bitrate to the encoder and dither the GIF

EtienneLescot48714c685938
diff --git a/crates/compositor-view-napi/src/lib.rs b/crates/compositor-view-napi/src/lib.rs
index 7a9f87638..6c2c8a768 100644
--- a/crates/compositor-view-napi/src/lib.rs
+++ b/crates/compositor-view-napi/src/lib.rs
@@ -442,6 +442,9 @@ pub struct ExportParamsInput {
/// "h264" | "h265". Toute autre valeur (ex. "vp9", pas d'équivalent matériel AMF) fait
/// échouer l'export avec un message clair plutôt que de silencieusement retomber sur h264.
pub codec: Option<String>,
+ /// Débit vidéo visé, en bits/s, calculé par l'app d'après la taille et la cadence.
+ /// Absent ou nul → le repli du pipeline, qui ignore la cadence.
+ pub bitrate: Option<u32>,
}
/// Export multiclip mesuré (worker libuv). Rend la vraie timeline (clips + trims) en un MP4.
@@ -496,6 +499,7 @@ impl Task for ExportMultiTask {
export_params.height = height;
if let Some(p) = &self.params {
export_params.fps = p.fps;
+ export_params.bit_rate = p.bitrate.filter(|&b| b > 0).map(i64::from);
if let Some(codec) = &p.codec {
export_params.codec = match codec.as_str() {
"h264" => pipeline::ExportCodec::H264,
@@ -579,11 +583,9 @@ pub fn export_multi(
}
/// Sortie GIF native (slice 1) — taille, cadence, compteur de loop, dithering.
-/// Tout optionnel : absent → 854×480, 12 fps, boucle infinie, pas de
-/// dithering. Les défauts sont choisis pour un export « petit / net » :
-/// GIF est un format 256-couleurs, 12 fps est la cadence historique de
-/// `gif.js` côté renderer, et 854×480 tient confortablement dans la
-/// palette 8 bits sans banding visible sur du contenu de présentation.
+/// Tout optionnel : absent → 854×480, 12 fps, boucle infinie, dithering
+/// Floyd-Steinberg. GIF est un format 256-couleurs et 12 fps est la cadence
+/// historique de `gif.js` côté renderer.
#[napi(object)]
pub struct GifParamsInput {
pub width: Option<u32>,
@@ -591,9 +593,8 @@ pub struct GifParamsInput {
pub fps: Option<u32>,
/// Compteur de loop GIF : `None` ou `0` = infini, sinon `n` boucles.
pub loop_count: Option<u16>,
- /// Floyd-Steinberg error diffusion avant quantification. Off par
- /// défaut (qualité acceptable sans, et ça double تقريبًا le coût
- /// CPU du quantize par frame).
+ /// Floyd-Steinberg error diffusion à la quantification. Actif par défaut :
+ /// sans lui, un fond en dégradé se découpe en bandes (cf. `GifExportParams`).
pub dither: Option<bool>,
}
@@ -759,7 +760,7 @@ pub fn export_gif(
height: p.height,
fps: p.fps,
loop_count: p.loop_count,
- dither: p.dither.unwrap_or(false),
+ dither: p.dither.unwrap_or(GifExportParams::default().dither),
})
.unwrap_or_default();
Ok(AsyncTask::new(ExportGifTask {
diff --git a/crates/compositor/src/gif_export.rs b/crates/compositor/src/gif_export.rs
index e3fc12f4d..8215704c2 100644
--- a/crates/compositor/src/gif_export.rs
+++ b/crates/compositor/src/gif_export.rs
@@ -133,10 +133,12 @@ pub struct GifExportParams {
/// `None` or `0` → infinite loop (the historical GIF default).
/// Otherwise finite count.
pub loop_count: Option<u16>,
- /// Floyd-Steinberg dithering before quantization. Default off —
- /// the quantized result without dithering is usually acceptable
- /// for screen content, and dithering roughly doubles the per-frame
- /// CPU cost.
+ /// Floyd-Steinberg dithering at quantization. Default ON: the median
+ /// cut spreads its 256 entries over the whole frame, so a gradient
+ /// wallpaper gets a few dozen of them and, mapped to the nearest one,
+ /// breaks into flat bands. Error diffusion keeps its local average on
+ /// the ramp, and leaves a flat area flat: a colour that is in the
+ /// palette has no error to spread.
pub dither: bool,
}
@@ -147,7 +149,7 @@ impl Default for GifExportParams {
height: Some(DEFAULT_GIF_HEIGHT),
fps: Some(DEFAULT_GIF_FPS),
loop_count: None, // infinite
- dither: false,
+ dither: true,
}
}
}
@@ -1371,6 +1373,64 @@ mod tests {
assert!((indices[0] as usize) < PALETTE_COLORS);
}
+ /// What the dithering is for: a smooth ramp against a palette too coarse for it. That is
+ /// what a real frame hands a wallpaper gradient, since the median cut spreads 256 entries
+ /// over the whole frame, not over the one gradient. Nearest-colour mapping flattens the ramp
+ /// into wide bands; Floyd-Steinberg keeps its local average on the ramp.
+ #[test]
+ fn dithering_keeps_a_gradient_on_its_ramp_where_plain_mapping_bands() {
+ let (w, h) = (512usize, 8usize);
+ let ramp = |x: usize| (64 + x / 4) as u8; // grey 64..=191, a new level every 4 px
+ let rgba: Vec<u8> = (0..h)
+ .flat_map(|_| (0..w).flat_map(move |x| [ramp(x), ramp(x), ramp(x), 255]))
+ .collect();
+ // 16 greys, 17 levels apart, repeated to fill the 256 entries.
+ let palette: Vec<u8> =
+ (0..PALETTE_COLORS).flat_map(|i| [((i % 16) * 17) as u8; 3]).collect();
+
+ let mut plain = vec![0u8; w * h];
+ map_to_indices(&palette, &rgba, &mut plain);
+ let mut dithered = vec![0u8; w * h];
+ let (mut err_cur, mut err_next) = (vec![0.0f32; w * 3], vec![0.0f32; w * 3]);
+ map_to_indices_dithered(
+ &palette,
+ &rgba,
+ w as u32,
+ h as u32,
+ &mut err_cur,
+ &mut err_next,
+ &mut dithered,
+ );
+
+ // RMS distance between the ramp and a 16-px moving average of what a row maps to: the
+ // eye averages neighbouring pixels, so this is the banding it sees.
+ let row = h / 2;
+ let banding = |indices: &[u8]| -> f64 {
+ let k = 16;
+ let grey = |x: usize| palette[indices[row * w + x] as usize * 3] as f64;
+ let sq: Vec<f64> = (0..=w - k)
+ .map(|x0| {
+ let seen = (x0..x0 + k).map(grey).sum::<f64>() / k as f64;
+ let truth = (x0..x0 + k).map(|x| ramp(x) as f64).sum::<f64>() / k as f64;
+ (seen - truth).powi(2)
+ })
+ .collect();
+ (sq.iter().sum::<f64>() / sq.len() as f64).sqrt()
+ };
+ let (plain_err, dithered_err) = (banding(&plain), banding(&dithered));
+ assert!(plain_err > 3.0, "this palette should band the ramp (error {plain_err:.2})");
+ assert!(
+ dithered_err < 1.5,
+ "dithering left the ramp banded: {dithered_err:.2} vs {plain_err:.2} undithered"
+ );
+ }
+
+ /// The export dithers unless told not to: without it every gradient wallpaper bands.
+ #[test]
+ fn gif_export_dithers_by_default() {
+ assert!(GifExportParams::default().dither);
+ }
+
/// `GifWriter::new` rejects zero dimensions.
#[test]
fn gif_writer_rejects_zero_dimensions() {
diff --git a/crates/compositor/src/pipeline_linux.rs b/crates/compositor/src/pipeline_linux.rs
index 387e29319..b118befdd 100644
--- a/crates/compositor/src/pipeline_linux.rs
+++ b/crates/compositor/src/pipeline_linux.rs
@@ -63,12 +63,13 @@ pub enum ExportCodec {
H265,
}
-/// Params d'export. Memes champs que `pipeline_macos::ExportParams`.
+/// Params d'export. Memes champs que `pipeline_macos::ExportParams`, `bit_rate` compris.
pub struct ExportParams {
pub width: u32,
pub height: u32,
pub fps: Option<u32>,
pub codec: ExportCodec,
+ pub bit_rate: Option<i64>,
}
impl Default for ExportParams {
@@ -78,6 +79,7 @@ impl Default for ExportParams {
height: 1080,
fps: None,
codec: ExportCodec::H264,
+ bit_rate: None,
}
}
}
@@ -848,9 +850,10 @@ pub fn run_composited_multi(
}
let (out_w, out_h) = (params.width, params.height);
let out_fps = params.fps.unwrap_or(30) as i32;
- // bitrate proportionnel a la surface (reference : 8 Mbps @ 1920x1080). Formule
- // IDENTIQUE a celle de `pipeline_macos.rs` et `pipeline_windows.rs` : la garder
- // alignee est ce qui fait que les trois plateformes exportent au meme poids.
+ // Debit fourni par l'app, calcule d'apres la taille ET la cadence : c'est lui qui fait
+ // que les trois plateformes exportent au meme poids. Le repli (8 Mbps @ 1920x1080 quelle
+ // que soit la cadence) est IDENTIQUE a celui de `pipeline_macos.rs` et
+ // `pipeline_windows.rs`, et ne sert plus qu'au banc et aux tests.
//
// Sur `libopenh264` ce nombre n'est qu'indicatif : c'est une entree d'un modele
// complexite -> QP, pas un contrat. Il agit comme un plafond APPROXIMATIF sur du
@@ -858,7 +861,9 @@ pub fn run_composited_multi(
// 0,97 produit, 2 -> 1,72, 4 -> 2,86, 8 -> 3,85) et n'a aucun effet sur un ecran
// statique, ou l'encodeur sature son plancher de QP. Voir
// `VideoEncoder::tune_openh264` pour le pourquoi et ce qui a ete tente.
- let bit_rate = ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000);
+ let bit_rate = params.bit_rate.unwrap_or_else(|| {
+ ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000)
+ });
let t0 = std::time::Instant::now();
// L'ENCODEUR SE CHOISIT AVANT LE MUXER, parce que c'est lui qui decrit le
diff --git a/crates/compositor/src/pipeline_macos.rs b/crates/compositor/src/pipeline_macos.rs
index e1f206fec..93827b00c 100644
--- a/crates/compositor/src/pipeline_macos.rs
+++ b/crates/compositor/src/pipeline_macos.rs
@@ -720,12 +720,13 @@ pub struct EncoderCandidate {
pub pix_fmt: crate::ffi::AVPixelFormat::Type,
}
-/// Paramètres d'export. Identiques à `pipeline_windows::ExportParams`.
+/// Paramètres d'export. Identiques à `pipeline_windows::ExportParams`, `bit_rate` compris.
pub struct ExportParams {
pub width: u32,
pub height: u32,
pub fps: Option<u32>,
pub codec: ExportCodec,
+ pub bit_rate: Option<i64>,
}
impl Default for ExportParams {
@@ -735,6 +736,7 @@ impl Default for ExportParams {
height: 1080,
fps: None,
codec: ExportCodec::H264,
+ bit_rate: None,
}
}
}
@@ -1128,8 +1130,11 @@ pub fn run_composited_multi(
// fps : explicite > dérivé du premier clip.
let out_fps = params.fps.unwrap_or(30) as i32;
- // bitrate proportionnel à la surface de sortie (référence : 8Mbps @ 1920x1080).
- let bit_rate = ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000);
+ // Débit fourni par l'app (taille ET cadence). Repli pour le banc et les tests seulement,
+ // le même que `pipeline_windows` : 8Mbps @ 1920x1080 quelle que soit la cadence.
+ let bit_rate = params.bit_rate.unwrap_or_else(|| {
+ ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000)
+ });
// ---- decodeurs : un par chemin, réutilisés entre clips (screen ≠ webcam → 2 maps) ----
let mut screen_decs: std::collections::HashMap<String, Decoder> =
diff --git a/crates/compositor/src/pipeline_windows.rs b/crates/compositor/src/pipeline_windows.rs
index 67bd325d9..fabe31207 100644
--- a/crates/compositor/src/pipeline_windows.rs
+++ b/crates/compositor/src/pipeline_windows.rs
@@ -1596,16 +1596,20 @@ unsafe fn nv12_to_yuv420p(src: *mut AVFrame, dst: *mut AVFrame) {
/// Résolution/cadence/codec de sortie. `fps: None` = dérivé du 1er clip (comportement
/// historique) ; `width`/`height` doivent être pairs (NV12 4:2:0) — l'appelant napi arrondit.
+/// `bit_rate` (bits/s) : celui que l'app calcule d'après la taille ET la cadence
+/// (`calculateMp4ExportSettings`) ; `None` = le repli à la surface seule de `run_multi_inner`,
+/// que seuls le banc et les tests empruntent encore.
pub struct ExportParams {
pub width: u32,
pub height: u32,
pub fps: Option<u32>,
pub codec: ExportCodec,
+ pub bit_rate: Option<i64>,
}
impl Default for ExportParams {
fn default() -> Self {
- Self { width: OUT_W, height: OUT_H, fps: None, codec: ExportCodec::H264 }
+ Self { width: OUT_W, height: OUT_H, fps: None, codec: ExportCodec::H264, bit_rate: None }
}
}
@@ -1657,9 +1661,12 @@ unsafe fn run_multi_inner(
} else {
make_enc_frames(gpu, out_w as i32, out_h as i32)?
};
- // débit proportionnel à la surface de sortie (référence : 8Mbps @ 1920x1080), plancher
- // 2Mbps pour rester regardable sur les petites tailles.
- let bit_rate = ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000);
+ // Le débit vient de l'app, qui le calcule d'après la taille ET la cadence. Le repli
+ // (8Mbps @ 1920x1080 quelle que soit la cadence, plancher 2Mbps) ne sert plus qu'au banc et
+ // aux tests : c'est lui qui affamait un export 1080p60, deux fois plus d'images au même débit.
+ let bit_rate = params.bit_rate.unwrap_or_else(|| {
+ ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000)
+ });
let mut enc = VideoEncoder::open(
&params.codec,
out_w as i32,
diff --git a/crates/compositor/tests/compose_linux.rs b/crates/compositor/tests/compose_linux.rs
index f7a93b593..3120e7c6a 100644
--- a/crates/compositor/tests/compose_linux.rs
+++ b/crates/compositor/tests/compose_linux.rs
@@ -805,6 +805,7 @@ fn export_linux_mp4() {
height: 360,
fps: Some(30),
codec: ExportCodec::H264,
+ bit_rate: None,
};
let mut last = 0u64;
diff --git a/crates/compositor/tests/export_timing.rs b/crates/compositor/tests/export_timing.rs
index f0070794b..34d5e8de4 100644
--- a/crates/compositor/tests/export_timing.rs
+++ b/crates/compositor/tests/export_timing.rs
@@ -136,6 +136,7 @@ fn mp4_export_frame_count_follows_output_fps() {
height: 360,
fps: Some(30),
codec: ExportCodec::H264,
+ bit_rate: None,
};
let comp = Compositor::new_sized(&gpu, params.width, params.height).expect("compositor");
let out = dir.join("out_timing.mp4");
diff --git a/crates/poc-d3d/src/bench.rs b/crates/poc-d3d/src/bench.rs
index 4b7a6e0c7..3da91883b 100644
--- a/crates/poc-d3d/src/bench.rs
+++ b/crates/poc-d3d/src/bench.rs
@@ -260,15 +260,15 @@ fn run_gif_bench(
let out_path = Path::new(out).join("gif.gif");
std::fs::create_dir_all(out).ok();
- // The bench defaults to 854×480 / 12 fps / no dithering — exactly
+ // The bench defaults to 854×480 / 12 fps / dithering — exactly
// what `GifExportParams::default()` produces, which is the slice-1
// target. The user can override via `--gif-width`, `--gif-height`,
// `--gif-fps` flags if they want to probe the readback cost at
- // different sizes.
+ // different sizes, and `--gif-dither 0` to price the dithering.
let width: u32 = get("--gif-width", "854").parse().unwrap_or(854);
let height: u32 = get("--gif-height", "480").parse().unwrap_or(480);
let fps: u32 = get("--gif-fps", "12").parse().unwrap_or(12);
- let dither: bool = get("--gif-dither", "0") == "1";
+ let dither: bool = get("--gif-dither", "1") == "1";
let params = GifExportParams {
width: Some(width),
height: Some(height),
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
index 697c0ec1c..2ac90e08e 100644
--- a/electron/native/compositor-view/addon.d.ts
+++ b/electron/native/compositor-view/addon.d.ts
@@ -66,14 +66,14 @@ export interface RemuxStats {
}
/** Sortie GIF native : taille, cadence, loop, dither. Tout optionnel —
- * absent → 854×480, 12 fps, boucle infinie, pas de dithering. */
+ * absent → 854×480, 12 fps, boucle infinie, dithering Floyd-Steinberg. */
export interface GifParamsInput {
width?: number;
height?: number;
fps?: number;
/** GIF loop count: `0` or omitted = infinite, else `n` finite loops. */
loopCount?: number;
- /** Floyd-Steinberg error diffusion before quantization. Off by default. */
+ /** Floyd-Steinberg error diffusion at quantization. On by default. */
dither?: boolean;
}
@@ -86,6 +86,9 @@ export interface ExportParamsInput {
/** "h264" | "h265". Anything else (e.g. "vp9", no AMF hardware equivalent) fails the export
* with a clear error instead of silently falling back to h264. */
codec?: string;
+ /** Target video bitrate in bits/s, from the output size and frame rate. Omitted or 0 → the
+ * pipeline's own fallback, which ignores the frame rate (8 Mb/s at 1080p). */
+ bitrate?: number;
}
/** One timeline clip for the native multiclip export (screen + webcam files + source trim). */
@@ -183,7 +186,7 @@ export interface CompositorViewAddon {
* in the compositor crate and differ only in the encoder. Cursor, background,
* layout and webcam all come from the scene, so there is no GIF-specific
* input. No codec pick: GIF is one codec. `params` defaults to 854×480,
- * 12 fps, infinite loop, no dithering (`GifExportParams::default`).
+ * 12 fps, infinite loop, dithered (`GifExportParams::default`).
* `onProgress(frames)` is throttled to ~10/s like the MP4 path. */
exportGif(
clips: ClipInput[],
diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsx
index 653c5ea27..8edbfe2ae 100644
--- a/src/cli/CliExportRunner.tsx
+++ b/src/cli/CliExportRunner.tsx
@@ -304,6 +304,7 @@ async function runExport(request: CliExportRequest): Promise<CliDoneResult> {
sourceWidth: smallestSource.width,
sourceHeight: smallestSource.height,
aspectRatioValue,
+ frameRate: MP4_EXPORT_FPS,
});
const builtClips = buildNativeClipList(axcutDocument);
@@ -360,6 +361,7 @@ async function runExport(request: CliExportRequest): Promise<CliDoneResult> {
height: outDims.height,
fps: MP4_EXPORT_FPS,
codec: "h264",
+ bitrate: outDims.bitrate,
});
if (request.audioPath) {
diff --git a/src/components/ai-edition/ExportDialog.params.test.tsx b/src/components/ai-edition/ExportDialog.params.test.tsx
new file mode 100644
index 000000000..969657578
--- /dev/null
+++ b/src/components/ai-edition/ExportDialog.params.test.tsx
@@ -0,0 +1,130 @@
+// @vitest-environment jsdom
+// What the export dialog hands the native exporter. The MP4 bitrate used to be computed here and
+// never sent, so every export ran at the pipeline's own 8 Mb/s at 1080p, whatever its frame rate.
+import "@testing-library/jest-dom";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("@/native", () => ({
+ exportMultiNative: vi.fn(async () => ({ videoDurationS: 10, wallS: 2 })),
+ exportGifNative: vi.fn(async () => ({ videoDurationS: 10, wallS: 2 })),
+ useIsCpuCompositor: () => false,
+}));
+
+vi.mock("@/native/sceneDescription", () => ({
+ buildSceneDescription: () => ({ speedRegions: [] }),
+ resolveVisibleClips: (doc: AxcutDocument) => doc.timeline.clips,
+}));
+
+import { I18nProvider } from "@/contexts/I18nContext";
+import { type AxcutDocument, axcutSchemaVersion } from "@/lib/ai-edition/schema";
+import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
+import { exportMultiNative } from "@/native";
+import { ExportDialog } from "./ExportDialog";
+
+type ElectronAPI = Window["electronAPI"];
+
+const noop = () => undefined;
+
+const DOC: AxcutDocument = {
+ schemaVersion: axcutSchemaVersion,
+ project: {
+ id: "proj_1",
+ title: "Params",
+ createdAt: "2026-09-25T10:00:00Z",
+ updatedAt: "2026-09-25T10:00:00Z",
+ primaryAssetId: "a1",
+ },
+ assets: [
+ {
+ id: "a1",
+ kind: "video",
+ label: "asset",
+ originalPath: "/tmp/a.mp4",
+ cameraTrack: null,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 60 },
+ },
+ ],
+ transcript: null,
+ transcripts: [],
+ timeline: {
+ clips: [
+ {
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ audioTracks: [],
+ // A fixed format, so the 1080p tier is exactly 1920x1080 (Auto adds its padding border).
+ legacyEditor: { aspectRatio: "16:9" },
+};
+
+function renderDialog() {
+ render(
+ <I18nProvider>
+ <ExportDialog open={true} onClose={noop} document={DOC} />
+ </I18nProvider>,
+ );
+}
+
+/** Clicks Export, waits for the native call, and hands back the params it received. */
+async function exportMp4() {
+ fireEvent.click(screen.getByRole("button", { name: /export mp4/i }));
+ await waitFor(() => expect(exportMultiNative).toHaveBeenCalled());
+ const params = vi.mocked(exportMultiNative).mock.calls.at(-1)?.[3];
+ await screen.findByTestId("export-show-in-folder");
+ return params;
+}
+
+describe("ExportDialog MP4 params", () => {
+ beforeEach(() => {
+ window.electronAPI = {
+ pickExportSavePath: vi.fn(async () => ({ path: "/tmp/out.mp4" })),
+ onNativeExportProgress: vi.fn(() => noop),
+ } as unknown as ElectronAPI;
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ });
+
+ it("sends the bitrate for the frame rate it exports at", async () => {
+ renderDialog();
+ const expected = (frameRate: number) =>
+ calculateMp4ExportSettings({
+ quality: "good",
+ sourceWidth: 1920,
+ sourceHeight: 1080,
+ aspectRatioValue: 16 / 9,
+ frameRate,
+ }).bitrate;
+
+ const at60 = await exportMp4();
+ expect(at60).toMatchObject({ width: 1920, height: 1080, fps: 60, bitrate: expected(60) });
+
+ fireEvent.click(screen.getByRole("button", { name: "30" }));
+ const at30 = await exportMp4();
+ expect(at30).toMatchObject({ fps: 30, bitrate: expected(30) });
+ expect(at30?.bitrate).toBeLessThan(at60?.bitrate ?? 0);
+ });
+});
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 9ee343dc0..5cda39edb 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -271,6 +271,7 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
sourceWidth: smallestSource.width,
sourceHeight: smallestSource.height,
aspectRatioValue: EXPORT_ASPECT,
+ frameRate: fps,
})
: null;
@@ -434,6 +435,7 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
height: outDims?.height,
fps,
codec,
+ bitrate: outDims?.bitrate,
});
if (activeExport.current !== job) return;
setSavedPath(pickedPath);
diff --git a/src/lib/exporter/mp4ExportSettings.test.ts b/src/lib/exporter/mp4ExportSettings.test.ts
index c66029ee2..d99593a7e 100644
--- a/src/lib/exporter/mp4ExportSettings.test.ts
+++ b/src/lib/exporter/mp4ExportSettings.test.ts
@@ -15,11 +15,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 1920,
sourceHeight: 1032,
aspectRatioValue,
+ frameRate: 60,
}),
).toMatchObject({
width: 2008,
height: 1080,
- bitrate: 30_000_000,
});
expect(
@@ -28,11 +28,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 1920,
sourceHeight: 1032,
aspectRatioValue,
+ frameRate: 60,
}),
).toMatchObject({
width: 1920,
height: 1032,
- bitrate: 30_000_000,
});
});
@@ -43,11 +43,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 1920,
sourceHeight: 1032,
aspectRatioValue: 1920 / 1032,
+ frameRate: 60,
}),
).toMatchObject({
width: 1338,
height: 720,
- bitrate: 20_000_000,
});
});
@@ -58,11 +58,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 1280,
sourceHeight: 720,
aspectRatioValue: 16 / 9,
+ frameRate: 60,
}),
).toMatchObject({
width: 1920,
height: 1080,
- bitrate: 20_000_000,
});
});
@@ -73,11 +73,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 1920,
sourceHeight: 1080,
aspectRatioValue: 16 / 9,
+ frameRate: 60,
}),
).toMatchObject({
width: 1920,
height: 1080,
- bitrate: 30_000_000,
});
expect(
@@ -86,11 +86,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 3840,
sourceHeight: 2160,
aspectRatioValue: 16 / 9,
+ frameRate: 60,
}),
).toMatchObject({
width: 3840,
height: 2160,
- bitrate: 80_000_000,
});
});
@@ -101,11 +101,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: 1080,
sourceHeight: 1920,
aspectRatioValue: 9 / 16,
+ frameRate: 60,
}),
).toMatchObject({
width: 1080,
height: 1920,
- bitrate: 20_000_000,
});
});
@@ -117,6 +117,7 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: source.width,
sourceHeight: source.height,
aspectRatioValue: 16 / 9,
+ frameRate: 60,
});
// The reported bug: both tiers resolve to the exact same 1920x1080 frame, so they must
@@ -137,6 +138,7 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: source.width,
sourceHeight: source.height,
aspectRatioValue: 16 / 9,
+ frameRate: 60,
}),
source,
),
@@ -160,11 +162,11 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: effectiveSource.width,
sourceHeight: effectiveSource.height,
aspectRatioValue: effectiveSource.width / effectiveSource.height,
+ frameRate: 60,
}),
).toMatchObject({
width: 854,
height: 480,
- bitrate: 30_000_000,
});
expect(
@@ -173,11 +175,42 @@ describe("calculateMp4ExportSettings", () => {
sourceWidth: effectiveSource.width,
sourceHeight: effectiveSource.height,
aspectRatioValue: effectiveSource.width / effectiveSource.height,
+ frameRate: 60,
}),
).toMatchObject({
width: 1920,
height: 1080,
- bitrate: 20_000_000,
});
});
});
+
+describe("calculateMp4ExportSettings bitrate", () => {
+ const bitrate = (quality: "medium" | "good" | "source", frameRate: number, source = 1080) =>
+ calculateMp4ExportSettings({
+ quality,
+ sourceWidth: (source * 16) / 9,
+ sourceHeight: source,
+ aspectRatioValue: 16 / 9,
+ frameRate,
+ }).bitrate;
+
+ it("gives a 1080p60 export 18.7 Mb/s, where the pipeline alone gave it 8", () => {
+ expect(bitrate("good", 60)).toBe(18_662_400);
+ });
+
+ it("scales with the frame rate: twice the frames, twice the bits", () => {
+ expect(bitrate("good", 60)).toBe(2 * bitrate("good", 30));
+ expect(bitrate("good", 24)).toBeLessThan(bitrate("good", 30));
+ });
+
+ it("scales with the pixels, whichever tier produced them", () => {
+ // 4K is four 1080p frames; "Source" gets no bonus over the pixels it adds.
+ expect(bitrate("source", 60, 2160)).toBe(4 * bitrate("good", 60));
+ expect(bitrate("source", 60, 1080)).toBe(bitrate("good", 60));
+ expect(bitrate("medium", 60)).toBeLessThan(bitrate("good", 60));
+ });
+
+ it("keeps a floor for tiny outputs", () => {
+ expect(bitrate("source", 24, 180)).toBe(2_000_000);
+ });
+});
diff --git a/src/lib/exporter/mp4ExportSettings.ts b/src/lib/exporter/mp4ExportSettings.ts
index f2acdfeb2..f512204d8 100644
--- a/src/lib/exporter/mp4ExportSettings.ts
+++ b/src/lib/exporter/mp4ExportSettings.ts
@@ -113,18 +113,25 @@ function calculateSourceDimensions(
};
}
-function calculateBitrate(width: number, height: number, quality: ExportQuality) {
- const totalPixels = width * height;
-
- if (quality === "source") {
- if (totalPixels > 2560 * 1440) return 80_000_000;
- if (totalPixels > 1920 * 1080) return 50_000_000;
- return 30_000_000;
- }
+/**
+ * Bits the encoder may spend per pixel of each frame. Measured with NVENC on scrolled text under
+ * animated zooms, against the same export with no cap: at 1080p60 the quality climbs steeply up
+ * to 16-20 Mb/s and flattens after, and 0.15 sits on that knee (18.7 Mb/s; 9.3 at 1080p30).
+ * Equal quality took 1.6-1.9x the bits at 60 fps as at 30, so scaling linearly with the frame
+ * rate is right, if a little generous. It is a ceiling more than a spend: NVENC and AMF run VBR
+ * and a still screen costs far less.
+ */
+const BITS_PER_PIXEL = 0.15;
+/** Floor for tiny outputs, the native pipeline's own. */
+const MIN_BITRATE = 2_000_000;
- if (totalPixels <= 1280 * 720) return 10_000_000;
- if (totalPixels <= 1920 * 1080) return 20_000_000;
- return 30_000_000;
+/**
+ * The bitrate the native encoder is asked for: per pixel AND per frame. The frame rate is the
+ * half that used to be missing. The pipeline encoded 8 Mb/s at 1080p whatever the rate, so a
+ * 60 fps export spread the same bits over twice the frames.
+ */
+function calculateBitrate(width: number, height: number, frameRate: number) {
+ return Math.max(MIN_BITRATE, Math.round(width * height * frameRate * BITS_PER_PIXEL));
}
export function calculateMp4ExportSettings({
@@ -132,17 +139,19 @@ export function calculateMp4ExportSettings({
sourceWidth,
sourceHeight,
aspectRatioValue,
+ frameRate,
}: {
quality: ExportQuality;
sourceWidth: number;
sourceHeight: number;
aspectRatioValue: number;
+ frameRate: number;
}): Mp4ExportSettings {
if (quality === "medium") {
const dimensions = calculateDimensionsForShortSide(MEDIUM_SHORT_SIDE, aspectRatioValue);
return {
...dimensions,
- bitrate: calculateBitrate(dimensions.width, dimensions.height, quality),
+ bitrate: calculateBitrate(dimensions.width, dimensions.height, frameRate),
};
}
@@ -150,13 +159,13 @@ export function calculateMp4ExportSettings({
const dimensions = calculateDimensionsForShortSide(HIGH_SHORT_SIDE, aspectRatioValue);
return {
...dimensions,
- bitrate: calculateBitrate(dimensions.width, dimensions.height, quality),
+ bitrate: calculateBitrate(dimensions.width, dimensions.height, frameRate),
};
}
const sourceDimensions = calculateSourceDimensions(sourceWidth, sourceHeight, aspectRatioValue);
return {
...sourceDimensions,
- bitrate: calculateBitrate(sourceDimensions.width, sourceDimensions.height, quality),
+ bitrate: calculateBitrate(sourceDimensions.width, sourceDimensions.height, frameRate),
};
}
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 5c40ddcb0..ec247932d 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -193,23 +193,23 @@ export interface CompositorExportParams {
fps?: number;
/** "h264" | "h265" — pas de vp9 (aucun équivalent matériel AMF côté natif). */
codec?: string;
+ /** Débit vidéo visé (bits/s), d'après la taille ET la cadence
+ * (`calculateMp4ExportSettings`). Omis → 8 Mb/s à 1080p quelle que soit la cadence. */
+ bitrate?: number;
}
/** Sortie GIF native (le seul chemin GIF de l'app).
- * Tout omis → 854×480, 12 fps, boucle infinie, pas de dithering —
- * défauts choisis pour un GIF 8-bit-indexed lisible : 12 fps est la
- * cadence historique de `gif.js` côté renderer, 854×480 tient
- * confortablement dans la palette 256-couleurs sans banding visible
- * sur du contenu de présentation. Le dithering Floyd-Steinberg est off
- * par défaut (qualité acceptable sans, et double تقريبًا le coût CPU
- * du quantize par frame). */
+ * Tout omis → 854×480, 12 fps, boucle infinie, dithering Floyd-Steinberg :
+ * 12 fps est la cadence historique de `gif.js` côté renderer, et le
+ * dithering empêche un fond en dégradé de se découper en bandes sur la
+ * palette de 256 couleurs. */
export interface CompositorExportGifParams {
width?: number;
height?: number;
fps?: number;
/** Compteur de loop GIF : `0` ou omis = infini, sinon `n` boucles finies. */
loopCount?: number;
- /** Floyd-Steinberg error diffusion avant quantification. `false` par défaut. */
+ /** Floyd-Steinberg error diffusion à la quantification. `true` par défaut. */
dither?: boolean;
}
diff --git a/technical-documentation/architecture/export-pipeline.md b/technical-documentation/architecture/export-pipeline.md
index a0a952cf2..8df173ea1 100644
--- a/technical-documentation/architecture/export-pipeline.md
+++ b/technical-documentation/architecture/export-pipeline.md
@@ -129,8 +129,11 @@ and **one** encoder + muxer pair:
drift from the compositor). `ExportDialog`'s `tierOutputDims` feeds the
crop-aware **smallest** clip on the timeline to
[`calculateMp4ExportSettings`](../../src/lib/exporter/mp4ExportSettings.ts),
- which maps quality + source dims + aspect ratio to the encoder
- width / height / bitrate, and passes `width` / `height` to `exportMulti`.
+ which maps quality + source dims + aspect ratio + frame rate to the encoder
+ width / height / bitrate, and passes all three to `exportMulti`. The bitrate
+ is 0.15 bit per pixel per frame (18.7 Mb/s at 1080p60, 9.3 at 1080p30):
+ before it was passed, every export ran at the pipeline's own 8 Mb/s at
+ 1080p, whatever its frame rate.
Only "Source" quality targets those source dims; 720p / 1080p target a
fixed short side regardless.
**Auto** resolves in that same function: the first clip's cropped screen,
@@ -147,14 +150,16 @@ and **one** encoder + muxer pair:
## Output formats and codecs
-The native MP4 export takes `width`, `height`, `frameRate`, and `codec` as
+The native MP4 export takes `width`, `height`, `fps`, `codec` and `bitrate` as
parameters on `exportMulti` and writes H.264 (AMF) by default. The
user-facing codec choice crosses as the plain `ExportVideoCodec` string
(`"h264"` / `"h265"` / `"vp9"`) in those params; VP9
falls back to the same H.264 path on machines without a hardware VP9
encoder (software VP9 was measured too slow and removed — see
-[native-compositor.md](native-compositor.md#known-gaps)). GIF is a
-separate path through `GifExporter` and does not use the native addon.
+[native-compositor.md](native-compositor.md#known-gaps)). GIF goes through
+the same addon (`exportGif`, `gif_export.rs`): a median-cut palette per frame,
+mapped with Floyd-Steinberg dithering by default so a gradient wallpaper does
+not break into flat bands.
## Licensing
diff --git a/technical-documentation/engineering/rendering-performance.md b/technical-documentation/engineering/rendering-performance.md
index fec18d333..6fa913214 100644
--- a/technical-documentation/engineering/rendering-performance.md
+++ b/technical-documentation/engineering/rendering-performance.md
@@ -695,13 +695,14 @@ The slice-1 bench lives at `--cfg GIF` on the existing
mode). It drives `compositor::export_gif` end-to-end on the fixture
(`fixture/screen.mp4` + `fixture/webcam.mp4` + `fixture/screen.cursor.json`,
360 frames at 60 fps = 6 s source), defaulting to 854×480 / 12 fps /
-infinite loop / no dithering, and reports wall time, frame count, FPS,
-file size, ms/frame, and spread across `--repeat` runs.
+infinite loop / Floyd-Steinberg dithering (the app's default), and reports
+wall time, frame count, FPS, file size, ms/frame, and spread across
+`--repeat` runs.
```bash
# from crates/
x.bat run --release -- --cfg GIF --repeat 3 --out out/
-# optional overrides: --gif-width 1920 --gif-height 1080 --gif-fps 24 --gif-dither 1
+# optional overrides: --gif-width 1920 --gif-height 1080 --gif-fps 24 --gif-dither 0
```
Per the brief: "**the readback is the dominant per-frame cost**." That