Skip to content

fix(preview): avoid redundant AVIF and HEIF decodes - #1971

Merged
l0gicgate merged 2 commits into
mainfrom
fix/1968-avoid-redundant-image-decodes
Nov 1, 2026
Merged

l0gicgate merged 2 commits into
mainfrom
fix/1968-avoid-redundant-image-decodes

Conversation

@JoeJoeflyn

Copy link
Copy Markdown
Collaborator

Description

Reuse callers' dimension results instead of probing again in the pixbuf renderer. Read AVIF/HEIF primary-item dimensions and rotation from bounded ISO BMFF metadata, keeping the existing renderers, decode budgets, and compatibility fallbacks. Extend the existing camera-format scenario with AVIF and share its fixture setup.

Benchmark

Same synthetic 4000×3000, 12-bit AVIF (123 KB), one warm-up and five measured runs per operation; table values are medians. These call the real helper functions in-process, outside the decoder sandbox, under private Xvfb/D-Bus. Preview/reference use an 800 px edge; thumbnails use 256 px.

Operation Before After
Single decode + PNG reference 975 ms 729 ms
Quick Preview 2,751 ms 767 ms
Thumbnail 2,224 ms 929 ms
Image dimensions 856 ms 0.088 ms
Whole benchmark CPU time (user + system) 11.47 s 5.22 s

54% less measured CPU time. Preview cost falls from 2.82× to 1.05× the single-decode reference; thumbnails from 2.28× to 1.27×. The reference timings show normal machine-load variation, not an improvement to the codec itself. CPU totals include warm-ups and reference decodes, not just preview work. The temporary reproduction harness is recorded in the validation comment, not added as a flaky timing test.

Visual evidence

N/A — decoder performance change; the interface is unchanged.

How to test

  1. Put a large AVIF or HEIC beside a comparable JPEG and open the folder with thumbnails enabled.
  2. Select each image, press Space for Quick Preview, and inspect its dimensions. Include an image with an ISO BMFF rotation property.

Expected result: Correct thumbnails, previews, and oriented dimensions. Supported AVIF/HEIF headers provide dimensions without decoding pixels; each normal image render needs one full decode rather than three. Unsupported or cropped metadata retains the existing decoder fallback.

Related issue

Closes #1968

Read bounded primary-item spatial extents and rotation from ISO BMFF headers, then reuse probed dimensions in the existing pixbuf renderers. Keep decoder fallbacks and frame budgets intact, and extend the camera-format QA owner without duplicating fixture setup.

Refs #1968
@github-actions github-actions Bot added the fix label Oct 31, 2026
@JoeJoeflyn

Copy link
Copy Markdown
Collaborator Author

Validation and benchmark reproduction

Scope: bounded image decoding/metadata change, not a worker-pool, dependency, preference, or input-routing change. Coverage includes the shared image/RAW renderers and their fallbacks/budgets, sandbox transport/lifecycle, remote preview staging/cancellation, and the real camera-format thumbnail/preview paths. No repository-rule overrides were used.

Completed checks

  • ./scripts/test-headless.py --config profile.dev.debug=0 --config profile.test.debug=0 -j 2 sandbox_helper::tests:: — 39 passed, including the six new header/metadata regressions.
  • ./scripts/test-headless.py --config profile.dev.debug=0 --config profile.test.debug=0 -j 2 sandbox::browser:: — 21 passed.
  • ./scripts/test-headless.py --config profile.dev.debug=0 --config profile.test.debug=0 -j 2 adapters::local_preview::tests::remote_preview — 5 passed, including their GTK child runs.
  • ./scripts/quality.sh fmt and ./scripts/quality.sh clippy — passed in the verified pinned image.
  • ./scripts/qa.sh camera-formats-preview-sandbox — all 4 variants passed on four selected runs (16 successful scenario executions), including a final run after updating the cost map.
  • ./scripts/qa.sh camera-formats-preview-sandbox/columns-avif with an intentionally wrong red preview expectation — failed at the intended pixel assertion, reporting actual [255,255,255]. Restored the white expectation and reran the affected scenario successfully. No mutation patch was changed.
  • Drove AVIF and HEIC selection, Space preview, actual decoded pixels, closing, and retained file focus through qa-drive.sh in its container/private display/private bus. No GLib criticals in the successful replies. Stopped the session afterward. This is a manual observation, separate from the scenario evidence.
  • git diff --check — passed.

