Skip to content

Conversation

@Brendonovich
Copy link
Contributor

@Brendonovich Brendonovich commented Sep 23, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of H.264 video encoding on Windows by strengthening error handling when the encoder needs more input.
    • Clearer, more actionable error reporting during capture/export to reduce silent failures and simplify troubleshooting.
    • Better handling of buffer and timing steps to prevent occasional crashes or stalled encodes, yielding smoother, more predictable performance.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 23, 2025

Walkthrough

Adds a new HandleNeedsInputError enum and updates H264Encoder::handle_needs_input to return Result<(), HandleNeedsInputError>. Each intermediate windows::core::Error is mapped to a specific enum variant. unsafe impl Send for H264Encoder remains unchanged. No other files modified.

Changes

Cohort / File(s) Summary
H264 encoder error handling
crates/enc-mediafoundation/src/video/h264.rs
Added HandleNeedsInputError enum with variants ProcessTexture, CreateSurfaceBuffer, CreateSample, AddBuffer, SetSampleTime, and ProcessInput (each wrapping windows::core::Error); changed H264Encoder::handle_needs_input return type to Result<(), HandleNeedsInputError> and mapped errors from each processing step to the corresponding variant; retained unsafe impl Send for H264Encoder.

Sequence Diagram(s)

sequenceDiagram
    actor Caller
    participant Enc as H264Encoder
    participant MF as Media Foundation

    Caller->>Enc: handle_needs_input(input)
    Enc->>MF: ProcessTexture
    alt error
        Enc-->>Caller: Err(ProcessTexture)
    else success
        Enc->>MF: CreateSurfaceBuffer
        alt error
            Enc-->>Caller: Err(CreateSurfaceBuffer)
        else success
            Enc->>MF: CreateSample
            alt error
                Enc-->>Caller: Err(CreateSample)
            else success
                Enc->>MF: AddBuffer
                alt error
                    Enc-->>Caller: Err(AddBuffer)
                else success
                    Enc->>MF: SetSampleTime
                    alt error
                        Enc-->>Caller: Err(SetSampleTime)
                    else success
                        Enc->>MF: ProcessInput
                        alt error
                            Enc-->>Caller: Err(ProcessInput)
                        else success
                            Enc-->>Caller: Ok(())
                        end
                    end
                end
            end
        end
    end

    note over Enc,Caller: Each failure maps to a distinct HandleNeedsInputError variant.
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my nose at errors’ flight,
Six neat burrows labeled right;
From texture’s path to sample time,
Each hiccup gets its proper sign.
Now hopping through the input lane—
One enum keeps the traces plain. 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "dedicated handle-needs-input error" succinctly and accurately describes the primary change in the diff — introducing a dedicated HandleNeedsInputError enum and updating handle_needs_input to return it — and is concise and focused for a reviewer scanning history.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch handle-needs-input-error

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel
Copy link
Contributor

vercel bot commented Sep 23, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
cap-web Ready Ready Preview Comment Sep 23, 2025 4:52pm

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/enc-mediafoundation/src/video/h264.rs (1)

417-419: Bitrate calculation underflows for fps < 30 (u32 subtraction)

(fps - 30) underflows when fps < 30, skewing bitrate massively. Also risks intermediate overflow on large resolutions. Use saturating math and wider intermediates.

-fn calculate_bitrate(width: u32, height: u32, fps: u32, multiplier: f32) -> u32 {
-    ((width * height * ((fps - 30) / 2 + 30)) as f32 * multiplier) as u32
-}
+fn calculate_bitrate(width: u32, height: u32, fps: u32, multiplier: f32) -> u32 {
+    let fps_term = fps.saturating_sub(30) / 2 + 30;
+    let pixels = (width as u64) * (height as u64);
+    let base = pixels.saturating_mul(fps_term as u64);
+    let scaled = (base as f64 * multiplier as f64).round();
+    scaled.min(u32::MAX as f64) as u32
+}
🧹 Nitpick comments (2)
crates/enc-mediafoundation/src/video/h264.rs (2)

81-95: Public error enum: consider future-proofing with non_exhaustive

Good granular variants. To allow adding variants without a breaking change, mark the enum as non-exhaustive.

-#[derive(Clone, Debug, thiserror::Error)]
+#[non_exhaustive]
+#[derive(Clone, Debug, thiserror::Error)]
 pub enum HandleNeedsInputError {

389-391: Avoid negative sample times (edge-case robustness)

If a frame arrives with a timestamp earlier than the first, SetSampleTime may receive a negative value. Clamp at 0.

-            mf_sample
-                .SetSampleTime(timestamp.Duration - first_time.Duration)
-                .map_err(HandleNeedsInputError::SetSampleTime)?;
+            let sample_time = (timestamp.Duration - first_time.Duration).max(0);
+            mf_sample
+                .SetSampleTime(sample_time)
+                .map_err(HandleNeedsInputError::SetSampleTime)?;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 54b57fb and ebf9ed6.

📒 Files selected for processing (1)
  • crates/enc-mediafoundation/src/video/h264.rs (3 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
crates/**/src/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

For desktop IPC, use tauri_specta derive/macros on Rust types/events; do not hand-roll bindings

Files:

  • crates/enc-mediafoundation/src/video/h264.rs
**/*.{ts,tsx,js,jsx,rs}

📄 CodeRabbit inference engine (CLAUDE.md)

Do not add inline, block, or docstring comments in any language; code must be self-explanatory

Files:

  • crates/enc-mediafoundation/src/video/h264.rs
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Format Rust code using rustfmt and ensure all Rust code passes workspace-level clippy lints.
Rust modules should be named with snake_case, and crate directories should be in kebab-case.

Files:

  • crates/enc-mediafoundation/src/video/h264.rs
crates/*/src/**/*

📄 CodeRabbit inference engine (AGENTS.md)

Rust crates should place tests within the src/ and/or a sibling tests/ directory for each crate inside crates/*.

Files:

  • crates/enc-mediafoundation/src/video/h264.rs
🧬 Code graph analysis (1)
crates/enc-mediafoundation/src/video/h264.rs (1)
crates/scap-direct3d/src/lib.rs (1)
  • texture (454-456)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (rust)
  • GitHub Check: Build Desktop (aarch64-apple-darwin, macos-latest)
  • GitHub Check: Build Desktop (x86_64-pc-windows-msvc, windows-latest)
🔇 Additional comments (2)
crates/enc-mediafoundation/src/video/h264.rs (2)

369-372: Per-step error mapping looks good

The mapping of process_texture errors to HandleNeedsInputError::ProcessTexture is clean and consistent.


368-368: Signature change verified — call sites already handle HandleNeedsInputError

Call sites updated: crates/recording/src/capture_pipeline.rs (lines ~333, ~566) use .map_err(|e| format!("NeedsInput: {e}"))?; crates/enc-mediafoundation/examples/cli.rs (line ~157) checks .is_err() and breaks.

@Brendonovich Brendonovich merged commit e552530 into main Sep 23, 2025
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants