Skip to content

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

feat(poc-d3d): speed regions and the native audio pipeline

Etienne Lescot9fbe4916ea04
diff --git a/poc-d3d/build.rs b/poc-d3d/build.rs
index 45d950949..dd3465796 100644
--- a/poc-d3d/build.rs
+++ b/poc-d3d/build.rs
@@ -28,7 +28,9 @@ fn main() {
.allowlist_function("avcodec_.*")
.allowlist_function("avformat_.*")
.allowlist_function("avio_.*")
+ .allowlist_function("swr_.*")
.allowlist_type("AV.*")
+ .allowlist_type("SwrContext")
.allowlist_var("AV_.*")
.allowlist_var("AVERROR.*")
.allowlist_var("FF_.*")
diff --git a/poc-d3d/compositor-view-napi/src/lib.rs b/poc-d3d/compositor-view-napi/src/lib.rs
index ac72332c9..765a6f57b 100644
--- a/poc-d3d/compositor-view-napi/src/lib.rs
+++ b/poc-d3d/compositor-view-napi/src/lib.rs
@@ -242,6 +242,8 @@ pub struct ClipInput {
pub source_end_sec: f64,
/// Décalage caméra (s) : temps source webcam = temps source screen - offset.
pub webcam_offset_sec: f64,
+ /// `false` évite une ouverture ffmpeg vouée à échouer et réserve du silence à ce clip.
+ pub has_audio: bool,
}
/// Taille/cadence/codec de sortie voulus par l'app (modale d'export). Tous optionnels :
@@ -357,6 +359,7 @@ pub fn export_multi(
source_start_sec: c.source_start_sec,
source_end_sec: c.source_end_sec,
webcam_offset_sec: c.webcam_offset_sec,
+ has_audio: c.has_audio,
})
.collect();
AsyncTask::new(ExportMultiTask { out_path, clips, scene_json, params })
diff --git a/poc-d3d/src/audio.rs b/poc-d3d/src/audio.rs
new file mode 100644
index 000000000..9a58bedc8
--- /dev/null
+++ b/poc-d3d/src/audio.rs
@@ -0,0 +1,877 @@
+//! Piste audio native de l'export multiclip : ffmpeg décode les sources écran, swresample
+//! normalise tout en f32 planaire 48 kHz stéréo, WSOLA applique les speed regions, puis un
+//! unique encodeur AAC alimente le même muxer que la vidéo.
+
+use crate::ffi::*;
+use crate::regions::SpeedSegment;
+use anyhow::{bail, Result};
+use std::f32::consts::PI;
+use std::ffi::CString;
+use std::ptr;
+
+pub const AUDIO_OUTPUT_SAMPLE_RATE: i32 = 48_000;
+pub const AUDIO_OUTPUT_CHANNELS: usize = 2;
+pub const AUDIO_BITRATE: i64 = 128_000;
+pub const AUDIO_BOUNDARY_FADE_SAMPLES: usize = 240;
+
+const AVERROR_EAGAIN: i32 = -11;
+const AVERROR_EOF: i32 = -541478725;
+const AVSEEK_FLAG_BACKWARD: i32 = 1;
+const DEFAULT_FRAME_SEC: f64 = 0.04;
+const MIN_FRAME_SEC: f64 = 0.005;
+const DEFAULT_SEARCH_SEC: f64 = 0.01;
+const TARGET_GRAINS: usize = 8;
+const PASSTHROUGH_EPSILON: f64 = 1e-3;
+
+pub type PlanarPcm = Vec<Vec<f32>>;
+
+extern "C" {
+ fn sn_fmt_stream(s: *mut AVFormatContext, i: i32) -> *mut AVStream;
+}
+
+fn averr(ret: i32, ctx: &str) -> Result<()> {
+ if ret < 0 {
+ let mut buf = [0i8; 256];
+ unsafe { av_strerror(ret, buf.as_mut_ptr(), buf.len()) };
+ let msg = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) }.to_string_lossy();
+ bail!("{ctx}: {ret} ({msg})");
+ }
+ Ok(())
+}
+
+struct AudioResampler {
+ ctx: *mut SwrContext,
+ input_rate: i32,
+}
+
+impl AudioResampler {
+ unsafe fn from_frame(frame: *mut AVFrame, dctx: *mut AVCodecContext) -> Result<Self> {
+ let mut output_layout = AVChannelLayout::default();
+ av_channel_layout_default(&mut output_layout, AUDIO_OUTPUT_CHANNELS as i32);
+
+ let mut fallback_layout = AVChannelLayout::default();
+ let input_layout = if (*frame).ch_layout.nb_channels > 0 {
+ &(*frame).ch_layout as *const AVChannelLayout
+ } else if (*dctx).ch_layout.nb_channels > 0 {
+ &(*dctx).ch_layout as *const AVChannelLayout
+ } else {
+ av_channel_layout_default(&mut fallback_layout, 1);
+ &fallback_layout as *const AVChannelLayout
+ };
+ let input_rate = if (*frame).sample_rate > 0 {
+ (*frame).sample_rate
+ } else {
+ (*dctx).sample_rate
+ };
+ if input_rate <= 0 {
+ av_channel_layout_uninit(&mut output_layout);
+ av_channel_layout_uninit(&mut fallback_layout);
+ bail!("fréquence audio source invalide");
+ }
+
+ let mut ctx: *mut SwrContext = ptr::null_mut();
+ let ret = swr_alloc_set_opts2(
+ &mut ctx,
+ &output_layout,
+ AVSampleFormat::AV_SAMPLE_FMT_FLTP,
+ AUDIO_OUTPUT_SAMPLE_RATE,
+ input_layout,
+ (*frame).format as AVSampleFormat::Type,
+ input_rate,
+ 0,
+ ptr::null_mut(),
+ );
+ av_channel_layout_uninit(&mut output_layout);
+ av_channel_layout_uninit(&mut fallback_layout);
+ averr(ret, "swr_alloc_set_opts2")?;
+ if ctx.is_null() {
+ bail!("swr_alloc_set_opts2: contexte nul");
+ }
+ averr(swr_init(ctx), "swr_init")?;
+ Ok(Self { ctx, input_rate })
+ }
+
+ unsafe fn push(&mut self, frame: *mut AVFrame, output: &mut PlanarPcm) -> Result<()> {
+ let out_capacity = swr_get_out_samples(self.ctx, (*frame).nb_samples).max(1) as usize;
+ let mut planes = vec![vec![0.0f32; out_capacity]; AUDIO_OUTPUT_CHANNELS];
+ let mut output_ptrs: Vec<*mut u8> = planes
+ .iter_mut()
+ .map(|plane| plane.as_mut_ptr() as *mut u8)
+ .collect();
+ let input_ptrs = (*frame).extended_data as *const *const u8;
+ let converted = swr_convert(
+ self.ctx,
+ output_ptrs.as_mut_ptr(),
+ out_capacity as i32,
+ input_ptrs,
+ (*frame).nb_samples,
+ );
+ averr(converted, "swr_convert")?;
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ planes[channel].truncate(converted as usize);
+ output[channel].extend_from_slice(&planes[channel]);
+ }
+ Ok(())
+ }
+
+ unsafe fn flush(&mut self, output: &mut PlanarPcm) -> Result<()> {
+ loop {
+ let delay = swr_get_delay(self.ctx, self.input_rate as i64);
+ if delay <= 0 {
+ break;
+ }
+ let out_capacity = (((delay * AUDIO_OUTPUT_SAMPLE_RATE as i64)
+ + self.input_rate as i64 - 1)
+ / self.input_rate as i64
+ + 32) as usize;
+ let mut planes = vec![vec![0.0f32; out_capacity]; AUDIO_OUTPUT_CHANNELS];
+ let mut output_ptrs: Vec<*mut u8> = planes
+ .iter_mut()
+ .map(|plane| plane.as_mut_ptr() as *mut u8)
+ .collect();
+ let converted = swr_convert(
+ self.ctx,
+ output_ptrs.as_mut_ptr(),
+ out_capacity as i32,
+ ptr::null(),
+ 0,
+ );
+ averr(converted, "swr_convert(flush)")?;
+ if converted == 0 {
+ break;
+ }
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ planes[channel].truncate(converted as usize);
+ output[channel].extend_from_slice(&planes[channel]);
+ }
+ }
+ Ok(())
+ }
+}
+
+impl Drop for AudioResampler {
+ fn drop(&mut self) {
+ unsafe { swr_free(&mut self.ctx) };
+ }
+}
+
+/// Décode uniquement la fenêtre source conservée. Le seek audio retombe sur une trame
+/// antérieure ; l'origine pts du premier bloc resamplé permet ensuite de couper précisément la
+/// prélecture sans supposer que la piste commence à t=0.
+pub fn decode_clip_audio(path: &str, source_start_sec: f64, source_end_sec: f64) -> Result<Option<PlanarPcm>> {
+ unsafe { decode_clip_audio_inner(path, source_start_sec, source_end_sec) }
+}
+
+unsafe fn decode_clip_audio_inner(
+ path: &str,
+ source_start_sec: f64,
+ source_end_sec: f64,
+) -> Result<Option<PlanarPcm>> {
+ let mut fmt: *mut AVFormatContext = ptr::null_mut();
+ let cpath = CString::new(path)?;
+ averr(
+ avformat_open_input(&mut fmt, cpath.as_ptr(), ptr::null_mut(), ptr::null_mut()),
+ "audio open_input",
+ )?;
+ averr(avformat_find_stream_info(fmt, ptr::null_mut()), "audio find_stream_info")?;
+ let audio_index = av_find_best_stream(
+ fmt,
+ AVMediaType::AVMEDIA_TYPE_AUDIO,
+ -1,
+ -1,
+ ptr::null_mut(),
+ 0,
+ );
+ if audio_index < 0 {
+ avformat_close_input(&mut fmt);
+ return Ok(None);
+ }
+
+ let stream = sn_fmt_stream(fmt, audio_index);
+ let codecpar = (*stream).codecpar;
+ let decoder = avcodec_find_decoder((*codecpar).codec_id);
+ if decoder.is_null() {
+ avformat_close_input(&mut fmt);
+ return Ok(None);
+ }
+ let mut dctx = avcodec_alloc_context3(decoder);
+ if dctx.is_null() {
+ avformat_close_input(&mut fmt);
+ bail!("audio avcodec_alloc_context3");
+ }
+ averr(avcodec_parameters_to_context(dctx, codecpar), "audio params_to_ctx")?;
+ averr(avcodec_open2(dctx, decoder, ptr::null_mut()), "audio avcodec_open2")?;
+
+ let time_base = (*stream).time_base;
+ let tb_sec = if time_base.den != 0 {
+ time_base.num as f64 / time_base.den as f64
+ } else {
+ 0.0
+ };
+ if tb_sec > 0.0 {
+ let target = (source_start_sec / tb_sec).floor() as i64;
+ if av_seek_frame(fmt, audio_index, target, AVSEEK_FLAG_BACKWARD) >= 0 {
+ avcodec_flush_buffers(dctx);
+ }
+ }
+
+ let mut packet = av_packet_alloc();
+ let mut frame = av_frame_alloc();
+ let mut resampler: Option<AudioResampler> = None;
+ let mut decoded = vec![Vec::<f32>::new(); AUDIO_OUTPUT_CHANNELS];
+ let mut decoded_origin_sec: Option<f64> = None;
+ let mut input_eof = false;
+ let mut decoder_eof = false;
+ let mut reached_end = false;
+
+ while !reached_end && !decoder_eof {
+ if !input_eof {
+ let read = av_read_frame(fmt, packet);
+ if read == AVERROR_EOF {
+ avcodec_send_packet(dctx, ptr::null());
+ input_eof = true;
+ } else {
+ averr(read, "audio av_read_frame")?;
+ if (*packet).stream_index == audio_index {
+ averr(avcodec_send_packet(dctx, packet), "audio send_packet")?;
+ }
+ av_packet_unref(packet);
+ }
+ }
+
+ loop {
+ let ret = avcodec_receive_frame(dctx, frame);
+ if ret == AVERROR_EOF {
+ decoder_eof = true;
+ break;
+ }
+ if ret == AVERROR_EAGAIN {
+ if input_eof {
+ decoder_eof = true;
+ }
+ break;
+ }
+ averr(ret, "audio receive_frame")?;
+
+ let pts = (*frame).best_effort_timestamp;
+ let frame_sec = if pts != i64::MIN && tb_sec > 0.0 {
+ pts as f64 * tb_sec
+ } else {
+ decoded_origin_sec.unwrap_or(source_start_sec)
+ };
+ if frame_sec >= source_end_sec {
+ reached_end = true;
+ av_frame_unref(frame);
+ break;
+ }
+ if decoded_origin_sec.is_none() {
+ decoded_origin_sec = Some(frame_sec);
+ }
+ if resampler.is_none() {
+ resampler = Some(AudioResampler::from_frame(frame, dctx)?);
+ }
+ resampler.as_mut().unwrap().push(frame, &mut decoded)?;
+ av_frame_unref(frame);
+ }
+ }
+
+ if let Some(r) = resampler.as_mut() {
+ r.flush(&mut decoded)?;
+ }
+
+ av_frame_free(&mut frame);
+ av_packet_free(&mut packet);
+ avcodec_free_context(&mut dctx);
+ avformat_close_input(&mut fmt);
+
+ let target_samples = (((source_end_sec - source_start_sec).max(0.0)
+ * AUDIO_OUTPUT_SAMPLE_RATE as f64)
+ .round()) as usize;
+ let mut trimmed = vec![vec![0.0f32; target_samples]; AUDIO_OUTPUT_CHANNELS];
+ let origin_sec = decoded_origin_sec.unwrap_or(source_start_sec);
+ let relative_start = ((source_start_sec - origin_sec) * AUDIO_OUTPUT_SAMPLE_RATE as f64).round() as i64;
+ let (src_start, dst_start) = if relative_start >= 0 {
+ (relative_start as usize, 0usize)
+ } else {
+ (0usize, (-relative_start) as usize)
+ };
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ if src_start >= decoded[channel].len() || dst_start >= target_samples {
+ continue;
+ }
+ let count = (decoded[channel].len() - src_start).min(target_samples - dst_start);
+ trimmed[channel][dst_start..dst_start + count]
+ .copy_from_slice(&decoded[channel][src_start..src_start + count]);
+ }
+ Ok(Some(trimmed))
+}
+
+fn hann(length: usize) -> Vec<f32> {
+ let mut window = vec![0.0; length];
+ for (i, value) in window.iter_mut().enumerate() {
+ *value = 0.5 - 0.5 * ((2.0 * PI * i as f32) / (length - 1) as f32).cos();
+ }
+ window
+}
+
+/// Port direct du WSOLA web. Tous les canaux partagent les positions choisies sur un downmix
+/// mono, sinon deux recherches indépendantes déplaceraient l'image stéréo.
+pub struct WsolaTimeStretcher {
+ channels: usize,
+ passthrough: bool,
+ n: usize,
+ hs: usize,
+ ha: f64,
+ search_radius: i64,
+ window: Vec<f32>,
+ buf: PlanarPcm,
+ mono: Vec<f32>,
+ buf_start: i64,
+ out: PlanarPcm,
+ win_sum: Vec<f32>,
+ out_start: usize,
+ ideal_pos: f64,
+ grain_pos: i64,
+ frame: usize,
+ placed_any: bool,
+}
+
+impl WsolaTimeStretcher {
+ pub fn new(
+ sample_rate: i32,
+ channels: usize,
+ speed: f64,
+ expected_output_samples: usize,
+ ) -> Self {
+ let channels = channels.max(1);
+ let passthrough = (speed - 1.0).abs() < PASSTHROUGH_EPSILON;
+ let mut n = (sample_rate as f64 * DEFAULT_FRAME_SEC).round() as usize;
+ n = n.max(4);
+ if n % 2 != 0 {
+ n += 1;
+ }
+ let mut hs = n / 2;
+ if expected_output_samples > 0 {
+ let min_hs = 2usize.max(
+ ((sample_rate as f64 * MIN_FRAME_SEC) / 2.0).round() as usize,
+ );
+ let target_hs = expected_output_samples / TARGET_GRAINS;
+ hs = hs.min(min_hs.max(target_hs));
+ }
+ let n = hs * 2;
+ let search_radius = ((sample_rate as f64 * DEFAULT_SEARCH_SEC).round() as usize)
+ .min(hs) as i64;
+ Self {
+ channels,
+ passthrough,
+ n,
+ hs,
+ ha: hs as f64 * speed,
+ search_radius,
+ window: hann(n),
+ buf: vec![Vec::new(); channels],
+ mono: Vec::new(),
+ buf_start: 0,
+ out: vec![Vec::new(); channels],
+ win_sum: Vec::new(),
+ out_start: 0,
+ ideal_pos: 0.0,
+ grain_pos: 0,
+ frame: 0,
+ placed_any: false,
+ }
+ }
+
+ pub fn push(&mut self, planar: &[Vec<f32>]) -> PlanarPcm {
+ if self.passthrough {
+ return (0..self.channels)
+ .map(|channel| {
+ planar
+ .get(channel)
+ .or_else(|| planar.first())
+ .cloned()
+ .unwrap_or_default()
+ })
+ .collect();
+ }
+ self.append(planar);
+ self.process(false)
+ }
+
+ pub fn flush(&mut self) -> PlanarPcm {
+ if self.passthrough {
+ return self.empty_chunk();
+ }
+ self.process(true)
+ }
+
+ fn empty_chunk(&self) -> PlanarPcm {
+ vec![Vec::new(); self.channels]
+ }
+
+ fn append(&mut self, planar: &[Vec<f32>]) {
+ let add_len = planar.first().map(|p| p.len()).unwrap_or(0);
+ if add_len == 0 {
+ return;
+ }
+ for channel in 0..self.channels {
+ if let Some(source) = planar.get(channel).or_else(|| planar.first()) {
+ self.buf[channel].extend_from_slice(&source[..add_len.min(source.len())]);
+ if source.len() < add_len {
+ let target_len = self.buf[channel].len() + add_len - source.len();
+ self.buf[channel].resize(target_len, 0.0);
+ }
+ }
+ }
+ for i in 0..add_len {
+ let mut sum = 0.0f32;
+ for channel in 0..self.channels {
+ sum += planar
+ .get(channel)
+ .and_then(|p| p.get(i))
+ .or_else(|| planar.first().and_then(|p| p.get(i)))
+ .copied()
+ .unwrap_or(0.0);
+ }
+ self.mono.push(sum / self.channels as f32);
+ }
+ }
+
+ fn buf_end(&self) -> i64 {
+ self.buf_start + self.buf[0].len() as i64
+ }
+
+ fn sample_at(&self, channel: usize, absolute_index: i64) -> f32 {
+ let index = absolute_index - self.buf_start;
+ if index < 0 {
+ 0.0
+ } else {
+ self.buf[channel].get(index as usize).copied().unwrap_or(0.0)
+ }
+ }
+
+ fn mono_at(&self, absolute_index: i64) -> f32 {
+ let index = absolute_index - self.buf_start;
+ if index < 0 {
+ 0.0
+ } else {
+ self.mono.get(index as usize).copied().unwrap_or(0.0)
+ }
+ }
+
+ fn process(&mut self, final_chunk: bool) -> PlanarPcm {
+ let mut emitted = self.empty_chunk();
+ loop {
+ let search_target = (self.ideal_pos + self.ha).round() as i64;
+ let required_end = (self.grain_pos + self.n as i64)
+ .max(self.grain_pos + self.hs as i64 + self.n as i64)
+ .max(search_target + self.search_radius + self.n as i64);
+ if !final_chunk && self.buf_end() < required_end {
+ break;
+ }
+ if self.grain_pos + self.n as i64 > self.buf_end() {
+ break;
+ }
+
+ self.place_grain(self.grain_pos);
+ let placed_frame = self.frame;
+ let reference_start = self.grain_pos + self.hs as i64;
+ let best_delta = self.find_best_delta(reference_start, search_target);
+ self.grain_pos = search_target + best_delta;
+ self.ideal_pos += self.ha;
+ self.frame += 1;
+
+ self.collect(placed_frame * self.hs, &mut emitted);
+ self.discard_below(self.grain_pos);
+ }
+ if final_chunk {
+ self.collect_all(&mut emitted);
+ }
+ emitted
+ }
+
+ fn place_grain(&mut self, position: i64) {
+ let output_absolute = self.frame * self.hs;
+ self.ensure_out(output_absolute + self.n);
+ let base = output_absolute - self.out_start;
+ for channel in 0..self.channels {
+ for k in 0..self.n {
+ let sample = self.sample_at(channel, position + k as i64);
+ self.out[channel][base + k] += sample * self.window[k];
+ }
+ }
+ for k in 0..self.n {
+ self.win_sum[base + k] += self.window[k];
+ }
+ self.placed_any = true;
+ }
+
+ fn find_best_delta(&self, reference_start: i64, target: i64) -> i64 {
+ if reference_start + self.n as i64 > self.buf_end() {
+ return 0;
+ }
+ let mut reference_energy = 0.0f32;
+ for k in 0..self.n {
+ let sample = self.mono_at(reference_start + k as i64);
+ reference_energy += sample * sample;
+ }
+ if reference_energy == 0.0 {
+ return 0;
+ }
+
+ let mut best_delta = 0;
+ let mut best_score = f32::NEG_INFINITY;
+ let low = (-self.search_radius).max(self.buf_start - target);
+ let high = self
+ .search_radius
+ .min(self.buf_end() - self.n as i64 - target);
+ for delta in low..=high {
+ let candidate_start = target + delta;
+ let mut dot = 0.0f32;
+ let mut energy = 0.0f32;
+ for k in 0..self.n {
+ let candidate = self.mono_at(candidate_start + k as i64);
+ dot += candidate * self.mono_at(reference_start + k as i64);
+ energy += candidate * candidate;
+ }
+ let score = if energy > 0.0 { dot / energy.sqrt() } else { 0.0 };
+ if score > best_score {
+ best_score = score;
+ best_delta = delta;
+ }
+ }
+ best_delta
+ }
+
+ fn ensure_out(&mut self, absolute_end: usize) {
+ let needed = absolute_end - self.out_start;
+ if needed <= self.out[0].len() {
+ return;
+ }
+ let next_len = needed.max(self.out[0].len() * 2).max(self.n * 4);
+ for channel in 0..self.channels {
+ self.out[channel].resize(next_len, 0.0);
+ }
+ self.win_sum.resize(next_len, 0.0);
+ }
+
+ fn collect(&mut self, absolute_end: usize, emitted: &mut PlanarPcm) {
+ let count = absolute_end.saturating_sub(self.out_start);
+ if count == 0 {
+ return;
+ }
+ for channel in 0..self.channels {
+ for i in 0..count {
+ let weight = self.win_sum[i];
+ let mut sample = self.out[channel][i];
+ if weight > 1e-6 {
+ sample /= weight;
+ }
+ emitted[channel].push(sample);
+ }
+ self.out[channel] = self.out[channel][count..].to_vec();
+ }
+ self.win_sum = self.win_sum[count..].to_vec();
+ self.out_start = absolute_end;
+ }
+
+ fn collect_all(&mut self, emitted: &mut PlanarPcm) {
+ if !self.placed_any {
+ return;
+ }
+ let end = (self.frame - 1) * self.hs + self.n;
+ self.collect(end, emitted);
+ }
+
+ fn discard_below(&mut self, absolute_index: i64) {
+ let drop_count = absolute_index - self.buf_start;
+ if drop_count <= 0 {
+ return;
+ }
+ let drop_count = drop_count as usize;
+ for channel in 0..self.channels {
+ self.buf[channel] = self.buf[channel][drop_count.min(self.buf[channel].len())..].to_vec();
+ }
+ self.mono = self.mono[drop_count.min(self.mono.len())..].to_vec();
+ self.buf_start = absolute_index;
+ }
+}
+
+fn stretch_pcm_to_length(pcm: &[Vec<f32>], target_samples: usize) -> PlanarPcm {
+ if target_samples == 0 {
+ return vec![Vec::new(); AUDIO_OUTPUT_CHANNELS];
+ }
+ let source_samples = pcm.first().map(|channel| channel.len()).unwrap_or(0);
+ if source_samples == 0 {
+ return vec![vec![0.0; target_samples]; AUDIO_OUTPUT_CHANNELS];
+ }
+ if source_samples.abs_diff(target_samples) <= 1 {
+ let mut exact = vec![vec![0.0; target_samples]; AUDIO_OUTPUT_CHANNELS];
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ if let Some(source) = pcm.get(channel) {
+ let count = source.len().min(target_samples);
+ exact[channel][..count].copy_from_slice(&source[..count]);
+ }
+ }
+ return exact;
+ }
+
+ let speed = source_samples as f64 / target_samples as f64;
+ let mut stretcher = WsolaTimeStretcher::new(
+ AUDIO_OUTPUT_SAMPLE_RATE,
+ AUDIO_OUTPUT_CHANNELS,
+ speed,
+ target_samples,
+ );
+ let chunks = [stretcher.push(pcm), stretcher.flush()];
+ let mut exact = vec![vec![0.0; target_samples]; AUDIO_OUTPUT_CHANNELS];
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ let mut written = 0usize;
+ for chunk in &chunks {
+ let source = &chunk[channel];
+ let count = source.len().min(target_samples - written);
+ if count > 0 {
+ exact[channel][written..written + count].copy_from_slice(&source[..count]);
+ written += count;
+ }
+ if written == target_samples {
+ break;
+ }
+ }
+ }
+ exact
+}
+
+/// Découpe le PCM gardé avec les mêmes spans et la même quantification frame que la vidéo.
+pub fn stretch_clip_pcm_by_speed(
+ pcm: &[Vec<f32>],
+ speed_segments: &[SpeedSegment],
+ output_fps: f64,
+) -> PlanarPcm {
+ let total_source_samples = pcm.first().map(|channel| channel.len()).unwrap_or(0);
+ let mut source_cursor = 0usize;
+ let mut chunks: Vec<PlanarPcm> = Vec::with_capacity(speed_segments.len());
+ for segment in speed_segments {
+ let input_samples = ((segment.end_sec - segment.start_sec)
+ * AUDIO_OUTPUT_SAMPLE_RATE as f64)
+ .round()
+ .max(0.0) as usize;
+ let input_start = source_cursor;
+ let input_end = (input_start + input_samples).min(total_source_samples);
+ source_cursor = input_start + input_samples;
+ let output_samples = ((segment.frame_count as f64 / output_fps)
+ * AUDIO_OUTPUT_SAMPLE_RATE as f64)
+ .round()
+ .max(0.0) as usize;
+ if input_end <= input_start {
+ chunks.push(vec![vec![0.0; output_samples]; AUDIO_OUTPUT_CHANNELS]);
+ continue;
+ }
+ let slice: PlanarPcm = (0..AUDIO_OUTPUT_CHANNELS)
+ .map(|channel| pcm[channel][input_start..input_end].to_vec())
+ .collect();
+ chunks.push(stretch_pcm_to_length(&slice, output_samples));
+ }
+
+ let mut output = vec![Vec::new(); AUDIO_OUTPUT_CHANNELS];
+ for chunk in chunks {
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ output[channel].extend_from_slice(&chunk[channel]);
+ }
+ }
+ output
+}
+
+#[derive(Clone, Copy)]
+pub struct AudioConcatSegmentPlan {
+ pub start_sample: usize,
+ pub sample_count: usize,
+ pub silence: bool,
+}
+
+pub struct AudioConcatPlan {
+ pub total_samples: usize,
+ pub segments: Vec<AudioConcatSegmentPlan>,
+}
+
+/// Les offsets sont la somme ENTIÈRE des longueurs arrondies clip par clip ; recalculer depuis
+/// une durée cumulée ferait dériver les jonctions sur une longue timeline.
+pub fn build_audio_concat_plan(
+ output_frame_counts: &[u64],
+ has_audio: &[bool],
+ output_fps: f64,
+) -> AudioConcatPlan {
+ let mut cursor = 0usize;
+ let mut segments = Vec::with_capacity(output_frame_counts.len());
+ for (index, &frame_count) in output_frame_counts.iter().enumerate() {
+ let sample_count = if output_fps > 0.0 {
+ ((frame_count as f64 / output_fps) * AUDIO_OUTPUT_SAMPLE_RATE as f64)
+ .round()
+ .max(0.0) as usize
+ } else {
+ 0
+ };
+ segments.push(AudioConcatSegmentPlan {
+ start_sample: cursor,
+ sample_count,
+ silence: !has_audio.get(index).copied().unwrap_or(false),
+ });
+ cursor += sample_count;
+ }
+ AudioConcatPlan { total_samples: cursor, segments }
+}
+
+pub fn assemble_concatenated_pcm(
+ clip_pcm: &[Option<PlanarPcm>],
+ plan: &AudioConcatPlan,
+) -> PlanarPcm {
+ let mut output = vec![vec![0.0f32; plan.total_samples]; AUDIO_OUTPUT_CHANNELS];
+ for (index, segment) in plan.segments.iter().enumerate() {
+ if segment.sample_count == 0 || segment.silence {
+ continue;
+ }
+ let Some(Some(pcm)) = clip_pcm.get(index) else {
+ continue;
+ };
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ let Some(source) = pcm.get(channel) else {
+ continue;
+ };
+ let count = segment.sample_count.min(source.len());
+ output[channel][segment.start_sample..segment.start_sample + count]
+ .copy_from_slice(&source[..count]);
+ }
+ }
+
+ for boundary in plan.segments.windows(2) {
+ let current = boundary[0];
+ let next = boundary[1];
+ let fade = AUDIO_BOUNDARY_FADE_SAMPLES
+ .min(current.sample_count / 2)
+ .min(next.sample_count / 2);
+ if fade == 0 {
+ continue;
+ }
+ let tail_start = current.start_sample + current.sample_count - fade;
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ for k in 0..fade {
+ let phase = (k as f32 / fade as f32) * PI * 0.5;
+ output[channel][tail_start + k] *= phase.cos();
+ output[channel][next.start_sample + k] *= phase.sin();
+ }
+ }
+ }
+ output
+}
+
+/// Encodeur AAC attaché au muxer avant son header. Les paquets utilisent le même interleaver
+/// que la vidéo ; les pts restent en unités échantillon jusqu'au rescale vers l'AVStream.
+pub(crate) struct AacEncoder {
+ context: *mut AVCodecContext,
+ stream: *mut AVStream,
+ packet: *mut AVPacket,
+}
+
+impl AacEncoder {
+ pub(crate) unsafe fn open(output: *mut AVFormatContext) -> Result<Self> {
+ let name = CString::new("aac")?;
+ let codec = avcodec_find_encoder_by_name(name.as_ptr());
+ if codec.is_null() {
+ bail!("encodeur aac introuvable");
+ }
+ let context = avcodec_alloc_context3(codec);
+ if context.is_null() {
+ bail!("aac avcodec_alloc_context3");
+ }
+ (*context).sample_fmt = AVSampleFormat::AV_SAMPLE_FMT_FLTP;
+ (*context).sample_rate = AUDIO_OUTPUT_SAMPLE_RATE;
+ (*context).bit_rate = AUDIO_BITRATE;
+ (*context).time_base = AVRational { num: 1, den: AUDIO_OUTPUT_SAMPLE_RATE };
+ av_channel_layout_default(&mut (*context).ch_layout, AUDIO_OUTPUT_CHANNELS as i32);
+ averr(avcodec_open2(context, codec, ptr::null_mut()), "aac avcodec_open2")?;
+
+ let stream = avformat_new_stream(output, ptr::null());
+ if stream.is_null() {
+ bail!("aac avformat_new_stream");
+ }
+ averr(
+ avcodec_parameters_from_context((*stream).codecpar, context),
+ "aac parameters_from_context",
+ )?;
+ (*stream).time_base = (*context).time_base;
+ let packet = av_packet_alloc();
+ if packet.is_null() {
+ bail!("aac av_packet_alloc");
+ }
+ Ok(Self { context, stream, packet })
+ }
+
+ pub(crate) unsafe fn encode(&mut self, pcm: &[Vec<f32>], output: *mut AVFormatContext) -> Result<()> {
+ let total_samples = pcm.first().map(|channel| channel.len()).unwrap_or(0);
+ let frame_size = if (*self.context).frame_size > 0 {
+ (*self.context).frame_size as usize
+ } else {
+ 1024
+ };
+ let mut offset = 0usize;
+ while offset < total_samples {
+ let sample_count = frame_size.min(total_samples - offset);
+ let mut frame = av_frame_alloc();
+ if frame.is_null() {
+ bail!("aac av_frame_alloc");
+ }
+ (*frame).format = (*self.context).sample_fmt as i32;
+ (*frame).sample_rate = AUDIO_OUTPUT_SAMPLE_RATE;
+ (*frame).nb_samples = sample_count as i32;
+ averr(
+ av_channel_layout_copy(&mut (*frame).ch_layout, &(*self.context).ch_layout),
+ "aac channel_layout_copy",
+ )?;
+ averr(av_frame_get_buffer(frame, 0), "aac frame_get_buffer")?;
+ averr(av_frame_make_writable(frame), "aac frame_make_writable")?;
+ for channel in 0..AUDIO_OUTPUT_CHANNELS {
+ let destination = *(*frame).extended_data.add(channel) as *mut f32;
+ ptr::write_bytes(destination, 0, sample_count);
+ if let Some(source) = pcm.get(channel) {
+ let available = source.len().saturating_sub(offset).min(sample_count);
+ if available > 0 {
+ ptr::copy_nonoverlapping(source.as_ptr().add(offset), destination, available);
+ }
+ }
+ }
+ (*frame).pts = offset as i64;
+ averr(avcodec_send_frame(self.context, frame), "aac send_frame")?;
+ self.drain(output)?;
+ av_frame_free(&mut frame);
+ offset += sample_count;
+ }
+ averr(avcodec_send_frame(self.context, ptr::null()), "aac flush")?;
+ self.drain(output)
+ }
+
+ unsafe fn drain(&mut self, output: *mut AVFormatContext) -> Result<()> {
+ loop {
+ let ret = avcodec_receive_packet(self.context, self.packet);
+ if ret == AVERROR_EAGAIN || ret == AVERROR_EOF {
+ return Ok(());
+ }
+ averr(ret, "aac receive_packet")?;
+ (*self.packet).stream_index = (*self.stream).index;
+ av_packet_rescale_ts(self.packet, (*self.context).time_base, (*self.stream).time_base);
+ averr(
+ av_interleaved_write_frame(output, self.packet),
+ "aac interleaved_write_frame",
+ )?;
+ av_packet_unref(self.packet);
+ }
+ }
+}
+
+impl Drop for AacEncoder {
+ fn drop(&mut self) {
+ unsafe {
+ av_packet_free(&mut self.packet);
+ avcodec_free_context(&mut self.context);
+ }
+ }
+}
diff --git a/poc-d3d/src/lib.rs b/poc-d3d/src/lib.rs
index 17ff5d10f..256873eb6 100644
--- a/poc-d3d/src/lib.rs
+++ b/poc-d3d/src/lib.rs
@@ -3,6 +3,7 @@
//! Electron. Le binaire (`main.rs`) n'est qu'un mince consommateur (`run()`).
pub mod app;
+pub mod audio;
pub mod compositor;
pub mod config;
pub mod cursor;
diff --git a/poc-d3d/src/pipeline.rs b/poc-d3d/src/pipeline.rs
index 4be340c3d..f8b2f2d0c 100644
--- a/poc-d3d/src/pipeline.rs
+++ b/poc-d3d/src/pipeline.rs
@@ -2,11 +2,16 @@
//! Aucun composite. Mesuré au plus extérieur (§10) : Instant (mappe QPC) autour de
//! tout le run, deux lectures seulement. Rien dans la boucle ne peut fausser le fps.
+use crate::audio::{
+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio,
+ stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,
+};
use crate::compositor::{Compositor, OUT_H, OUT_W};
use crate::config::Cfg;
use crate::cursor::CursorTrack;
use crate::d3d::Gpu;
use crate::ffi::*;
+use crate::regions::speed_segments_for_window;
use anyhow::{anyhow, bail, Result};
use std::collections::HashMap;
use std::ffi::{c_void, CString};
@@ -530,6 +535,27 @@ impl Drop for Decoder {
}
}
+/// Avance un décodeur jusqu'au premier pts dans le référentiel écran qui atteint la cible.
+/// `timeline_offset_sec` remet les pts webcam dans ce référentiel (`webcam + offset = screen`) :
+/// chaque source garde ainsi sa cadence propre au lieu d'être consommée 1:1 avec l'autre.
+unsafe fn advance_decoder_to(
+ decoder: &mut Decoder,
+ target_source_time: f64,
+ timeline_offset_sec: f64,
+) -> Result<bool> {
+ loop {
+ if decoder.cur_frame().is_null() {
+ return Ok(false);
+ }
+ if decoder.cur_time_sec() + timeline_offset_sec >= target_source_time {
+ return Ok(true);
+ }
+ if decoder.next()?.is_null() {
+ return Ok(false);
+ }
+ }
+}
+
/// Frames-context de l'encodeur : NV12 sur notre device, bind RENDER_TARGET (§5) pour
/// que le compositeur rende directement dans les surfaces de l'encodeur.
unsafe fn make_enc_frames(gpu: &Gpu, w: i32, h: i32) -> Result<(*mut AVBufferRef, *mut AVBufferRef)> {
@@ -672,6 +698,7 @@ pub struct ClipSource {
pub source_start_sec: f64,
pub source_end_sec: f64,
pub webcam_offset_sec: f64,
+ pub has_audio: bool,
}
/// Export **multiclip** : rend la timeline (clips ordonnés, avec trims) en un seul MP4.
@@ -787,8 +814,14 @@ unsafe fn run_multi_inner(
"alloc_output_context2",
)?;
let ostream = avformat_new_stream(octx, ptr::null());
+ if ostream.is_null() {
+ bail!("video avformat_new_stream");
+ }
averr(avcodec_parameters_from_context((*ostream).codecpar, ectx), "params_from_ctx")?;
(*ostream).time_base = (*ectx).time_base;
+ // Les deux streams doivent exister avant le header MP4 ; l'AAC reste ouvert pendant le
+ // rendu puis reçoit le PCM assemblé à partir des comptes de frames réellement produits.
+ let mut audio_encoder = AacEncoder::open(octx)?;
let mut pb: *mut AVIOContext = ptr::null_mut();
averr(avio_open(&mut pb, outc.as_ptr(), AVIO_FLAG_WRITE as i32), "avio_open")?;
sn_fmt_set_pb(octx, pb);
@@ -796,6 +829,9 @@ unsafe fn run_multi_inner(
let opkt = av_packet_alloc();
let mut frames: u64 = 0;
+ let mut clip_frame_counts = vec![0u64; clips.len()];
+ let mut clip_pcm: Vec<Option<PlanarPcm>> =
+ std::iter::repeat_with(|| None).take(clips.len()).collect();
let t0 = Instant::now();
for (clip_index, clip) in clips.iter().enumerate() {
@@ -849,15 +885,24 @@ unsafe fn run_multi_inner(
continue;
}
- if let Some(base_scene) = scene.as_ref() {
- comp.set_scene(Some(base_scene.for_clip_window(
- clip_index,
- clip.source_start_sec,
- source_end_sec,
- )));
+ let clip_scene = scene.as_ref().map(|base_scene| {
+ base_scene.for_clip_window(clip_index, clip.source_start_sec, source_end_sec)
+ });
+ let speed_segments = speed_segments_for_window(
+ clip_scene
+ .as_ref()
+ .map(|s| s.speed_regions.as_slice())
+ .unwrap_or(&[]),
+ clip.source_start_sec,
+ source_end_sec,
+ out_fps as f64,
+ );
+ if clip_scene.is_some() {
+ comp.set_scene(clip_scene);
}
- // un seul seek keyframe, puis décodage séquentiel jusqu'à source_end.
+ // un seul seek keyframe, puis chaque décodeur avance selon son propre pts jusqu'aux
+ // temps source demandés par les spans de vitesse.
if sdec.seek_to(clip.source_start_sec)?.is_null() {
continue; // clip vide / au-delà de la source
}
@@ -889,39 +934,64 @@ unsafe fn run_multi_inner(
}
}
- loop {
- let sf = sdec.cur_frame();
- let wf = wdec.cur_frame();
- if sf.is_null() || wf.is_null() {
- break;
- }
- let source_t = sdec.cur_time_sec();
- if source_t >= source_end_sec {
- break;
- }
- comp.set_timeline_time(Some(source_t as f32));
- if cursor_enabled && cursor_active_path.is_some() {
- comp.set_cursor_time(Some(source_t as f32));
- }
- comp.compose_frame(sf, wf, frames as f32, cfg)?;
-
- let outf = av_frame_alloc();
- averr(av_hwframe_get_buffer(enc_frames, outf, 0), "hwframe_get_buffer")?;
- let out_tex = (*outf).data[0] as *mut c_void;
- let out_slice = (*outf).data[1] as u32;
- comp.rgb_to_nv12_scaled(out_w, out_h, out_tex, out_slice)?;
- (*outf).pts = frames as i64;
- averr(avcodec_send_frame(ectx, outf), "send_frame")?;
- drain_encoder(ectx, octx, ostream, opkt)?;
- av_frame_free(&mut (outf as *mut _));
- frames += 1;
- progress(frames);
+ let frames_before_clip = frames;
+ 'clip_frames: for segment in &speed_segments {
+ for segment_frame in 0..segment.frame_count {
+ let target_source_time = segment.start_sec
+ + segment_frame as f64 * segment.speed / out_fps as f64;
+ if !advance_decoder_to(sdec, target_source_time, 0.0)? {
+ break 'clip_frames;
+ }
+ if !advance_decoder_to(
+ wdec,
+ target_source_time,
+ clip.webcam_offset_sec,
+ )? {
+ break 'clip_frames;
+ }
+ let sf = sdec.cur_frame();
+ let wf = wdec.cur_frame();
+ if sf.is_null() || wf.is_null() {
+ break 'clip_frames;
+ }
- if sdec.next()?.is_null() {
- break;
+ comp.set_timeline_time(Some(target_source_time as f32));
+ if cursor_enabled && cursor_active_path.is_some() {
+ comp.set_cursor_time(Some(target_source_time as f32));
+ }
+ comp.compose_frame(sf, wf, frames as f32, cfg)?;
+
+ let outf = av_frame_alloc();
+ averr(av_hwframe_get_buffer(enc_frames, outf, 0), "hwframe_get_buffer")?;
+ let out_tex = (*outf).data[0] as *mut c_void;
+ let out_slice = (*outf).data[1] as u32;
+ comp.rgb_to_nv12_scaled(out_w, out_h, out_tex, out_slice)?;
+ (*outf).pts = frames as i64;
+ averr(avcodec_send_frame(ectx, outf), "send_frame")?;
+ drain_encoder(ectx, octx, ostream, opkt)?;
+ av_frame_free(&mut (outf as *mut _));
+ frames += 1;
+ progress(frames);
}
- if wdec.next()?.is_null() {
- break;
+ }
+ clip_frame_counts[clip_index] = frames - frames_before_clip;
+ if clip.has_audio && clip_frame_counts[clip_index] > 0 {
+ match decode_clip_audio(&clip.screen, clip.source_start_sec, source_end_sec) {
+ Ok(Some(pcm)) => {
+ clip_pcm[clip_index] = Some(stretch_clip_pcm_by_speed(
+ &pcm,
+ &speed_segments,
+ out_fps as f64,
+ ));
+ }
+ Ok(None) => eprintln!(
+ "[pipeline] warning: clip #{} déclaré audio mais sans flux décodable; silence conservé",
+ clip_index,
+ ),
+ Err(error) => eprintln!(
+ "[pipeline] warning: décodage audio du clip #{} échoué ({error:#}); silence conservé",
+ clip_index,
+ ),
}
}
}
@@ -932,6 +1002,16 @@ unsafe fn run_multi_inner(
avcodec_send_frame(ectx, ptr::null_mut());
drain_encoder(ectx, octx, ostream, opkt)?;
+
+ let declared_audio: Vec<bool> = clips.iter().map(|clip| clip.has_audio).collect();
+ let audio_plan = build_audio_concat_plan(
+ &clip_frame_counts,
+ &declared_audio,
+ out_fps as f64,
+ );
+ let assembled_audio = assemble_concatenated_pcm(&clip_pcm, &audio_plan);
+ audio_encoder.encode(&assembled_audio, octx)?;
+
averr(av_write_trailer(octx), "write_trailer")?;
let wall_s = t0.elapsed().as_secs_f64();
@@ -963,7 +1043,7 @@ unsafe fn drain_encoder(
return Ok(());
}
averr(r, "receive_packet")?;
- (*opkt).stream_index = 0;
+ (*opkt).stream_index = (*ostream).index;
av_packet_rescale_ts(opkt, (*ectx).time_base, (*ostream).time_base);
averr(
av_interleaved_write_frame(octx, opkt),
diff --git a/poc-d3d/src/regions.rs b/poc-d3d/src/regions.rs
index c3131a83c..c719d3599 100644
--- a/poc-d3d/src/regions.rs
+++ b/poc-d3d/src/regions.rs
@@ -6,7 +6,82 @@
//! tilt perspective — ce module ne fait que le calcul temporel, pas le rendu GPU).
use crate::cursor::CursorTrack;
-use crate::scene::{SceneCameraFullscreenRegion, SceneZoomRegion};
+use crate::scene::{SceneCameraFullscreenRegion, SceneSpeedRegion, SceneZoomRegion};
+
+/// Quantification commune vidéo/audio : le web retranche exactement 1 ms avant `ceil`.
+pub const SPEED_FRAME_EPSILON_SEC: f64 = 0.001;
+const MIN_SPEED_SEGMENT_SEC: f64 = 0.0001;
+
+#[derive(Debug, Clone, Copy)]
+pub struct SpeedSegment {
+ pub start_sec: f64,
+ pub end_sec: f64,
+ pub speed: f64,
+ pub frame_count: u64,
+}
+
+/// Découpe toute la fenêtre gardée en spans contigus ; hors région la vitesse vaut 1×.
+/// Les régions sont ordonnées par début et, si un ancien payload en superpose, la première
+/// conserve la portion déjà couverte pour ne jamais émettre deux fois le même temps source.
+pub fn speed_segments_for_window(
+ regions: &[SceneSpeedRegion],
+ source_start_sec: f64,
+ source_end_sec: f64,
+ fps: f64,
+) -> Vec<SpeedSegment> {
+ if source_end_sec <= source_start_sec || !fps.is_finite() || fps <= 0.0 {
+ return Vec::new();
+ }
+ let mut overlapping: Vec<&SceneSpeedRegion> = regions
+ .iter()
+ .filter(|r| r.start_sec < source_end_sec && r.end_sec > source_start_sec)
+ .collect();
+ overlapping.sort_by(|a, b| {
+ a.start_sec
+ .partial_cmp(&b.start_sec)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+
+ let mut spans = Vec::new();
+ let mut cursor = source_start_sec;
+ for region in overlapping {
+ let start = region.start_sec.max(source_start_sec).max(cursor);
+ let end = region.end_sec.min(source_end_sec);
+ if start > cursor {
+ push_speed_segment(&mut spans, cursor, start, 1.0, fps);
+ }
+ if end > start {
+ let speed = if region.speed.is_finite() && region.speed > 0.0 {
+ region.speed
+ } else {
+ 1.0
+ };
+ push_speed_segment(&mut spans, start, end, speed, fps);
+ cursor = end;
+ }
+ }
+ if cursor < source_end_sec {
+ push_speed_segment(&mut spans, cursor, source_end_sec, 1.0, fps);
+ }
+ spans
+}
+
+fn push_speed_segment(
+ spans: &mut Vec<SpeedSegment>,
+ start_sec: f64,
+ end_sec: f64,
+ speed: f64,
+ fps: f64,
+) {
+ let duration = end_sec - start_sec;
+ if duration <= MIN_SPEED_SEGMENT_SEC {
+ return;
+ }
+ let frames = (((duration - SPEED_FRAME_EPSILON_SEC) / speed) * fps)
+ .ceil()
+ .max(0.0) as u64;
+ spans.push(SpeedSegment { start_sec, end_sec, speed, frame_count: frames });
+}
// mêmes fenêtres de transition que le web (TRANSITION_WINDOW_MS etc., converties en secondes).
const TRANSITION_WINDOW_S: f32 = 1.01505;
@@ -71,7 +146,8 @@ fn lerp(a: f32, b: f32, t: f32) -> f32 {
/// Port de `computeRegionStrength` (TS, `zoomRegionUtils.ts`) : 0 hors fenêtre, ease-in avant
/// `startSec` (le zoom anticipe légèrement), plein régime pendant la région, ease-out après
-/// `endSec`. `playbackRate` toujours 1 côté natif (pas de speed regions dans l'export natif).
+/// `endSec`. Les temps reçus sont les temps source échantillonnés par le pipeline, donc ces
+/// enveloppes restent alignées quand une speed region répète ou saute des frames.
fn zoom_region_strength(region: &SceneZoomRegion, t: f32) -> f32 {
let start = region.start_sec as f32;
let end = region.end_sec as f32;
diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rs
index c7983a8d3..1024aa611 100644
--- a/poc-d3d/src/scene.rs
+++ b/poc-d3d/src/scene.rs
@@ -16,6 +16,9 @@ pub struct SceneClip {
pub source_end_sec: f64,
/// temps source webcam = temps source screen − ceci.
pub webcam_offset_sec: f64,
+ /// Une source sans piste audio décodable garde sa durée via du silence natif.
+ #[serde(default)]
+ pub has_audio: bool,
}
#[derive(Debug, Clone, Copy, Deserialize)]
@@ -95,6 +98,18 @@ pub struct SceneZoomRegion {
pub rotation: Option<String>,
}
+/// Une zone de vitesse portée par le temps source d'un clip.
+#[derive(Debug, Clone, Copy, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneSpeedRegion {
+ /// Index du clip dont les temps source portent cette région (voir `SceneZoomRegion`).
+ #[serde(default)]
+ pub clip_index: Option<usize>,
+ pub start_sec: f64,
+ pub end_sec: f64,
+ pub speed: f64,
+}
+
/// Une zone "Full Camera" de la timeline (temps en secondes) : la webcam grandit pour couvrir
/// (presque) tout le cadre pendant cette fenêtre. Pas de champs au-delà des bornes temporelles
/// (miroir de `CameraFullscreenRegion`, TS).
@@ -157,6 +172,9 @@ pub struct Scene {
pub zoom_regions: Vec<SceneZoomRegion>,
/// `#[serde(default)]` : champ ajouté après coup, absent des JSON de test existants.
#[serde(default)]
+ pub speed_regions: Vec<SceneSpeedRegion>,
+ /// `#[serde(default)]` : champ ajouté après coup, absent des JSON de test existants.
+ #[serde(default)]
pub camera_fullscreen_regions: Vec<SceneCameraFullscreenRegion>,
pub cursor: SceneCursor,
/// Crop écran par clip, dans le même ordre que `clips` (`cropByClip` côté TS).
@@ -188,6 +206,9 @@ impl Scene {
scene.zoom_regions.retain(|region| {
belongs(region.clip_index, region.start_sec, region.end_sec)
});
+ scene.speed_regions.retain(|region| {
+ belongs(region.clip_index, region.start_sec, region.end_sec)
+ });
scene.camera_fullscreen_regions.retain(|region| {
belongs(region.clip_index, region.start_sec, region.end_sec)
});
@@ -202,11 +223,12 @@ mod tests {
#[test]
fn parses_a_minimal_scene_json() {
let json = r##"{
- "clips": [{"screenPath":"/s.mp4","webcamPath":"/w.mp4","sourceStartSec":0,"sourceEndSec":4,"webcamOffsetSec":0}],
+ "clips": [{"screenPath":"/s.mp4","webcamPath":"/w.mp4","sourceStartSec":0,"sourceEndSec":4,"webcamOffsetSec":0,"hasAudio":true}],
"layout": {"preset":"picture-in-picture","webcamSize":1.5,"webcamShape":"circle","webcamMirror":true,"webcamPosition":null,"webcamReactiveZoom":false},
"effects": {"padding":0.5,"blur":true,"shadow":0.8,"roundnessPx":24,"motionBlur":0.0},
"background": {"kind":"gradient","angleDeg":135,"stops":["#eaebed","#bcc0c6"]},
"zoomRegions": [{"clipIndex":0,"startSec":1.0,"endSec":3.0,"scale":2.0,"focusX":0.5,"focusY":0.3,"rotation":"iso"}],
+ "speedRegions": [{"clipIndex":0,"startSec":1.0,"endSec":2.0,"speed":2.0}],
"cursor": {"show":true,"size":1,"smoothing":0.5,"motionBlur":0.2,"clickBounce":1,"clipToBounds":false,"theme":"default"},
"cropByClip": [null],
"output": {"width":1920,"height":1080,"fps":null}
@@ -226,6 +248,8 @@ mod tests {
}
assert_eq!(scene.zoom_regions[0].scale, 2.0);
assert_eq!(scene.zoom_regions[0].clip_index, Some(0));
+ assert_eq!(scene.speed_regions[0].speed, 2.0);
+ assert!(scene.clips[0].has_audio);
assert_eq!(scene.crop_by_clip.len(), 1);
assert_eq!(scene.output.width, 1920);
}
diff --git a/poc-d3d/wrapper.h b/poc-d3d/wrapper.h
index e4ef2c8ca..88fb4be89 100644
--- a/poc-d3d/wrapper.h
+++ b/poc-d3d/wrapper.h
@@ -5,3 +5,4 @@
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
+#include <libswresample/swresample.h>
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 8fcea5894..e77af1fa0 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -73,6 +73,12 @@ function buildNativeClipList(document: AxcutDocument): CompositorClipInput[] {
// the single canonical precedence used by every consumer (clip.probe → asset.duration
// → timeline-length guess). See `resolveClipSourceEndSec` for the full order.
const sourceEndSec = resolveClipSourceEndSec(clip, asset);
+ // ponytail: matches the rule in `buildSceneDescription` — screen recordings
+ // from this app always carry a decodable audio track (the webcam path
+ // never does), so the only clips that reach this branch already have audio.
+ // If a per-asset audio-probe flag lands on the schema later, swap to
+ // `Boolean(asset.audio)` here too and keep these two derivation paths in
+ // lock-step with `buildSceneDescription` in src/native/sceneDescription.ts.
return [
{
screenPath: asset.originalPath,
@@ -80,6 +86,7 @@ function buildNativeClipList(document: AxcutDocument): CompositorClipInput[] {
sourceStartSec: clip.sourceStartSec,
sourceEndSec,
webcamOffsetSec: cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
+ hasAudio: true,
},
];
});
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 440fc27eb..4e0ecc603 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -121,6 +121,12 @@ export interface CompositorClipInput {
sourceEndSec: number;
/** temps source webcam = temps source screen − ceci. */
webcamOffsetSec: number;
+ /** `true` when this clip's screen asset has a decodable audio track the native
+ * compositor should mix into the export. `false` skips audio decode/encode/mux
+ * for this clip entirely (and the webcam path never carries audio by product
+ * convention). Populated by `buildSceneDescription` and `buildNativeClipList`;
+ * see the comment on the producer side for the exact rule. */
+ hasAudio: boolean;
}
/** Bilan d'un export natif (mesure enveloppante §10 : frames, durée, fps). */
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 03de4dd92..ef60d33c2 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -305,6 +305,48 @@ describe("buildSceneDescription.clips", () => {
const doc = makeDoc({ assets: [asset], clips: [clip] });
expect(buildSceneDescription(doc).clips).toEqual([]);
});
+
+ it("sets hasAudio=true for a clip whose screen asset has an originalPath", () => {
+ // ponytail: the rule is "screen recordings from this app always carry a decodable
+ // audio track" (per product convention + ffprobe on real recordings). The visibleClips
+ // filter above guarantees only clips with originalPath reach the producer, so every
+ // produced CompositorClipInput must carry hasAudio=true today.
+ const asset = makeAsset({ id: "a", originalPath: "/screen.mp4" });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip] });
+ expect(buildSceneDescription(doc).clips[0].hasAudio).toBe(true);
+ });
+
+ it("sets hasAudio=true consistently across multiple clips in the same scene", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/screen.mp4" });
+ const clip1 = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ });
+ const clip2 = makeClip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 4,
+ sourceEndSec: 8,
+ timelineStartSec: 4,
+ timelineEndSec: 8,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip1, clip2] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips).toHaveLength(2);
+ expect(clips.every((c) => c.hasAudio === true)).toBe(true);
+ });
});
// --- zoomRegions -----------------------------------------------------------
@@ -438,6 +480,76 @@ describe("buildSceneDescription.cameraFullscreenRegions", () => {
});
});
+// --- speedRegions -----------------------------------------------------------
+// Speed regions today live under `document.legacyEditor.speedRegions` (the schema's
+// `timeline.speedRanges` is `rangeSchema[]` which carries no `speed` value — see
+// src/native/sceneDescription.ts SceneDescription.speedRegions comment). These tests
+// mirror the cameraFullscreenRegions shape but additionally carry the `speed` field
+// through projection (and assert it stays the same on both sides of a clip split).
+
+describe("buildSceneDescription.speedRegions", () => {
+ it("converts ms->sec for start/end and carries the speed value through", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ const doc = makeDoc({
+ assets: [asset],
+ clips: [clip],
+ legacyEditor: {
+ speedRegions: [{ id: "s1", startMs: 2000, endMs: 5500, speed: 2.5 }],
+ },
+ });
+ const { speedRegions } = buildSceneDescription(doc);
+ expect(speedRegions).toEqual([{ startSec: 2, endSec: 5.5, speed: 2.5 }]);
+ });
+
+ it("yields [] when legacyEditor.speedRegions is missing", () => {
+ const doc = makeDoc({ legacyEditor: {} });
+ expect(buildSceneDescription(doc).speedRegions).toEqual([]);
+ });
+
+ it("splits a region straddling two clips into one entry per clip, both keeping the same speed", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const clip1 = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 100,
+ sourceEndSec: 105,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ });
+ const clip2 = makeClip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 200,
+ sourceEndSec: 205,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ });
+ // Region spans timeline [3s, 7s) — 2s over clip1's tail, 2s over clip2's head.
+ // Both fragments must carry the original `speed` value (3.0) — the projection
+ // function only rewrites startMs/endMs/id, every other field passes through.
+ const doc = makeDoc({
+ assets: [asset],
+ clips: [clip1, clip2],
+ legacyEditor: {
+ speedRegions: [{ id: "s1", startMs: 3000, endMs: 7000, speed: 3.0 }],
+ },
+ });
+ const { speedRegions } = buildSceneDescription(doc);
+ expect(speedRegions).toEqual([
+ { startSec: 103, endSec: 105, speed: 3.0 },
+ { startSec: 200, endSec: 202, speed: 3.0 },
+ ]);
+ });
+});
+
// --- cropByClip --------------------------------------------------------------
describe("buildSceneDescription.cropByClip", () => {
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index be93e09f5..8b8811573 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -15,7 +15,7 @@
* contract — do not change the exported types.
*/
-import type { CameraFullscreenRegion } from "@/components/video-editor/types";
+import type { CameraFullscreenRegion, SpeedRegion } from "@/components/video-editor/types";
import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
import { createId } from "@/lib/ai-edition/document/ids";
import type { AxcutDocument } from "@/lib/ai-edition/schema";
@@ -54,6 +54,19 @@ export interface SceneCameraFullscreenRegion {
endSec: number;
}
+/** A speed region projected onto each clip's source time. The native compositor matches
+ * these against each decoded frame's SOURCE time, the same way zoom regions do — that's
+ * why the spans live in seconds and the underlying projection is `projectRegionsToSourceTime`.
+ * A region straddling a clip boundary splits into one entry per covered clip; both fragments
+ * carry the SAME `speed` value (the projection function only rewrites `startMs`/`endMs`/`id`,
+ * every other field passes through verbatim). */
+export interface SceneSpeedRegion {
+ startSec: number;
+ endSec: number;
+ /** Playback rate multiplier (1 = unchanged). */
+ speed: number;
+}
+
/** Webcam layout, from the editor settings. */
export interface SceneLayout {
preset: "picture-in-picture" | "dual-frame" | "vertical-stack" | "no-webcam";
@@ -118,6 +131,22 @@ export interface SceneDescription {
* source-time span after `projectRegionsToSourceTime`). Empty when none set.
*/
cameraFullscreenRegions: SceneCameraFullscreenRegion[];
+ /**
+ * Speed regions projected onto each clip's source time (one entry per
+ * source-time span after `projectRegionsToSourceTime`). Empty when none set.
+ *
+ * ponytail: speed regions today live at `document.legacyEditor.speedRegions`
+ * — the new `timeline.speedRanges` schema field is `z.array(rangeSchema)` and
+ * `rangeSchema` is `{startSec, endSec, reason}`, which does NOT carry a `speed`
+ * value (see migrate.ts comment "speedRegions stay on the legacy editor envelope
+ * — axcut's rangeSchema doesn't carry a speed value, and Phase 1 timeline rewrite
+ * is when speed becomes a first-class timeline concept"). We read from
+ * `legacyEditor.speedRegions` (where the `speed` multiplier actually lives) so
+ * the native compositor gets a populated `speed`, matching the legacy web
+ * exporter's read site. When the schema rewrite lands, swap the source to
+ * `document.timeline.speedRanges` and keep the same projection call.
+ */
+ speedRegions: SceneSpeedRegion[];
cursor: SceneCursor;
/**
* Per-clip screen crop (fractions of the frame), or null for the identity
@@ -206,6 +235,16 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
const asset = assetById.get(clip.assetId);
if (!asset?.originalPath) return [];
const cam = asset.cameraTrack;
+ // ponytail: screen recordings from this app always carry a decodable audio
+ // track (confirmed via ffprobe on real recordings); webcam files never do
+ // and clips only ever reference their SCREEN path for the main video. The
+ // `asset.audio` schema slot exists but is never populated by the probe
+ // pipeline today, so we can't rely on it as an "is there a track?" signal —
+ // matching the legacy web exporter (which just tries-and-catches in
+ // `decodeSegmentAudioPcm`), we default `hasAudio: true` for every clip whose
+ // asset has an `originalPath`. The visibleClips filter above already
+ // guarantees that precondition by the time we reach this branch. If a
+ // per-asset audio-probe flag is added later, swap to `Boolean(asset.audio)`.
return [
{
screenPath: asset.originalPath,
@@ -213,6 +252,7 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
sourceStartSec: clip.sourceStartSec,
sourceEndSec: resolveClipSourceEndSec(clip, asset),
webcamOffsetSec: cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
+ hasAudio: true,
},
];
});
@@ -254,6 +294,19 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
docClips,
() => createId("camfull"),
);
+ // Speed regions carry an extra `speed` field the standard `rangeSchema` does not, so we
+ // can't read from `document.timeline.speedRanges` today (see SceneDescription.speedRegions
+ // comment). The legacy web exporter reads from `legacyEditor.speedRegions`; we mirror it.
+ // `projectRegionsToSourceTime` accepts any `T extends { id; startMs; endMs }` and copies
+ // every other field verbatim via `{...region}` — so the `speed` field passes through,
+ // and the splitting-across-clips semantics match zoomRegions / cameraFullscreenRegions.
+ const projectedSpeedRegions = projectRegionsToSourceTime(
+ ((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as
+ | SpeedRegion[]
+ | undefined) ?? [],
+ docClips,
+ () => createId("speed"),
+ );
return {
clips,
@@ -298,6 +351,11 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
startSec: region.startMs / 1000,
endSec: region.endMs / 1000,
})),
+ speedRegions: projectedSpeedRegions.map((region) => ({
+ startSec: region.startMs / 1000,
+ endSec: region.endMs / 1000,
+ speed: region.speed,
+ })),
cropByClip,
output: { ...pickOutputDims(document), fps: null },
};