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(preview): stop leaking a decoded frame per scrub step

Etienne Lescotfafd046b7042
diff --git a/crates/compositor/src/linux_decode.rs b/crates/compositor/src/linux_decode.rs
index fb313f25b..e8bb81bc5 100644
--- a/crates/compositor/src/linux_decode.rs
+++ b/crates/compositor/src/linux_decode.rs
@@ -363,6 +363,21 @@ impl SwDecoder {
bail!("av_frame_alloc pour resultat");
}
}
+ // FUITE MÉMOIRE si on l'oublie. `av_frame_move_ref` écrase
+ // `found` SANS déréférencer ce qu'il contenait — c'est écrit
+ // noir sur blanc dans libavutil/frame.h : « dst is not
+ // unreferenced, but directly overwritten without reading or
+ // deallocating its contents. Call av_frame_unref(dst)
+ // manually before calling this function to ensure that no
+ // memory is leaked. »
+ //
+ // Cette boucle décode en avant depuis la keyframe jusqu'à la
+ // cible, donc elle passe ici une fois par frame du GOP. Sans
+ // ce unref, chaque frame intermédiaire abandonnait ses
+ // buffers : ~3,1 Mo en 1080p YUV420P, plusieurs dizaines de
+ // fois par scrub. Symptôme observé : le scrubbing ralentit
+ // progressivement, puis l'app gèle et meurt.
+ av_frame_unref(found);
av_frame_move_ref(found, frame);
av_frame_unref(frame);
if (*found).best_effort_timestamp as f64 * self.stream_timebase >= target_ts_seconds {
diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rs
index 95e1f23ce..e129d6e78 100644
--- a/electron/native/pipewire-capture/src/capture.rs
+++ b/electron/native/pipewire-capture/src/capture.rs
@@ -65,6 +65,28 @@ pub struct Selection {
pub rejected: Vec<String>,
}
+/// Bits per pixel per frame for H.264 screen content.
+///
+/// Screen recordings are mostly static and compress far better than camera
+/// footage, so this sits well below the ~0.2 a live-action encode would want.
+/// At 1920×1080/60 it comes to about 12 Mbit/s.
+const BITS_PER_PIXEL: f64 = 0.1;
+
+/// Picks a video bitrate from the size the compositor actually negotiated.
+///
+/// THE CALLER CANNOT DO THIS. On Wayland the app does not know the capture
+/// resolution until the portal has negotiated it — the user picks the source in
+/// the compositor's own dialog, and it may be a window rather than a display.
+/// The renderer therefore sends no bitrate at all. It used to send
+/// `computeBitrate(TARGET_WIDTH, TARGET_HEIGHT)`, whose constants are 4K, so a
+/// 1080p capture asked for 76.5 Mbit/s and produced 44 MB for 18 seconds.
+fn default_bitrate(width: i32, height: i32, fps: i32) -> i64 {
+ let pixels_per_second = f64::from(width.max(1)) * f64::from(height.max(1)) * f64::from(fps.max(1));
+ // Floor so that a tiny window capture still gets enough bits to look sharp,
+ // ceiling so that a 4K/120 stream cannot ask for something no disk wants.
+ ((pixels_per_second * BITS_PER_PIXEL) as i64).clamp(2_000_000, 60_000_000)
+}
+
pub struct Summary {
pub path: PathBuf,
pub duration_ms: u64,
@@ -101,10 +123,13 @@ impl Capture {
width: i32,
height: i32,
fps: i32,
- bitrate: i64,
+ // `None` derives one from the negotiated size, which is almost always
+ // what the caller wants — see `default_bitrate`.
+ bitrate: Option<i64>,
forced: Option<Backend>,
audio_sources: Vec<AudioSource>,
) -> Result<(Self, Selection), String> {
+ let bitrate = bitrate.unwrap_or_else(|| default_bitrate(width, height, fps));
let mut rejected = Vec::new();
let encoder = VideoEncoder::open(
VideoParams { width, height, fps, bitrate },
@@ -383,7 +408,7 @@ mod tests {
fn the_timeline_does_not_start_until_the_first_frame_is_staged() {
let output = std::env::temp_dir().join("openscreen-capture-epoch.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, 1_000_000, Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
.expect("start");
assert!(!capture.started());
// Nothing staged: advance must not write a frame of uninitialised memory.
@@ -402,7 +427,7 @@ mod tests {
// further arrivals, and the file must still fill with frames.
let output = std::env::temp_dir().join("openscreen-capture-static.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, 1_000_000, Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
.expect("start");
capture
.stage(&frame(320, 240, shim::constants().video_format_bgrx))
@@ -421,7 +446,7 @@ mod tests {
fn paused_time_does_not_advance_the_timeline() {
let output = std::env::temp_dir().join("openscreen-capture-pause.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, 1_000_000, Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
.expect("start");
capture
.stage(&frame(320, 240, shim::constants().video_format_bgrx))
@@ -458,7 +483,7 @@ mod tests {
320,
240,
30,
- 1_000_000,
+ Some(1_000_000),
Some(Backend::Software),
vec![AudioSource { label: "system", ring: ring.clone(), gain: 1.0, bitrate: 128_000 }],
)
@@ -491,7 +516,7 @@ mod tests {
320,
240,
30,
- 1_000_000,
+ Some(1_000_000),
Some(Backend::Software),
vec![AudioSource { label: "microphone", ring, gain: 4.0, bitrate: 128_000 }],
)
@@ -516,7 +541,7 @@ mod tests {
fn catch_up_is_bounded_so_a_stall_cannot_block_stop() {
let output = std::env::temp_dir().join("openscreen-capture-catchup.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 60, 1_000_000, Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 60, Some(1_000_000), Some(Backend::Software), Vec::new())
.expect("start");
capture
.stage(&frame(320, 240, shim::constants().video_format_bgrx))
diff --git a/electron/native/pipewire-capture/src/encoder.rs b/electron/native/pipewire-capture/src/encoder.rs
index 58202f6aa..03dd85067 100644
--- a/electron/native/pipewire-capture/src/encoder.rs
+++ b/electron/native/pipewire-capture/src/encoder.rs
@@ -301,7 +301,16 @@ impl VideoEncoder {
(*codec_ctx).framerate = ff::AVRational { num: params.fps, den: 1 };
(*codec_ctx).pix_fmt = backend.codec_pixel_format();
(*codec_ctx).bit_rate = params.bitrate;
- (*codec_ctx).gop_size = params.fps * 2;
+ // Half a second, not the two seconds a streaming preset would use.
+ //
+ // This file is an EDITING SOURCE, and the editor scrubs it. Seeking
+ // to an arbitrary point means decoding forward from the previous
+ // keyframe, so the GOP length is exactly the worst-case scrub cost:
+ // at 60 fps a two-second GOP makes the editor decode up to 120
+ // frames to show one. Halving it to 30 quarters that, and the extra
+ // keyframes cost a few percent of bitrate on screen content, which
+ // is mostly static and compresses well anyway.
+ (*codec_ctx).gop_size = (params.fps / 2).max(1);
// No B-frames. A screen recording has no use for them, they add
// reorder delay, and they force DTS bookkeeping the muxer would
// otherwise not need.
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index 8ec72db3e..7d2db6ce6 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -50,7 +50,6 @@ const DEFAULT_SAMPLE_INTERVAL_MS: u64 = 33;
const MIN_SAMPLE_INTERVAL_MS: u64 = 8;
const DEFAULT_FPS: i32 = 30;
-const DEFAULT_BITRATE: i64 = 8_000_000;
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -137,12 +136,15 @@ impl Request {
.unwrap_or(DEFAULT_FPS)
}
- fn bitrate(&self) -> i64 {
+ /// An explicit override, or `None` to let the encoder derive one from the
+ /// size the compositor negotiates. `None` is the normal case: on Wayland the
+ /// app cannot know the capture resolution in advance, so a bitrate chosen
+ /// caller-side is a guess about a picture nobody has seen yet.
+ fn bitrate(&self) -> Option<i64> {
self.video
.as_ref()
.and_then(|video| video.bitrate)
.filter(|bitrate| *bitrate > 0)
- .unwrap_or(DEFAULT_BITRATE)
}
/// The audio streams to open, in the order they become MP4 tracks.
@@ -289,7 +291,8 @@ struct RunConfig {
/// `None` for a cursor-only session.
output_path: Option<PathBuf>,
fps: i32,
- bitrate: i64,
+ /// `None` lets the encoder derive one from the negotiated size.
+ bitrate: Option<i64>,
forced_encoder: Option<encoder::Backend>,
cursor_mode: portal::CursorMode,
audio: Vec<AudioSourceConfig>,
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index d51cb261d..c42b2f8d4 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -1261,8 +1261,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const request: NativeLinuxRecordingRequest = {
recordingId: activeRecordingId,
video: {
+ // No bitrate on purpose. TARGET_WIDTH/HEIGHT are the app's 4K
+ // ceiling, not the capture size — on Wayland nobody knows that
+ // until the portal has negotiated it, and the user may well
+ // have picked a single window. Sending computeBitrate() of the
+ // ceiling asked for 76.5 Mbit/s for a 1080p capture. The helper
+ // derives it from the size it actually got.
fps: TARGET_FRAME_RATE,
- bitrate: computeBitrate(TARGET_WIDTH, TARGET_HEIGHT),
},
audio: {
system: { enabled: systemAudioEnabled },