Address code-review findings across export, decode, and data model
Export correctness: - Honor the user's color-range (Limited/Full) on the software encode path: thread full_range through gpu_yuv (new shader range uniform), the CPU swscale fallback (sws_setColorspaceDetails → BT.709 + range, fixing the BT.601 hue/level shift on odd-width exports), and the encoder color tags. - Reject HDR + WebM up front with a clear message and log the forced HEVC override instead of producing an unplayable file. - Delete dead render_frame_to_rgba_hdr (hardcoded Stretch; live HDR path already honors the fit mode). Decode/playback (video.rs): - Drain the decoder at EOF (send_eof + flush) so the final B-frame-delayed frames render instead of erroring; per-frame logic extracted to a helper. - Missing-PTS frames continue monotonically rather than snapping to ts=0. - Force exact thumbnail width so sub-128px sources aren't shown stretched. Resource leaks (gpu-video-encoder): - dmabuf import_raw: RAII guard frees the duped fd + partial VkImages/memory on every error path. - vaapi alloc: free device/frames-ctx/AVFrames on the unexpected-DRM path. Data model / robustness: - collapse_boundary_spikes requires a full curve reversal (all control points) so it no longer deletes a real lens/sliver and drops the fill. - Export audio spin-wait ignores a stale `finished` flag when a forward seek is pending (was rendering silence over real audio). - RasterDiff apply_before/after take current dims and skip on a post-resize mismatch. - beam_archive read_media_full caps the preallocation from untrusted total_len. UI/visual: - SVG export skips hidden layers/empty groups; import folds fill-opacity into gradients and surfaces failures as a notification. - Active raster-layer border uses playback_time + overlay_transform. - gpu_brush remove_layer_texture also evicts the stale low-res proxy. - ensure_raster_resident_for_undo registers faulted frames in the LRU so resident RAM stays bounded. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
1fa4d744be
commit
b301c63387
@@ -98,11 +98,16 @@ impl RasterDiff {
|
||||
self.before_region.len() + self.after_region.len()
|
||||
}
|
||||
|
||||
/// Restore the pre-edit pixels into `raw` (undo / first-execute rollback).
|
||||
pub fn apply_before(&self, raw: &mut Vec<u8>) {
|
||||
/// Restore the pre-edit pixels into `raw` (undo / first-execute rollback). `cur_w`/`cur_h`
|
||||
/// are the keyframe's current dimensions; if they differ from the diff's captured size the
|
||||
/// diff predates a resize and is skipped rather than applied at mismatched dims.
|
||||
pub fn apply_before(&self, raw: &mut Vec<u8>, cur_w: u32, cur_h: u32) {
|
||||
if self.bbox.is_none() {
|
||||
return; // no change
|
||||
}
|
||||
if cur_w != self.full_width || cur_h != self.full_height {
|
||||
return; // diff predates a keyframe resize
|
||||
}
|
||||
if self.before_blank {
|
||||
// The frame was blank before this edit (it was the first stroke); undoing
|
||||
// it returns to blank regardless of the current buffer.
|
||||
@@ -112,11 +117,16 @@ impl RasterDiff {
|
||||
self.stamp_resident(&self.before_region, raw);
|
||||
}
|
||||
|
||||
/// Apply the post-edit pixels into `raw` (commit / redo).
|
||||
pub fn apply_after(&self, raw: &mut Vec<u8>) {
|
||||
/// Apply the post-edit pixels into `raw` (commit / redo). `cur_w`/`cur_h` are the keyframe's
|
||||
/// current dimensions; a mismatch with the captured size means the diff predates a resize, so
|
||||
/// it's skipped rather than rebuilding the buffer at stale dimensions.
|
||||
pub fn apply_after(&self, raw: &mut Vec<u8>, cur_w: u32, cur_h: u32) {
|
||||
if self.bbox.is_none() {
|
||||
return; // no change
|
||||
}
|
||||
if cur_w != self.full_width || cur_h != self.full_height {
|
||||
return; // diff predates a keyframe resize
|
||||
}
|
||||
if self.before_blank {
|
||||
// Base was blank: build a full transparent buffer then stamp the bbox. The
|
||||
// commit/redo path frequently starts from empty `raw_pixels` here.
|
||||
@@ -175,9 +185,9 @@ mod tests {
|
||||
assert_eq!(diff.bbox, Some((3, 2, 2, 2)));
|
||||
|
||||
let mut buf = after.clone();
|
||||
diff.apply_before(&mut buf);
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert_eq!(buf, before, "undo must reproduce the pre-edit buffer exactly");
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "redo must reproduce the post-edit buffer exactly");
|
||||
}
|
||||
|
||||
@@ -195,15 +205,15 @@ mod tests {
|
||||
// First execute / redo from EMPTY raw_pixels (the real commit path): builds
|
||||
// the full buffer from transparent + the stroke.
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "commit/redo must build the frame from a blank base");
|
||||
|
||||
// Undo the first stroke → back to blank (empty).
|
||||
diff.apply_before(&mut buf);
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert!(buf.is_empty(), "undoing the first stroke restores the blank keyframe");
|
||||
|
||||
// Redo again from the now-empty buffer.
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after);
|
||||
}
|
||||
|
||||
@@ -215,7 +225,7 @@ mod tests {
|
||||
assert_eq!(diff.bbox, None);
|
||||
assert_eq!(diff.byte_size(), 0);
|
||||
let mut b = buf.clone();
|
||||
diff.apply_before(&mut b);
|
||||
diff.apply_before(&mut b, w, h);
|
||||
assert_eq!(b, buf);
|
||||
}
|
||||
|
||||
@@ -226,7 +236,7 @@ mod tests {
|
||||
let after = solid(w, h, [1, 2, 3, 255]);
|
||||
let diff = RasterDiff::compute(&before, &after, w, h);
|
||||
let mut empty: Vec<u8> = Vec::new();
|
||||
diff.apply_before(&mut empty); // base not resident
|
||||
diff.apply_before(&mut empty, w, h); // base not resident
|
||||
assert!(empty.is_empty(), "must not resize/corrupt a non-resident base");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Action for RasterFillAction {
|
||||
if let Some(full) = self.full_after.take() {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
self.diff.apply_after(&mut kf.raw_pixels);
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
@@ -71,7 +71,7 @@ impl Action for RasterFillAction {
|
||||
let kf = raster
|
||||
.keyframe_at_mut(self.time)
|
||||
.ok_or_else(|| format!("No raster keyframe at/before t={}", self.time))?;
|
||||
self.diff.apply_before(&mut kf.raw_pixels);
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
|
||||
@@ -61,7 +61,7 @@ impl Action for RasterStrokeAction {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
// Redo: replay via the diff onto the (resident) base.
|
||||
self.diff.apply_after(&mut kf.raw_pixels);
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
@@ -70,7 +70,7 @@ impl Action for RasterStrokeAction {
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
self.diff.apply_before(&mut kf.raw_pixels);
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
|
||||
@@ -374,7 +374,11 @@ impl BeamArchive {
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut out = Vec::with_capacity(info.total_len as usize);
|
||||
// `total_len` is an untrusted DB field; cap the preallocation so a corrupt/oversized
|
||||
// value can't trigger a multi-GB eager allocation (or, on 32-bit, a truncated `as usize`).
|
||||
// The Vec still grows to fit the actual chunk bytes regardless.
|
||||
const PREALLOC_CAP: u64 = 64 * 1024 * 1024;
|
||||
let mut out = Vec::with_capacity(info.total_len.min(PREALLOC_CAP) as usize);
|
||||
for row in rows {
|
||||
out.extend_from_slice(&row.map_err(map_sql)?);
|
||||
}
|
||||
|
||||
@@ -266,6 +266,9 @@ pub fn document_to_svg(document: &Document, time: f64) -> String {
|
||||
fn layer_to_svg(layer: &AnyLayer, time: f64, parent_opacity: f64, body: &mut String, defs: &mut String, grad_n: &mut usize) {
|
||||
match layer {
|
||||
AnyLayer::Vector(vl) => {
|
||||
if !vl.layer.visible {
|
||||
return; // hidden layers are not rendered, so don't export them
|
||||
}
|
||||
let opacity = parent_opacity * vl.layer.opacity;
|
||||
if let Some(graph) = vl.tweened_graph_at(time) {
|
||||
let wrap = opacity < 0.999;
|
||||
@@ -281,12 +284,21 @@ fn layer_to_svg(layer: &AnyLayer, time: f64, parent_opacity: f64, body: &mut Str
|
||||
// exported — a refinement once loose-geometry export is verified.
|
||||
}
|
||||
AnyLayer::Group(g) => {
|
||||
let opacity = parent_opacity * g.layer.opacity;
|
||||
body.push_str(&format!(r#"<g opacity="{opacity:.4}">"#));
|
||||
for child in &g.children {
|
||||
layer_to_svg(child, time, 1.0, body, defs, grad_n);
|
||||
if !g.layer.visible {
|
||||
return;
|
||||
}
|
||||
// Render children first; only emit the <g> wrapper if it has exportable content
|
||||
// (avoids empty groups when every child is a non-vector/hidden layer).
|
||||
let mut inner = String::new();
|
||||
for child in &g.children {
|
||||
layer_to_svg(child, time, 1.0, &mut inner, defs, grad_n);
|
||||
}
|
||||
if !inner.is_empty() {
|
||||
let opacity = parent_opacity * g.layer.opacity;
|
||||
body.push_str(&format!(r#"<g opacity="{opacity:.4}">"#));
|
||||
body.push_str(&inner);
|
||||
body.push_str("</g>");
|
||||
}
|
||||
body.push_str("</g>");
|
||||
}
|
||||
// Raster/Video/Audio/Effect have no lossless vector representation — skipped this pass.
|
||||
_ => {}
|
||||
|
||||
@@ -1302,21 +1302,26 @@ impl VectorGraph {
|
||||
/// bouncing across near-coincident duplicate edges). These are zero-area and would make
|
||||
/// `boundary_to_bezpath` render a stray hair; collapsing them yields a simple loop.
|
||||
fn collapse_boundary_spikes(&self, face: &mut Vec<(EdgeId, Direction)>) {
|
||||
let dstart = |entry: &(EdgeId, Direction)| -> Point {
|
||||
// The four control points of an entry's curve in its traversal order.
|
||||
let traversed = |entry: &(EdgeId, Direction)| -> [Point; 4] {
|
||||
let c = self.edges[entry.0.idx()].curve;
|
||||
match entry.1 {
|
||||
Direction::Forward => c.p0,
|
||||
Direction::Backward => c.p3,
|
||||
}
|
||||
};
|
||||
let dend = |entry: &(EdgeId, Direction)| -> Point {
|
||||
let c = self.edges[entry.0.idx()].curve;
|
||||
match entry.1 {
|
||||
Direction::Forward => c.p3,
|
||||
Direction::Backward => c.p0,
|
||||
Direction::Forward => [c.p0, c.p1, c.p2, c.p3],
|
||||
Direction::Backward => [c.p3, c.p2, c.p1, c.p0],
|
||||
}
|
||||
};
|
||||
const EPS: f64 = 0.5;
|
||||
// Entries i and j cancel only when j is the *exact reverse* of i — every control point of
|
||||
// j matches the mirror of i. Testing endpoints alone would also collapse a genuine
|
||||
// lens/sliver (two distinct edges that merely share near-coincident endpoints), silently
|
||||
// deleting real boundary geometry and dropping the fill.
|
||||
let reverses = |a: &(EdgeId, Direction), b: &(EdgeId, Direction)| -> bool {
|
||||
let (ca, cb) = (traversed(a), traversed(b));
|
||||
(0..4).all(|k| {
|
||||
let (p, q) = (ca[k], cb[3 - k]);
|
||||
(p.x - q.x).hypot(p.y - q.y) < EPS
|
||||
})
|
||||
};
|
||||
loop {
|
||||
let n = face.len();
|
||||
if n < 2 {
|
||||
@@ -1325,10 +1330,7 @@ impl VectorGraph {
|
||||
let mut collapsed = false;
|
||||
for i in 0..n {
|
||||
let j = (i + 1) % n;
|
||||
// entries i and j cancel when j ends back at i's start.
|
||||
let si = dstart(&face[i]);
|
||||
let ej = dend(&face[j]);
|
||||
if (si.x - ej.x).hypot(si.y - ej.y) < EPS {
|
||||
if reverses(&face[i], &face[j]) {
|
||||
let (hi, lo) = if i > j { (i, j) } else { (j, i) };
|
||||
face.remove(hi);
|
||||
face.remove(lo);
|
||||
|
||||
@@ -120,6 +120,153 @@ enum DecodedFrame {
|
||||
Gpu(GpuVideoFrame),
|
||||
}
|
||||
|
||||
/// Result of processing one decoded frame against the requested target timestamp.
|
||||
enum FrameOutcome {
|
||||
/// Frame consumed; keep decoding.
|
||||
Continue,
|
||||
/// `current_frame_ts >= frame_ts` — caller should return the best frame found.
|
||||
ReachedTarget,
|
||||
/// Hardware surface import failed; caller should fall back to software.
|
||||
HwImportFailed,
|
||||
}
|
||||
|
||||
/// Process one decoded `frame`: update the best-so-far (`best_*`) toward `frame_ts`, importing a
|
||||
/// GPU surface (`gpu_out`) or swscaling to RGBA otherwise. Pulled out of the decode loop so the
|
||||
/// same logic runs both for packet-fed frames and for frames flushed out of the codec at EOF.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn process_decoded_video_frame(
|
||||
frame: &mut ffmpeg::util::frame::Video,
|
||||
decoder: &ffmpeg::decoder::Video,
|
||||
gpu_out: bool,
|
||||
hw: bool,
|
||||
out_w: u32,
|
||||
out_h: u32,
|
||||
frame_ts: i64,
|
||||
importer: Option<&Arc<dyn HwVideoImporter>>,
|
||||
scaler: &mut Option<(ffmpeg::format::Pixel, u32, u32, u32, u32, SendScaler)>,
|
||||
best_frame_data: &mut Option<Vec<u8>>,
|
||||
best_gpu: &mut Option<GpuVideoFrame>,
|
||||
best_frame_ts: &mut Option<i64>,
|
||||
last_decoded_ts: &mut i64,
|
||||
scale_time_ms: &mut u128,
|
||||
) -> Result<FrameOutcome, String> {
|
||||
use std::time::Instant;
|
||||
|
||||
// A frame with no PTS continues monotonically from the last decoded position rather than
|
||||
// snapping to 0 — treating "no timestamp" as ts=0 would look like a huge backward jump and
|
||||
// corrupt the best-frame / seek logic on streams with missing PTS.
|
||||
let current_frame_ts = frame.timestamp().unwrap_or(*last_decoded_ts + 1);
|
||||
*last_decoded_ts = current_frame_ts;
|
||||
|
||||
let is_better = match *best_frame_ts {
|
||||
None => true,
|
||||
Some(best_ts) => (current_frame_ts - frame_ts).abs() < (best_ts - frame_ts).abs(),
|
||||
};
|
||||
|
||||
if is_better {
|
||||
if gpu_out {
|
||||
// VAAPI hw frames often don't carry the stream's colour tags, so the importer would
|
||||
// mis-detect transfer/gamut. Copy the authoritative values from the codec context
|
||||
// (parsed from the bitstream) onto the frame when it left them unspecified.
|
||||
unsafe {
|
||||
use ffmpeg::ffi::*;
|
||||
let fp = frame.as_mut_ptr();
|
||||
let cp = decoder.as_ptr();
|
||||
if (*fp).color_trc == AVColorTransferCharacteristic::AVCOL_TRC_UNSPECIFIED {
|
||||
(*fp).color_trc = (*cp).color_trc;
|
||||
}
|
||||
if (*fp).color_primaries == AVColorPrimaries::AVCOL_PRI_UNSPECIFIED {
|
||||
(*fp).color_primaries = (*cp).color_primaries;
|
||||
}
|
||||
if (*fp).colorspace == AVColorSpace::AVCOL_SPC_UNSPECIFIED {
|
||||
(*fp).colorspace = (*cp).colorspace;
|
||||
}
|
||||
if (*fp).color_range == AVColorRange::AVCOL_RANGE_UNSPECIFIED {
|
||||
(*fp).color_range = (*cp).color_range;
|
||||
}
|
||||
}
|
||||
let importer = importer.unwrap();
|
||||
match unsafe { importer.import(frame.as_mut_ptr() as *mut std::ffi::c_void) } {
|
||||
Some(gpu) => {
|
||||
*best_gpu = Some(gpu);
|
||||
*best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
None => return Ok(FrameOutcome::HwImportFailed),
|
||||
}
|
||||
} else {
|
||||
let t_scale_start = Instant::now();
|
||||
|
||||
// A hardware decoder produces VAAPI surfaces; a CPU consumer (export) downloads to
|
||||
// system memory first, then swscales like the software path.
|
||||
let downloaded;
|
||||
let src: &ffmpeg::util::frame::Video = if hw {
|
||||
let mut dl = ffmpeg::util::frame::Video::empty();
|
||||
let r = unsafe {
|
||||
ffmpeg::ffi::av_hwframe_transfer_data(dl.as_mut_ptr(), frame.as_ptr(), 0)
|
||||
};
|
||||
if r < 0 {
|
||||
return Err(format!("av_hwframe_transfer_data failed: {r}"));
|
||||
}
|
||||
downloaded = dl;
|
||||
&downloaded
|
||||
} else {
|
||||
&*frame
|
||||
};
|
||||
|
||||
// Reuse the RGBA scaler across frames; rebuild only if the input format/size or the
|
||||
// requested output size changes.
|
||||
let need_new = match scaler {
|
||||
Some((fmt, w, h, ow, oh, _)) => {
|
||||
*fmt != src.format() || *w != src.width() || *h != src.height()
|
||||
|| *ow != out_w || *oh != out_h
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if need_new {
|
||||
let ctx = ffmpeg::software::scaling::context::Context::get(
|
||||
src.format(),
|
||||
src.width(),
|
||||
src.height(),
|
||||
ffmpeg::format::Pixel::RGBA,
|
||||
out_w,
|
||||
out_h,
|
||||
ffmpeg::software::scaling::flag::Flags::BILINEAR,
|
||||
).map_err(|e| e.to_string())?;
|
||||
*scaler = Some((src.format(), src.width(), src.height(), out_w, out_h, SendScaler(ctx)));
|
||||
}
|
||||
let scaler = &mut scaler.as_mut().unwrap().5.0;
|
||||
|
||||
let mut rgb_frame = ffmpeg::util::frame::Video::empty();
|
||||
scaler.run(src, &mut rgb_frame)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Remove stride padding to create tightly packed RGBA data
|
||||
let width = out_w as usize;
|
||||
let height = out_h as usize;
|
||||
let stride = rgb_frame.stride(0);
|
||||
let row_size = width * 4; // RGBA = 4 bytes per pixel
|
||||
let source_data = rgb_frame.data(0);
|
||||
|
||||
let mut packed_data = Vec::with_capacity(row_size * height);
|
||||
for y in 0..height {
|
||||
let row_start = y * stride;
|
||||
let row_end = row_start + row_size;
|
||||
packed_data.extend_from_slice(&source_data[row_start..row_end]);
|
||||
}
|
||||
|
||||
*scale_time_ms += t_scale_start.elapsed().as_millis();
|
||||
*best_frame_data = Some(packed_data);
|
||||
*best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
}
|
||||
|
||||
if current_frame_ts >= frame_ts {
|
||||
Ok(FrameOutcome::ReachedTarget)
|
||||
} else {
|
||||
Ok(FrameOutcome::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
/// `get_format` callback for hardware decode: select VAAPI surfaces. With `hw_device_ctx` set,
|
||||
/// FFmpeg auto-allocates the frames context.
|
||||
unsafe extern "C" fn get_vaapi_format(
|
||||
@@ -459,159 +606,73 @@ impl VideoDecoder {
|
||||
let mut scale_time_ms = 0u128;
|
||||
let mut hw_import_failed = false;
|
||||
|
||||
'decode: for (stream, packet) in input.packets() {
|
||||
if stream.index() == self.stream_index {
|
||||
decoder.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
'decode: {
|
||||
for (stream, packet) in input.packets() {
|
||||
if stream.index() == self.stream_index {
|
||||
decoder.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
while decoder.receive_frame(&mut frame).is_ok() {
|
||||
decode_count += 1;
|
||||
match process_decoded_video_frame(
|
||||
&mut frame, decoder, gpu_out, hw, out_w, out_h, frame_ts,
|
||||
self.importer.as_ref(), &mut self.scaler,
|
||||
&mut best_frame_data, &mut best_gpu, &mut best_frame_ts,
|
||||
&mut self.last_decoded_ts, &mut scale_time_ms,
|
||||
)? {
|
||||
FrameOutcome::Continue => {}
|
||||
FrameOutcome::ReachedTarget => break 'decode,
|
||||
FrameOutcome::HwImportFailed => {
|
||||
self.hw_failed = true;
|
||||
hw_import_failed = true;
|
||||
break 'decode;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush: the codec may still hold buffered frames (B-frame reorder delay) past the
|
||||
// last packet. Drain them so requesting the final frame(s) of a clip — scrubbing to
|
||||
// the end or exporting the tail — doesn't fail with "Failed to decode frame".
|
||||
if !hw_import_failed {
|
||||
let _ = decoder.send_eof();
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
while decoder.receive_frame(&mut frame).is_ok() {
|
||||
decode_count += 1;
|
||||
let current_frame_ts = frame.timestamp().unwrap_or(0);
|
||||
self.last_decoded_ts = current_frame_ts; // Update last decoded position
|
||||
|
||||
// Check if this frame is closer to our target than the previous best
|
||||
let is_better = match best_frame_ts {
|
||||
None => true,
|
||||
Some(best_ts) => {
|
||||
(current_frame_ts - frame_ts).abs() < (best_ts - frame_ts).abs()
|
||||
match process_decoded_video_frame(
|
||||
&mut frame, decoder, gpu_out, hw, out_w, out_h, frame_ts,
|
||||
self.importer.as_ref(), &mut self.scaler,
|
||||
&mut best_frame_data, &mut best_gpu, &mut best_frame_ts,
|
||||
&mut self.last_decoded_ts, &mut scale_time_ms,
|
||||
)? {
|
||||
FrameOutcome::Continue => {}
|
||||
FrameOutcome::ReachedTarget => break 'decode,
|
||||
FrameOutcome::HwImportFailed => {
|
||||
self.hw_failed = true;
|
||||
hw_import_failed = true;
|
||||
break 'decode;
|
||||
}
|
||||
};
|
||||
|
||||
if is_better {
|
||||
if gpu_out {
|
||||
// Hardware + GPU consumer: import the VAAPI surface as wgpu NV12 textures
|
||||
// (no CPU copy).
|
||||
// VAAPI hw frames often don't carry the stream's colour tags, so the
|
||||
// importer (which only sees the frame) would mis-detect transfer/gamut.
|
||||
// Copy the authoritative values from the codec context (parsed from the
|
||||
// bitstream) onto the frame when it left them unspecified.
|
||||
unsafe {
|
||||
use ffmpeg::ffi::*;
|
||||
let fp = frame.as_mut_ptr();
|
||||
let cp = decoder.as_ptr();
|
||||
if (*fp).color_trc == AVColorTransferCharacteristic::AVCOL_TRC_UNSPECIFIED {
|
||||
(*fp).color_trc = (*cp).color_trc;
|
||||
}
|
||||
if (*fp).color_primaries == AVColorPrimaries::AVCOL_PRI_UNSPECIFIED {
|
||||
(*fp).color_primaries = (*cp).color_primaries;
|
||||
}
|
||||
if (*fp).colorspace == AVColorSpace::AVCOL_SPC_UNSPECIFIED {
|
||||
(*fp).colorspace = (*cp).colorspace;
|
||||
}
|
||||
if (*fp).color_range == AVColorRange::AVCOL_RANGE_UNSPECIFIED {
|
||||
(*fp).color_range = (*cp).color_range;
|
||||
}
|
||||
}
|
||||
let importer = self.importer.as_ref().unwrap();
|
||||
match unsafe { importer.import(frame.as_mut_ptr() as *mut std::ffi::c_void) } {
|
||||
Some(gpu) => {
|
||||
best_gpu = Some(gpu);
|
||||
best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
None => {
|
||||
// Import failed → fall back to software for this clip.
|
||||
self.hw_failed = true;
|
||||
hw_import_failed = true;
|
||||
break 'decode;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let t_scale_start = Instant::now();
|
||||
|
||||
// A hardware decoder produces VAAPI surfaces; a CPU consumer (export)
|
||||
// downloads to system memory first, then swscales like the software path.
|
||||
let downloaded;
|
||||
let src: &ffmpeg::util::frame::Video = if hw {
|
||||
let mut dl = ffmpeg::util::frame::Video::empty();
|
||||
let r = unsafe {
|
||||
ffmpeg::ffi::av_hwframe_transfer_data(dl.as_mut_ptr(), frame.as_ptr(), 0)
|
||||
};
|
||||
if r < 0 {
|
||||
return Err(format!("av_hwframe_transfer_data failed: {r}"));
|
||||
}
|
||||
downloaded = dl;
|
||||
&downloaded
|
||||
} else {
|
||||
&frame
|
||||
};
|
||||
|
||||
// Reuse the RGBA scaler across frames; rebuild only if the input
|
||||
// format/size or the requested output size changes.
|
||||
let need_new = match &self.scaler {
|
||||
Some((fmt, w, h, ow, oh, _)) => {
|
||||
*fmt != src.format() || *w != src.width() || *h != src.height()
|
||||
|| *ow != out_w || *oh != out_h
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if need_new {
|
||||
let ctx = ffmpeg::software::scaling::context::Context::get(
|
||||
src.format(),
|
||||
src.width(),
|
||||
src.height(),
|
||||
ffmpeg::format::Pixel::RGBA,
|
||||
out_w,
|
||||
out_h,
|
||||
ffmpeg::software::scaling::flag::Flags::BILINEAR,
|
||||
).map_err(|e| e.to_string())?;
|
||||
self.scaler = Some((src.format(), src.width(), src.height(), out_w, out_h, SendScaler(ctx)));
|
||||
}
|
||||
let scaler = &mut self.scaler.as_mut().unwrap().5.0;
|
||||
|
||||
let mut rgb_frame = ffmpeg::util::frame::Video::empty();
|
||||
scaler.run(src, &mut rgb_frame)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Remove stride padding to create tightly packed RGBA data
|
||||
let width = out_w as usize;
|
||||
let height = out_h as usize;
|
||||
let stride = rgb_frame.stride(0);
|
||||
let row_size = width * 4; // RGBA = 4 bytes per pixel
|
||||
let source_data = rgb_frame.data(0);
|
||||
|
||||
let mut packed_data = Vec::with_capacity(row_size * height);
|
||||
for y in 0..height {
|
||||
let row_start = y * stride;
|
||||
let row_end = row_start + row_size;
|
||||
packed_data.extend_from_slice(&source_data[row_start..row_end]);
|
||||
}
|
||||
|
||||
scale_time_ms += t_scale_start.elapsed().as_millis();
|
||||
best_frame_data = Some(packed_data);
|
||||
best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
}
|
||||
|
||||
// If we've reached or passed the target timestamp, we can stop
|
||||
if current_frame_ts >= frame_ts {
|
||||
if video_debug() {
|
||||
let total_time = t_start.elapsed().as_millis();
|
||||
let decode_time = t_decode_start.elapsed().as_millis();
|
||||
eprintln!("[Video Timing] ts={:.3}s | Decoded {} frames in {}ms | Scale: {}ms | Total: {}ms | {}",
|
||||
timestamp, decode_count, decode_time, scale_time_ms, total_time, if hw { "hw" } else { "sw" });
|
||||
}
|
||||
if gpu_out {
|
||||
if let Some(gpu) = best_gpu.take() {
|
||||
return Ok(DecodedFrame::Gpu(gpu));
|
||||
}
|
||||
} else if let Some(data) = best_frame_data {
|
||||
self.frame_cache.put(cache_key, data.clone());
|
||||
return Ok(DecodedFrame::Cpu { rgba: data, width: out_w, height: out_h });
|
||||
}
|
||||
break 'decode;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reached EOF without hitting the target, or HW import failed mid-stream.
|
||||
if video_debug() {
|
||||
let total_time = t_start.elapsed().as_millis();
|
||||
let decode_time = t_decode_start.elapsed().as_millis();
|
||||
eprintln!("[Video Timing] ts={:.3}s | Decoded {} frames in {}ms | Scale: {}ms | Total: {}ms | {}",
|
||||
timestamp, decode_count, decode_time, scale_time_ms, total_time, if hw { "hw" } else { "sw" });
|
||||
}
|
||||
|
||||
// Reached the target, EOF, or HW import failed mid-stream.
|
||||
if hw_import_failed {
|
||||
self.decoder = None; // force a software rebuild next call (decoder borrow ended here)
|
||||
self.input = None;
|
||||
return Err("hardware frame import failed; retrying software".to_string());
|
||||
}
|
||||
// EOF: return the closest frame we found, if any.
|
||||
// Return the closest frame we found, if any.
|
||||
if gpu_out {
|
||||
if let Some(gpu) = best_gpu.take() {
|
||||
return Ok(DecodedFrame::Gpu(gpu));
|
||||
@@ -673,8 +734,23 @@ pub fn generate_keyframe_thumbnails(
|
||||
}
|
||||
// Decode at the thumbnail width (large height so width is the constraint), capped to native.
|
||||
// Thumbnail decoders are always software (no hardware importer).
|
||||
if let Ok(DecodedFrame::Cpu { rgba, .. }) = decoder.get_frame(ks, thumb_width, 100_000, false) {
|
||||
on_thumb(ks, Arc::new(rgba));
|
||||
if let Ok(DecodedFrame::Cpu { rgba, width, height }) = decoder.get_frame(ks, thumb_width, 100_000, false) {
|
||||
// `capped_output` never upscales, so a source narrower than `thumb_width` decodes
|
||||
// smaller — but `get_thumbnail_at` reconstructs height assuming an exact `thumb_width`.
|
||||
// Force the exact width here (rare path) so that assumption holds and the thumbnail
|
||||
// isn't shown stretched.
|
||||
let data = if width == thumb_width || width == 0 || height == 0 {
|
||||
rgba
|
||||
} else {
|
||||
let new_h = ((thumb_width as u64 * height as u64) / width as u64).max(1) as u32;
|
||||
match image::RgbaImage::from_raw(width, height, rgba) {
|
||||
Some(img) => image::imageops::resize(
|
||||
&img, thumb_width, new_h, image::imageops::FilterType::Triangle,
|
||||
).into_raw(),
|
||||
None => continue,
|
||||
}
|
||||
};
|
||||
on_thumb(ks, Arc::new(data));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user