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(recording): remux Linux captures so they carry a real Duration

Etienne Lescotac0e710dc5f2
diff --git a/crates/compositor-view-napi/src/lib.rs b/crates/compositor-view-napi/src/lib.rs
index 3d5635970..a68b0fe7a 100644
--- a/crates/compositor-view-napi/src/lib.rs
+++ b/crates/compositor-view-napi/src/lib.rs
@@ -656,3 +656,56 @@ pub fn export_gif(
on_progress: make_progress_tsfn(on_progress)?,
}))
}
+
+/// Bilan d'un remux, tel que le voit la glue TS.
+#[napi(object)]
+pub struct RemuxStats {
+ /// Paquets recopiés, toutes pistes confondues. `f64` car napi n'expose pas
+ /// `u64` — sans risque, un enregistrement plausible reste très loin de 2^53.
+ pub packets: f64,
+ pub streams: u32,
+ pub wall_s: f64,
+}
+
+pub struct RemuxTask {
+ input_path: String,
+ output_path: String,
+}
+
+impl Task for RemuxTask {
+ type Output = openscreen_compositor::remux::RemuxStats;
+ type JsValue = RemuxStats;
+
+ fn compute(&mut self) -> Result<Self::Output> {
+ openscreen_compositor::remux::remux_to_seekable_matroska(&self.input_path, &self.output_path)
+ .map_err(|e| Error::from_reason(format!("{e:#}")))
+ }
+
+ fn resolve(&mut self, _env: Env, out: Self::Output) -> Result<Self::JsValue> {
+ Ok(RemuxStats {
+ packets: out.packets as f64,
+ streams: out.streams,
+ wall_s: out.wall_s,
+ })
+ }
+}
+
+/// Recopie `input_path` vers `output_path` par le muxer matroska (aucun
+/// ré-encodage) pour doter le fichier des `Cues`/`SeekHead` que `MediaRecorder`
+/// n'écrit pas. Voir `openscreen_compositor::remux` pour le détail.
+///
+/// `AsyncTask` et pas une fonction synchrone : le remux lit et réécrit tout le
+/// fichier, ce qui se compte en secondes sur un long enregistrement. Le faire
+/// sur le thread principal de Node gèlerait la fenêtre pendant la sauvegarde,
+/// exactement au moment où l'UI affiche « enregistrement en cours ».
+///
+/// `output_path` doit être un chemin TEMPORAIRE : c'est au caller TS de
+/// renommer par-dessus l'original une fois la promesse résolue, pour qu'un échec
+/// laisse l'enregistrement intact.
+#[napi]
+pub fn remux_seekable(input_path: String, output_path: String) -> AsyncTask<RemuxTask> {
+ AsyncTask::new(RemuxTask {
+ input_path,
+ output_path,
+ })
+}
diff --git a/crates/compositor/src/lib.rs b/crates/compositor/src/lib.rs
index 1bbd293d8..d8972e7d1 100644
--- a/crates/compositor/src/lib.rs
+++ b/crates/compositor/src/lib.rs
@@ -34,6 +34,11 @@ pub mod ffi;
pub mod frame_geometry;
pub mod gif_export;
pub mod regions;
+// Multiplateforme à dessein : n'utilise que libavformat (liée sur les trois
+// cibles) et le shim C. Seul Linux l'appelle aujourd'hui, parce que c'est la
+// seule plateforme dont la capture passe par `MediaRecorder`, mais rien dedans
+// n'est spécifique à Linux.
+pub mod remux;
pub mod scene;
pub mod text_anim;
pub mod text_plate;
diff --git a/crates/compositor/src/remux.rs b/crates/compositor/src/remux.rs
new file mode 100644
index 000000000..e147f8e39
--- /dev/null
+++ b/crates/compositor/src/remux.rs
@@ -0,0 +1,248 @@
+//! Remux « stream copy » vers le muxer MATROSKA — réécrit un fichier en gardant
+//! ses paquets bit-pour-bit, uniquement pour lui donner un index de seek.
+//!
+//! # Le problème
+//!
+//! `MediaRecorder` (Chromium) écrit le WebM comme un flux **live** : il n'a pas
+//! le droit de revenir en arrière pour remplir un index, donc le fichier final
+//! n'a NI `Cues` NI `SeekHead`. Vérifié sur un vrai enregistrement de l'app :
+//! les deux magic bytes sont absents du début comme de la fin du fichier. Sans
+//! `Cues`, `av_seek_frame` n'a aucun point d'entrée et échoue pour tout
+//! timestamp non nul — d'où le repli « rembobine et scanne » linéaire de
+//! `linux_decode.rs`.
+//!
+//! # Le correctif
+//!
+//! Relire les paquets et les réécrire par le muxer matroska, qui lui connaît la
+//! taille finale du fichier et écrit donc `Cues` + `SeekHead` en fin de course
+//! (`av_write_trailer` revient au début patcher les offsets). Aucun ré-encodage :
+//! les paquets sont copiés tels quels, seuls les timestamps sont rebasés sur la
+//! timebase du flux de sortie. Mesuré sur un enregistrement réel de 7,8 Mo :
+//! 0,084 s et +378 octets.
+//!
+//! # Pourquoi `matroska` et pas `webm`
+//!
+//! Le muxer `webm` REFUSE ce fichier : « Only VP8 or VP9 or AV1 video and Vorbis
+//! or Opus audio ... are supported for WebM ». Chromium produit du **H.264 dans
+//! du WebM**, une combinaison hors spec que seul lui écrit. On force donc le
+//! muxer matroska par son nom (2e argument d'`avformat_alloc_output_context2`),
+//! ce qui court-circuite la déduction par extension — le fichier de sortie garde
+//! son nom `.webm` alors que son contenu est du Matroska, ce qui est un
+//! sur-ensemble strict et décrit le contenu plus honnêtement que ne le faisait
+//! `MediaRecorder`. L'extension NE CHANGE PAS : elle alimente le nom du sidecar
+//! curseur, le JSON de session et la persistance projet côté TS.
+//!
+//! # Effet de bord utile : la `Duration`
+//!
+//! Le muxer matroska recalcule la `Duration` à partir des timestamps réels des
+//! paquets, sans lire celle de l'entrée. Confronté à une entrée dont la
+//! `Duration` avait été forcée à 999999, il a écrit 16977 — la vraie valeur. Ce
+//! remux subsume donc le patch de `Duration` que `webm-duration.ts` applique
+//! par ailleurs (`MediaRecorder` ne l'écrit pas non plus).
+
+use anyhow::{bail, Context, Result};
+use std::ffi::CString;
+use std::ptr;
+
+use crate::ffi::{
+ av_interleaved_write_frame, av_packet_alloc, av_packet_free, av_packet_rescale_ts,
+ av_packet_unref, av_read_frame, av_write_trailer, avcodec_parameters_copy,
+ avformat_alloc_output_context2, avformat_close_input, avformat_find_stream_info,
+ avformat_free_context, avformat_new_stream, avformat_open_input, avformat_write_header,
+ averr, avio_closep, avio_open, sn_fmt_nb_streams, sn_fmt_set_pb, sn_fmt_stream, AVIOContext,
+ AVFormatContext, AVMediaType, AVPacket, AVIO_FLAG_WRITE,
+};
+
+/// Bilan d'un remux, remonté jusqu'à la glue TS pour la journalisation.
+#[derive(Debug)]
+pub struct RemuxStats {
+ /// Nombre de paquets recopiés (toutes pistes confondues).
+ pub packets: u64,
+ /// Nombre de pistes conservées dans la sortie.
+ pub streams: u32,
+ /// Durée du remux en secondes.
+ pub wall_s: f64,
+}
+
+/// Ferme les ressources libav* quel que soit le chemin de sortie (`?` compris).
+///
+/// Sans ça, chaque `?` du corps de `remux_to_seekable_matroska` fuiterait un
+/// `AVFormatContext` et un descripteur de fichier. `Drop` ne peut pas faillir,
+/// donc les erreurs de fermeture sont ignorées — on est déjà en train de rendre
+/// une erreur au caller quand ça arrive.
+struct RemuxGuard {
+ ictx: *mut AVFormatContext,
+ octx: *mut AVFormatContext,
+ pb: *mut AVIOContext,
+ pkt: *mut AVPacket,
+}
+
+impl Drop for RemuxGuard {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.pkt.is_null() {
+ av_packet_free(&mut self.pkt);
+ }
+ if !self.ictx.is_null() {
+ avformat_close_input(&mut self.ictx);
+ }
+ if !self.pb.is_null() {
+ avio_closep(&mut self.pb);
+ }
+ if !self.octx.is_null() {
+ avformat_free_context(self.octx);
+ self.octx = ptr::null_mut();
+ }
+ }
+ }
+}
+
+/// Recopie `input` vers `output` par le muxer matroska, sans ré-encoder.
+///
+/// `output` DOIT être un chemin temporaire distinct de `input` : le caller
+/// (`electron/recording/webm-seek-index.ts`) ne renomme par-dessus l'original
+/// qu'une fois le remux terminé, pour qu'un échec laisse l'enregistrement
+/// d'origine intact. Écrire directement sur `input` détruirait la seule copie
+/// des pixels dès la première erreur d'écriture.
+///
+/// Les pistes autres que vidéo/audio/sous-titre sont ignorées : `MediaRecorder`
+/// n'en produit pas, et un flux `DATA` ou `ATTACHMENT` inattendu ferait échouer
+/// `avformat_write_header` plutôt que de dégrader proprement.
+pub fn remux_to_seekable_matroska(input: &str, output: &str) -> Result<RemuxStats> {
+ if input == output {
+ bail!("remux : entrée et sortie identiques ({input}) — le caller doit passer un chemin temporaire");
+ }
+ let t0 = std::time::Instant::now();
+ let cin = CString::new(input).context("chemin d'entrée non convertible en CString")?;
+ let cout = CString::new(output).context("chemin de sortie non convertible en CString")?;
+ // Nom du muxer, PAS une extension : c'est l'équivalent de `-f matroska`.
+ let cfmt = CString::new("matroska").expect("littéral sans NUL");
+
+ let mut guard = RemuxGuard {
+ ictx: ptr::null_mut(),
+ octx: ptr::null_mut(),
+ pb: ptr::null_mut(),
+ pkt: ptr::null_mut(),
+ };
+
+ unsafe {
+ averr(
+ avformat_open_input(&mut guard.ictx, cin.as_ptr(), ptr::null_mut(), ptr::null_mut()),
+ "avformat_open_input",
+ )?;
+ averr(
+ avformat_find_stream_info(guard.ictx, ptr::null_mut()),
+ "avformat_find_stream_info",
+ )?;
+
+ averr(
+ avformat_alloc_output_context2(
+ &mut guard.octx,
+ ptr::null(),
+ cfmt.as_ptr(),
+ cout.as_ptr(),
+ ),
+ "avformat_alloc_output_context2(matroska)",
+ )?;
+ if guard.octx.is_null() {
+ bail!("avformat_alloc_output_context2 n'a pas alloué de contexte matroska");
+ }
+
+ // `stream_map[i]` = index de sortie de la piste d'entrée `i`, ou -1 si
+ // elle est ignorée. Les index de sortie sont réattribués en séquence,
+ // donc ils ne coïncident pas forcément avec ceux de l'entrée.
+ let nb_in = sn_fmt_nb_streams(guard.ictx);
+ let mut stream_map: Vec<i32> = vec![-1; nb_in as usize];
+ let mut nb_out: i32 = 0;
+ for i in 0..nb_in {
+ let istream = sn_fmt_stream(guard.ictx, i as i32);
+ if istream.is_null() {
+ continue;
+ }
+ let codec_type = (*(*istream).codecpar).codec_type;
+ if codec_type != AVMediaType::AVMEDIA_TYPE_VIDEO
+ && codec_type != AVMediaType::AVMEDIA_TYPE_AUDIO
+ && codec_type != AVMediaType::AVMEDIA_TYPE_SUBTITLE
+ {
+ continue;
+ }
+ let ostream = avformat_new_stream(guard.octx, ptr::null());
+ if ostream.is_null() {
+ bail!("avformat_new_stream a rendu NULL pour la piste {i}");
+ }
+ averr(
+ avcodec_parameters_copy((*ostream).codecpar, (*istream).codecpar),
+ "avcodec_parameters_copy",
+ )?;
+ // Le codec_tag est propre au conteneur d'origine ; le garder ferait
+ // écrire à matroska un tag qu'il ne reconnaît pas. 0 = « au muxer de
+ // choisir », c'est ce que fait `ffmpeg -c copy`.
+ (*(*ostream).codecpar).codec_tag = 0;
+ stream_map[i as usize] = nb_out;
+ nb_out += 1;
+ }
+ if nb_out == 0 {
+ bail!("remux : aucune piste vidéo/audio/sous-titre dans {input}");
+ }
+
+ averr(
+ avio_open(&mut guard.pb, cout.as_ptr(), AVIO_FLAG_WRITE as i32),
+ "avio_open",
+ )?;
+ sn_fmt_set_pb(guard.octx, guard.pb);
+ averr(
+ avformat_write_header(guard.octx, ptr::null_mut()),
+ "avformat_write_header",
+ )?;
+
+ guard.pkt = av_packet_alloc();
+ if guard.pkt.is_null() {
+ bail!("av_packet_alloc a rendu NULL");
+ }
+
+ let mut packets: u64 = 0;
+ loop {
+ let r = av_read_frame(guard.ictx, guard.pkt);
+ if r < 0 {
+ // Fin de fichier ou flux tronqué : dans les deux cas on écrit le
+ // trailer sur ce qu'on a. Un enregistrement coupé net (crash,
+ // batterie) reste lisible et devient seekable jusqu'à sa coupure.
+ break;
+ }
+ let in_idx = (*guard.pkt).stream_index;
+ let out_idx = stream_map
+ .get(in_idx as usize)
+ .copied()
+ .unwrap_or(-1);
+ if out_idx < 0 {
+ av_packet_unref(guard.pkt);
+ continue;
+ }
+ let istream = sn_fmt_stream(guard.ictx, in_idx);
+ let ostream = sn_fmt_stream(guard.octx, out_idx);
+ if istream.is_null() || ostream.is_null() {
+ av_packet_unref(guard.pkt);
+ continue;
+ }
+ av_packet_rescale_ts(guard.pkt, (*istream).time_base, (*ostream).time_base);
+ (*guard.pkt).stream_index = out_idx;
+ // `pos` décrit un offset dans le fichier d'ENTRÉE ; le laisser
+ // induirait le muxer en erreur sur la sortie.
+ (*guard.pkt).pos = -1;
+ let w = av_interleaved_write_frame(guard.octx, guard.pkt);
+ // `av_interleaved_write_frame` prend possession du paquet (il le
+ // déréférence lui-même), d'où l'absence d'`av_packet_unref` ici.
+ averr(w, "av_interleaved_write_frame")?;
+ packets += 1;
+ }
+
+ // C'est CE trailer qui écrit `Cues` puis revient patcher `SeekHead`.
+ averr(av_write_trailer(guard.octx), "av_write_trailer")?;
+
+ Ok(RemuxStats {
+ packets,
+ streams: nb_out as u32,
+ wall_s: t0.elapsed().as_secs_f64(),
+ })
+ }
+}
diff --git a/crates/compositor/tests/remux_seek_index.rs b/crates/compositor/tests/remux_seek_index.rs
new file mode 100644
index 000000000..5e209bc82
--- /dev/null
+++ b/crates/compositor/tests/remux_seek_index.rs
@@ -0,0 +1,164 @@
+//! Le remux doit doter un Matroska « live » (sans index) de ses `Cues`.
+//!
+//! C'est le filet du correctif « les enregistrements Linux ne sont pas
+//! seekables » : `MediaRecorder` écrit son WebM en flux live, donc sans `Cues`
+//! ni `SeekHead`, et `av_seek_frame` échoue alors pour tout timestamp non nul.
+//!
+//! Le test est AUTONOME — il ne dépend ni d'un binaire ffmpeg ni d'une fixture
+//! média (celles de `crates/fixture/` ne sont pas versionnées, cf.
+//! `export_timing.rs` qui doit être opt-in pour cette raison). Il fabrique son
+//! entrée avec le muxer matroska lui-même en mode `live=1`, qui est précisément
+//! le mode « je ne peux pas revenir en arrière » que subit `MediaRecorder` :
+//! aucun `Cues` n'est écrit. Une piste `rawvideo` porte quelques octets
+//! arbitraires — le test est de niveau CONTENEUR, la charge utile n'est jamais
+//! décodée.
+
+use openscreen_compositor::ffi::*;
+use openscreen_compositor::remux::remux_to_seekable_matroska;
+use std::ffi::CString;
+use std::ptr;
+
+/// ID EBML de `Cues` (0x1C53BB6B) et de `SeekHead` (0x114D9B74), en big-endian
+/// tels qu'ils apparaissent tels quels dans les octets du fichier.
+const CUES_ID: &[u8] = &[0x1C, 0x53, 0xBB, 0x6B];
+const SEEKHEAD_ID: &[u8] = &[0x11, 0x4D, 0x9B, 0x74];
+
+fn contains(haystack: &[u8], needle: &[u8]) -> bool {
+ haystack.windows(needle.len()).any(|w| w == needle)
+}
+
+/// Écrit un Matroska minimal SANS `Cues`, en forçant l'option `live` du muxer.
+///
+/// Retourne le nombre de paquets écrits, pour que le test puisse vérifier que le
+/// remux les retrouve tous.
+fn write_live_matroska(path: &str, packets: i64) -> i64 {
+ let cpath = CString::new(path).unwrap();
+ let cfmt = CString::new("matroska").unwrap();
+ unsafe {
+ let mut octx: *mut AVFormatContext = ptr::null_mut();
+ assert!(
+ avformat_alloc_output_context2(
+ &mut octx,
+ ptr::null(),
+ cfmt.as_ptr(),
+ cpath.as_ptr()
+ ) >= 0,
+ "alloc_output_context2"
+ );
+
+ let st = avformat_new_stream(octx, ptr::null());
+ assert!(!st.is_null(), "avformat_new_stream");
+ // VP8 : matroska le range en `V_VP8` sans jamais regarder la charge
+ // utile (contrairement à H264, qui exige un `extradata` avcC valide, et
+ // à RAWVIDEO, que le muxer refuse). Le test reste donc de niveau
+ // conteneur, sans encodeur ni bitstream réel.
+ (*(*st).codecpar).codec_type = AVMediaType::AVMEDIA_TYPE_VIDEO;
+ (*(*st).codecpar).codec_id = AVCodecID::AV_CODEC_ID_VP8;
+ (*(*st).codecpar).width = 16;
+ (*(*st).codecpar).height = 16;
+ // 1 ms par tick : les timestamps du test sont alors directement des ms.
+ (*st).time_base = AVRational { num: 1, den: 1000 };
+
+ let mut pb: *mut AVIOContext = ptr::null_mut();
+ assert!(
+ avio_open(&mut pb, cpath.as_ptr(), AVIO_FLAG_WRITE as i32) >= 0,
+ "avio_open"
+ );
+ sn_fmt_set_pb(octx, pb);
+
+ // `live=1` : le muxer se comporte comme s'il ne pouvait pas revenir en
+ // arrière — pas de Cues. C'est la contrainte que subit MediaRecorder.
+ let mut opts: *mut AVDictionary = ptr::null_mut();
+ let k = CString::new("live").unwrap();
+ let v = CString::new("1").unwrap();
+ av_dict_set(&mut opts, k.as_ptr(), v.as_ptr(), 0);
+ assert!(avformat_write_header(octx, &mut opts) >= 0, "write_header");
+ av_dict_free(&mut opts);
+
+ // Contenu arbitraire : jamais décodé, seul le conteneur est testé.
+ let payload = vec![0x42u8; 256];
+ let mut pkt = av_packet_alloc();
+ for i in 0..packets {
+ assert!(av_new_packet(pkt, payload.len() as i32) >= 0, "av_new_packet");
+ ptr::copy_nonoverlapping(payload.as_ptr(), (*pkt).data, payload.len());
+ (*pkt).stream_index = 0;
+ (*pkt).pts = i * 40; // 25 fps en timebase 1/1000
+ (*pkt).dts = i * 40;
+ (*pkt).duration = 40;
+ (*pkt).flags = AV_PKT_FLAG_KEY as i32;
+ assert!(
+ av_interleaved_write_frame(octx, pkt) >= 0,
+ "interleaved_write_frame"
+ );
+ }
+ av_packet_free(&mut pkt);
+ assert!(av_write_trailer(octx) >= 0, "write_trailer");
+ avio_closep(&mut pb);
+ avformat_free_context(octx);
+ }
+ packets
+}
+
+#[test]
+fn remux_adds_cues_to_a_live_matroska() {
+ // `avformat_find_stream_info` tente de décoder la charge utile bidon pour
+ // deviner les paramètres du flux et crache un « Invalid sync code » par
+ // paquet. C'est attendu ici (et sans effet : les `codecpar` sont déjà
+ // renseignés par le muxer d'entrée) ; on coupe le log pour que la sortie du
+ // test reste lisible.
+ unsafe { av_log_set_level(AV_LOG_QUIET) };
+
+ let dir = std::env::temp_dir().join(format!("openscreen-remux-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let input = dir.join("live.webm");
+ let output = dir.join("indexed.webm");
+ let input_s = input.to_str().unwrap().to_string();
+ let output_s = output.to_str().unwrap().to_string();
+
+ let written = write_live_matroska(&input_s, 25);
+
+ // Prémisse du correctif : l'entrée n'a PAS d'index. Si cette assertion
+ // tombe un jour, c'est le mode `live` du muxer qui a changé, et le test ne
+ // prouve plus rien — mieux vaut qu'il échoue ici que silencieusement.
+ let before = std::fs::read(&input).unwrap();
+ assert!(
+ !contains(&before, CUES_ID),
+ "l'entrée de test ne doit pas avoir de Cues (mode live)"
+ );
+
+ let stats = remux_to_seekable_matroska(&input_s, &output_s).expect("remux");
+
+ let after = std::fs::read(&output).unwrap();
+ assert!(contains(&after, CUES_ID), "la sortie doit contenir des Cues");
+ assert!(
+ contains(&after, SEEKHEAD_ID),
+ "la sortie doit contenir un SeekHead"
+ );
+ assert_eq!(stats.packets, written as u64, "tous les paquets recopiés");
+ assert_eq!(stats.streams, 1);
+
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn remux_refuses_to_write_over_its_own_input() {
+ // Garde-fou : écrire sur l'entrée détruirait la seule copie des pixels dès
+ // la première erreur d'écriture. Le contrat « passe un chemin temporaire »
+ // est vérifié, pas seulement documenté.
+ let err = remux_to_seekable_matroska("/tmp/same.webm", "/tmp/same.webm")
+ .expect_err("doit refuser entrée == sortie");
+ assert!(err.to_string().contains("identiques"), "message: {err}");
+}
+
+#[test]
+fn remux_reports_an_error_for_a_missing_input() {
+ // Le caller TS traite toute erreur comme « garde l'original » ; encore
+ // faut-il qu'une entrée absente en produise une plutôt que de paniquer.
+ let out = std::env::temp_dir().join("openscreen-remux-never-written.webm");
+ let err = remux_to_seekable_matroska(
+ "/nonexistent/openscreen/no-such-recording.webm",
+ out.to_str().unwrap(),
+ )
+ .expect_err("doit échouer sur une entrée absente");
+ assert!(err.to_string().contains("avformat_open_input"), "message: {err}");
+}
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 7dc8c1092..308784c1d 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -56,6 +56,7 @@ import { createCursorRecordingSession } from "../native-bridge/cursor/recording/
import { requestMacCursorAccessibilityAccess } from "../native-bridge/cursor/recording/macNativeCursorRecordingSession";
import type { CursorRecordingSession } from "../native-bridge/cursor/recording/session";
import { patchWebmDurationOnDisk } from "../recording/webm-duration";
+import { reindexRecordingOnDisk } from "../recording/webm-seek-index";
import { registerNativeBridgeHandlers } from "./nativeBridge";
import { RecordingStreamRegistry, registerRecordingStreamHandlers } from "./recordingStream";
@@ -307,6 +308,37 @@ async function finalizeRecordingFile(
return streamed;
}
+/**
+ * Give a finalized recording a usable container, by whichever route works.
+ *
+ * MediaRecorder omits the `Duration` header, so without repair the editor sees
+ * `duration = Infinity` and cannot scale its timeline.
+ *
+ * Two routes, in order of quality:
+ * 1. A full container remux through libavformat's matroska muxer (Linux, where
+ * capture goes through MediaRecorder). The muxer derives `Duration` from
+ * the real packet timestamps rather than from the renderer's wall-clock
+ * measurement, and writes `Cues`/`SeekHead` on the way past.
+ * 2. The EBML header patch, which splices the caller's `durationMs` into the
+ * Info section. Used on Windows/macOS, and on Linux whenever the remux is
+ * unavailable (no addon, or a `.node` predating it) or fails.
+ *
+ * Both rewrite the file exactly once, so route 1 is not the more expensive one —
+ * it is the same I/O for a strictly better result. Either way a failure leaves
+ * the original file intact; a recording is never lost to a failed repair.
+ */
+async function repairRecordingContainer(filePath: string, durationMs: number): Promise<void> {
+ const reindexed = await reindexRecordingOnDisk(filePath);
+ if (reindexed.reindexed) {
+ console.info(
+ `[recording] re-muxed ${path.basename(filePath)}: ${reindexed.packets} packets, ` +
+ `${reindexed.streams} streams, ${reindexed.wallS.toFixed(3)}s`,
+ );
+ return;
+ }
+ await patchWebmDurationOnDisk(filePath, durationMs);
+}
+
async function getApprovedProjectSession(
project: unknown,
projectFilePath?: string,
@@ -2539,15 +2571,15 @@ export function registerIpcHandlers(
}
// Streamed files lack the WebM Duration header (renderer no longer holds the
- // blob), so patch on disk for the editor's seek bar and timeline. Best-effort,
- // independent per file, so they run together.
+ // blob), so repair the container on disk for the editor's seek bar and timeline.
+ // Best-effort, independent per file, so they run together.
if (isValidDurationMs(payload.durationMs)) {
const patches: Promise<unknown>[] = [];
if (screenStreamed) {
- patches.push(patchWebmDurationOnDisk(screenVideoPath, payload.durationMs));
+ patches.push(repairRecordingContainer(screenVideoPath, payload.durationMs));
}
if (webcamStreamed && webcamVideoPath) {
- patches.push(patchWebmDurationOnDisk(webcamVideoPath, payload.durationMs));
+ patches.push(repairRecordingContainer(webcamVideoPath, payload.durationMs));
}
await Promise.all(patches);
}
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
index 7400b4a6d..9efc302ec 100644
--- a/electron/native-bridge/services/compositorViewService.ts
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -15,6 +15,7 @@ import type {
GifExportStats,
GifParamsInput,
NativeFramePacket,
+ RemuxStats,
} from "../../native/compositor-view/addon";
/**
@@ -575,4 +576,23 @@ export class CompositorViewService {
onProgress,
);
}
+
+ /** Stream-copy `inputPath` to `outputPath` through libavformat's matroska muxer.
+ * No re-encode: the packets are copied verbatim and only the container is rebuilt,
+ * which is what gives the output a real `Duration`, `Cues` and `SeekHead`.
+ *
+ * `outputPath` must be a TEMPORARY path — the caller renames it over the original
+ * only once this resolves, so a failure leaves the recording untouched. See
+ * `electron/recording/webm-seek-index.ts`, the only caller.
+ *
+ * Returns null when the addon is absent, or when it predates this export (a stale
+ * `.node` from an earlier build): the caller then keeps the file as it is rather
+ * than treating a missing optimisation as a failed save. */
+ async remuxSeekable(inputPath: string, outputPath: string): Promise<RemuxStats | null> {
+ const addon = this.ensureAddon();
+ if (!addon?.remuxSeekable) {
+ return null;
+ }
+ return addon.remuxSeekable(inputPath, outputPath);
+ }
}
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
index da0172c31..dc5fe599a 100644
--- a/electron/native/compositor-view/addon.d.ts
+++ b/electron/native/compositor-view/addon.d.ts
@@ -56,6 +56,15 @@ export interface GifExportStats {
fileBytes: number;
}
+/** Outcome of a container-only remux — see `remuxSeekable`. */
+export interface RemuxStats {
+ /** Packets copied verbatim, all streams combined. */
+ packets: number;
+ /** Streams kept in the output (video/audio/subtitle; anything else is dropped). */
+ streams: number;
+ wallS: number;
+}
+
/** Sortie GIF native : taille, cadence, loop, dither. Tout optionnel —
* absent → 854×480, 12 fps, boucle infinie, pas de dithering. */
export interface GifParamsInput {
@@ -172,6 +181,15 @@ export interface CompositorViewAddon {
params?: GifParamsInput,
onProgress?: (frames: number) => void,
): Promise<GifExportStats>;
+
+ /** Stream-copy `inputPath` to `outputPath` through the matroska muxer, rebuilding the
+ * container (real `Duration` computed from the packet timestamps, plus `Cues` and
+ * `SeekHead`) without re-encoding a single frame.
+ *
+ * Optional at the type level: a `.node` built before this export exists in the wild
+ * (dev trees keep a stale binary until the next `build-linux-compositor-addon.mjs`),
+ * and the caller degrades to "leave the file alone" rather than failing the save. */
+ remuxSeekable?(inputPath: string, outputPath: string): Promise<RemuxStats>;
}
/**
diff --git a/electron/recording/webm-seek-index.test.ts b/electron/recording/webm-seek-index.test.ts
new file mode 100644
index 000000000..fd654a3a6
--- /dev/null
+++ b/electron/recording/webm-seek-index.test.ts
@@ -0,0 +1,133 @@
+import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { reindexRecordingOnDisk } from "./webm-seek-index";
+
+/**
+ * The property under test is not "does libavformat work" — the Rust side owns
+ * that, and `crates/compositor/tests/remux_seek_index.rs` proves it. It is the
+ * far more expensive-to-get-wrong half: a failed re-index must never cost the
+ * user a recording. So the addon is stubbed and every way it can fail is driven
+ * through the wrapper, asserting each time that the original bytes survive.
+ */
+describe("recording re-index", () => {
+ let dir: string;
+ const ORIGINAL = "original recording bytes";
+
+ beforeEach(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), "openscreen-reindex-"));
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ });
+
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+ });
+
+ async function makeRecording(name = "recording-1.webm"): Promise<string> {
+ const filePath = path.join(dir, name);
+ await writeFile(filePath, ORIGINAL);
+ return filePath;
+ }
+
+ /** Stands in for the napi addon: writes `output` then reports success. */
+ const fakeRemux = (payload: string) => ({
+ remuxSeekable: vi.fn(async (_input: string, output: string) => {
+ await writeFile(output, payload);
+ return { packets: 42, streams: 2, wallS: 0.05 };
+ }),
+ });
+
+ it("replaces the file with the remuxed output on success", async () => {
+ const filePath = await makeRecording();
+ const service = fakeRemux("remuxed bytes");
+
+ const result = await reindexRecordingOnDisk(filePath, service);
+
+ expect(result).toEqual({ reindexed: true, packets: 42, streams: 2, wallS: 0.05 });
+ expect(await readFile(filePath, "utf8")).toBe("remuxed bytes");
+ });
+
+ it("writes to a temporary sibling and leaves none behind", async () => {
+ const filePath = await makeRecording();
+ const service = fakeRemux("remuxed bytes");
+
+ await reindexRecordingOnDisk(filePath, service);
+
+ // Same directory as the recording, so the rename is same-filesystem and
+ // therefore atomic — a temp dir could be another mount.
+ const outputArg = service.remuxSeekable.mock.calls[0][1];
+ expect(path.dirname(outputArg)).toBe(path.dirname(filePath));
+ expect(outputArg).not.toBe(filePath);
+ await expect(stat(outputArg)).rejects.toThrow();
+ });
+
+ it("keeps the original when the remux throws", async () => {
+ const filePath = await makeRecording();
+ const service = {
+ remuxSeekable: vi.fn(async () => {
+ throw new Error("avformat_open_input a échoué (ret=-2)");
+ }),
+ };
+
+ const result = await reindexRecordingOnDisk(filePath, service);
+
+ expect(result).toEqual({ reindexed: false, reason: "remux-failed" });
+ expect(await readFile(filePath, "utf8")).toBe(ORIGINAL);
+ });
+
+ it("keeps the original when the remux leaves a truncated 0-byte file", async () => {
+ // A muxer that errors after opening its output still leaves a file behind.
+ // Renaming that over the recording would destroy it.
+ const filePath = await makeRecording();
+ const service = {
+ remuxSeekable: vi.fn(async (_input: string, output: string) => {
+ await writeFile(output, "");
+ return { packets: 0, streams: 0, wallS: 0.01 };
+ }),
+ };
+
+ const result = await reindexRecordingOnDisk(filePath, service);
+
+ expect(result).toEqual({ reindexed: false, reason: "empty-output" });
+ expect(await readFile(filePath, "utf8")).toBe(ORIGINAL);
+ });
+
+ it("keeps the original when the addon is absent", async () => {
+ const filePath = await makeRecording();
+ const service = { remuxSeekable: vi.fn(async () => null) };
+
+ const result = await reindexRecordingOnDisk(filePath, service);
+
+ expect(result).toEqual({ reindexed: false, reason: "no-addon" });
+ expect(await readFile(filePath, "utf8")).toBe(ORIGINAL);
+ });
+
+ it("clears a stale temporary file left by an earlier interrupted run", async () => {
+ const filePath = await makeRecording();
+ const stalePath = `${filePath}.reindex.tmp`;
+ await writeFile(stalePath, "leftover from a crashed save");
+ const service = fakeRemux("remuxed bytes");
+
+ const result = await reindexRecordingOnDisk(filePath, service);
+
+ expect(result).toMatchObject({ reindexed: true });
+ expect(await readFile(filePath, "utf8")).toBe("remuxed bytes");
+ });
+
+ it("does nothing on platforms whose capture already writes indexed files", async () => {
+ const filePath = await makeRecording();
+ const service = fakeRemux("remuxed bytes");
+ const platform = process.platform;
+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });
+ try {
+ const result = await reindexRecordingOnDisk(filePath, service);
+ expect(result).toEqual({ reindexed: false, reason: "unsupported-platform" });
+ expect(service.remuxSeekable).not.toHaveBeenCalled();
+ expect(await readFile(filePath, "utf8")).toBe(ORIGINAL);
+ } finally {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+ }
+ });
+});
diff --git a/electron/recording/webm-seek-index.ts b/electron/recording/webm-seek-index.ts
new file mode 100644
index 000000000..06430d290
--- /dev/null
+++ b/electron/recording/webm-seek-index.ts
@@ -0,0 +1,105 @@
+import fs from "node:fs/promises";
+import { CompositorViewService } from "../native-bridge/services/compositorViewService";
+
+export type ReindexResult =
+ | { reindexed: true; packets: number; streams: number; wallS: number }
+ | {
+ reindexed: false;
+ reason: "unsupported-platform" | "no-addon" | "remux-failed" | "empty-output" | "io-error";
+ };
+
+/**
+ * Rebuild a finalized recording's container so it carries a real `Duration`,
+ * `Cues` and `SeekHead`.
+ *
+ * WHY THIS EXISTS — and what it does NOT fix.
+ *
+ * MediaRecorder writes WebM as a live stream: it never rewinds to fill in an
+ * index, so the file has neither `Cues` nor `SeekHead` (confirmed by scanning
+ * the bytes of real recordings — both magic sequences absent from head and
+ * tail). The obvious conclusion is that seeking must be broken. It is NOT:
+ * measured on this machine, `av_seek_frame` returns 0 for every timestamp and
+ * every flag on every real recording, because libavformat's matroska demuxer
+ * falls back to a byte-offset binary search when there is no index. Chromium's
+ * `<video>` seeks those same files correctly too — every seek landed exactly on
+ * target, within noise of the indexed copy. On a 10-minute/44MB file the index
+ * is worth 0.23ms per libavformat seek. That is not a bug anyone can see.
+ *
+ * What the remux DOES buy, measured:
+ * - A real `Duration`, computed by the muxer from the actual packet
+ * timestamps. Without one, Chromium reports `duration = Infinity` and
+ * `seekable = 0..Infinity`, which breaks any timeline that scales to the
+ * clip length. This is the same problem `webm-duration.ts` exists to solve,
+ * and the muxer solves it from the packets instead of from a wall-clock
+ * estimate handed down by the renderer (16.977s vs the 17.013s the header
+ * patch wrote for the same file).
+ * - A standards-conformant container, rather than the H.264-in-WebM
+ * combination only Chromium emits.
+ *
+ * So this REPLACES the duration patch on Linux rather than adding to it. Both
+ * rewrite the file exactly once, so the I/O cost is unchanged; the output is
+ * strictly more correct. When the remux is unavailable or fails, the caller
+ * falls back to the header patch and behaviour is exactly what it was before.
+ *
+ * MEMORY. The whole job happens inside libavformat, which streams packets
+ * through its own IO layer — nothing is ever read into the JS heap. That is the
+ * constraint `webm-duration.ts` learned the hard way (a naive whole-file read
+ * crashed the main process on long recordings).
+ *
+ * DURABILITY. The remux writes to a temporary sibling and is renamed over the
+ * original only after it has been verified non-empty. A failure at any point
+ * leaves the original recording byte-for-byte intact — a recording must never
+ * be lost to a failed re-index.
+ */
+export async function reindexRecordingOnDisk(
+ filePath: string,
+ service: Pick<CompositorViewService, "remuxSeekable"> = new CompositorViewService(),
+): Promise<ReindexResult> {
+ // Linux-only by intent, not by capability: it is the only platform whose
+ // screen capture goes through MediaRecorder. Windows and macOS record via
+ // native helpers that write indexed files at the source, so rewriting their
+ // output would be pure cost.
+ if (process.platform !== "linux") {
+ return { reindexed: false, reason: "unsupported-platform" };
+ }
+
+ // Same directory as the recording, so the final rename is a same-filesystem
+ // operation and therefore atomic. A temp dir could sit on another mount,
+ // where rename() degrades to copy+unlink and stops being atomic.
+ const tmpPath = `${filePath}.reindex.tmp`;
+ try {
+ await fs.unlink(tmpPath).catch(() => undefined);
+
+ const stats = await service.remuxSeekable(filePath, tmpPath);
+ if (!stats) {
+ await fs.unlink(tmpPath).catch(() => undefined);
+ return { reindexed: false, reason: "no-addon" };
+ }
+
+ // Trust nothing: a muxer that errored late can still leave a short or
+ // empty file behind, and renaming that over the recording would destroy
+ // it. Size is the cheap check that catches the whole class.
+ let tmpSize = 0;
+ try {
+ tmpSize = (await fs.stat(tmpPath)).size;
+ } catch {
+ return { reindexed: false, reason: "empty-output" };
+ }
+ if (tmpSize === 0) {
+ await fs.unlink(tmpPath).catch(() => undefined);
+ return { reindexed: false, reason: "empty-output" };
+ }
+
+ await fs.rename(tmpPath, filePath);
+ return {
+ reindexed: true,
+ packets: stats.packets,
+ streams: stats.streams,
+ wallS: stats.wallS,
+ };
+ } catch (error) {
+ console.warn(`[webm-seek-index] failed to re-index ${filePath}:`, error);
+ await fs.unlink(tmpPath).catch(() => undefined);
+ return { reindexed: false, reason: "remux-failed" };
+ }
+}