The new AVIF cost hint (0.4) is calibrated against the existing HEIC 0.4 weight: three scoped-run medians were 1.971 s for AVIF and 1.895 s for HEIC. Other historical weights are retained. A full global cost refresh was not run.

Intentional omissions: full local Rust and QA suites were not run for this bounded change; required CI remains the full gate before merge. The local QA quality rating remains I/C/K/D 3/3/4/4, score 33. Independent Haiku grading was attempted but unavailable because the configured model gateway rejected the model; it is not reported as passed. One initial cold native build was interrupted for memory pressure and repeated with debug information disabled/two jobs. An initial empty-fixture drive without a private session bus did not reach readiness; it was stopped and replaced with the seeded/private-bus session above, never a desktop fallback.

Reproduce the benchmark

The PR description contains the before/after measurements. The harness uses the same fixture and six calls per operation (one warm-up, then the median of five samples). CPU totals are shell user + system for the entire warmed workload, including reference decodes. The harness calls real helper functions in-process, outside the worker sandbox, as in the issue's original measurements. Its timing assertions fail on the baseline and pass with the fix; they are intentionally not added to CI.

Generate the fixture:

mkdir -p target/issue-1968
magick -limit thread 4 -seed 1968 -size 4000x3000 plasma:fractal target/issue-1968/source.png
avifenc --jobs 4 --speed 9 -q 30 target/issue-1968/source.png target/issue-1968/photo.avif

For each revision, temporarily save the following as target/issue-1968/benchmark.rs and declare it from src/sandbox_helper/tests.rs:

#[path = "../../target/issue-1968/benchmark.rs"]
mod issue_1968_benchmark;
Temporary benchmark source
use std::{path::Path, time::{Duration, Instant}};

fn median(mut run: impl FnMut()) -> Duration {
    run();
    let mut samples = Vec::new();
    for _ in 0..5 {
        let start = Instant::now();
        run();
        samples.push(start.elapsed());
    }
    samples.sort();
    samples[2]
}

#[test]
#[ignore = "temporary issue 1968 performance reproduction"]
fn avif_decode_work_is_not_repeated() {
    use crate::sandbox::browser::wire::Operation;
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("target/issue-1968/photo.avif");
    let single = median(|| {
        let pixbuf = gdk_pixbuf::Pixbuf::from_file_at_scale(&path, 800, 800, true)
            .expect("decode AVIF");
        std::hint::black_box(
            pixbuf.save_to_bufferv("png", &[("compression", "1")])
                .expect("encode PNG")
        );
    });
    let preview = median(|| {
        assert!(!super::super::browser_render(&path, Operation::PreviewImage)
            .png.is_empty());
    });
    let thumbnail = median(|| {
        assert!(!super::super::browser_render(&path, Operation::Image)
            .png.is_empty());
    });
    let metadata = median(|| {
        assert!(!super::super::browser_render(&path, Operation::ImageMetadata)
            .metadata.is_empty());
    });
    eprintln!("single={single:?} preview={preview:?} thumbnail={thumbnail:?} metadata={metadata:?}");
    assert!(preview.as_secs_f64() / single.as_secs_f64() < 2.0);
    assert!(thumbnail.as_secs_f64() / single.as_secs_f64() < 2.0);
    assert!(metadata.as_secs_f64() / single.as_secs_f64() < 0.1);
}

Prebuild/run once without timing, then run the same command on the baseline and PR revision:

TIMEFORMAT='wall=%R user=%U system=%S'
time ./scripts/test-headless.py --config profile.dev.debug=0 --config profile.test.debug=0 -j 2 avif_decode_work_is_not_repeated -- --ignored --nocapture

Remove the temporary module declaration afterward. No benchmark source, generated image, log, screenshot, or report is committed.

@JoeJoeflyn

Copy link
Copy Markdown
Collaborator Author

Follow-up profiling for the request to go faster (no production-code changes): on the same 12 MP fixture, fresh CLI medians were 1,227 ms for the current preview helper, 2,001 ms for the existing ImageMagick renderer, and 655 ms for an exploratory FFmpeg RGBA8 path with one decoder/filter thread. This CLI comparison includes process startup and is separate from the in-process benchmark in the description.

The FFmpeg prototype is not a safe drop-in: a transparent AVIF rendered by Strata retained alpha range 0–1, while the prototype became fully opaque (1–1). A 90-degree rotation fixture produced the correct 40×80 dimensions in both paths, but ICC/HDR behavior is not yet validated. Bare avifdec --info took 117 ms, but that excludes RGB conversion, resizing, and PNG output; its CLI is also absent from the pinned test image. It is not an end-to-end preview timing.

There is potential headroom, but a faster path needs complete image semantics rather than a quality-breaking decoder swap. The current branch remains unchanged and all required CI checks now pass. No additional production speedup or CPU reduction is being claimed from these exploratory measurements.

@l0gicgate

Copy link
Copy Markdown
Contributor

Review

Merged main at 8760486 into the branch (clean, no conflicts) and reviewed the full diff against it. No blockers found; no code changes beyond the merge.

What was checked

  • isobmff::dimensions box walking: size 0 / extended-size handling, ftyp gate, meta size cap (1 MiB), box-count cap, and seeking past mdat without reading pixel payloads.
  • metadata_dimensions / primary_properties: pitm v0/v1 item IDs, ipma v0/v1 and 8/16-bit associations with the essential bit masked, 1-based ipco indices, duplicate ispe and reserved irot bits rejected, clap deferring to the decoder.
  • Callers: browser_render (Image, ImageMetadata), render_raw, render_camera_raw, render_camera_raw_preview pass the already-probed dimensions into render_pixbuf, so the decoded-frame budget check is unchanged while the redundant file_info probe is gone. CR3 and other non-image ISO BMFF inputs fall through to the previous Pixbuf::file_info path.
  • Cross-checked the parser against gdk-pixbuf's file_info on real files generated with avifenc (plain, --irot 1, --irot 2, --imir 0, --clap), heif-enc (plain and a 3×2 tiled grid primary item), and an ImageMagick-rotated HEIC: oriented dimensions match in every case and the cropped AVIF correctly falls back to the decoder.
  • Tests: all six new isobmff tests exercise distinct behaviour (field widths, extended/to-end sizes, truncation at every byte, malformed and unassociated properties, read bounds on sparse multi-GiB input, budget enforcement from header-only files); nothing tautological to prune. Comments added by the PR are limited to two rationale notes and byte-layout annotations in test fixtures, all retained.
  • QA scenario: shared top-level setup plus per-variant setup is supported by the runner, and the new cached_in + pixel thumbnail assertion and preview pixel wait are existing step kinds.

Local verification (worktree, native)

  • ./scripts/test-headless.py -- sandbox_helper::tests:: sandbox::browser:: adapters::local_preview::tests::remote_preview — 65 passed plus 4 isolated GTK child runs, 0 failed.
  • ./scripts/qa.sh camera-formats-preview-sandbox — 4/4 variants passed (columns-heic, columns-avif, columns-mov, columns-mp4) in the pinned container.
  • cargo fmt --all --check and cargo clippy --all-targets --all-features -- -D warnings — clean.
  • Scoped validation per the repository's risk-based policy; the full Rust suite ran in CI on the merged head and is green.

CI on 3ce1215f3: all required checks pass (QA scenarios job is dispatch-only on PRs and skipped as usual).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AVIF previews and thumbnails decode the image three times

2 participants