Fix video thumbnail strip bugs + persist thumbnails (resumable)
Thumbnail rendering fixes: - Strip now tiles from each clip's true (unclamped) origin and draws only the tiles intersecting the visible rect, so it scrolls correctly and shows the right frames when a clip is scrolled partly off the left. Both render sites (collapsed group + expanded track) share one draw_video_thumbnail_strip helper. - On-clip strip no longer freezes on the first thumbnail: get_thumbnail_at now returns the actual thumbnail timestamp and the GPU texture cache keys on it, so tiles refresh as closer thumbnails finish generating. - Hover preview derives content time from the clip's true origin too (matches the strip when scrolled off-screen). - insert_thumbnail keeps the cache sorted + deduped (fixes a latent unsorted binary_search bug, and makes concurrent restore + resume race-safe). Thumbnail persistence (mirrors waveform persistence): - MediaKind::Thumbnail rows, keyed by thumbnail_media_id(clip_id) (clip id XOR a sentinel). Each clip's thumbnails PNG-encoded into one opaque LBTN blob (editor owns the format), snapshotted cheaply (Arc clones) and encoded off the UI thread. - Save writes the packs (kept in place on re-save); load reads them into LoadedProject.thumbnail_blobs; the editor decodes + inserts them on a background thread, so reload shows thumbnails instantly with no re-decode (even if the source video file is missing). - Partial sets are persisted with a complete flag and RESUMED on load: generate_keyframe_thumbnails takes a should_skip predicate so a save made mid-generation continues from where it left off instead of redoing the work. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
c784816615
commit
097345be76
@@ -55,6 +55,9 @@ pub enum MediaKind {
|
||||
/// A precomputed waveform LOD pyramid blob for an audio item (keyed by the
|
||||
/// same id as the audio it describes). See `daw_backend::audio::waveform_pyramid`.
|
||||
Waveform = 4,
|
||||
/// A pack of precomputed video thumbnails for a video clip (keyed by a
|
||||
/// sentinel-derived id from the clip id). Opaque blob; format owned by the editor.
|
||||
Thumbnail = 5,
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
@@ -65,6 +68,7 @@ impl MediaKind {
|
||||
2 => Some(Self::Raster),
|
||||
3 => Some(Self::ImageAsset),
|
||||
4 => Some(Self::Waveform),
|
||||
5 => Some(Self::Thumbnail),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,11 @@ pub struct LoadedProject {
|
||||
/// Loaded audio pool entries
|
||||
pub audio_pool_entries: Vec<AudioPoolEntry>,
|
||||
|
||||
/// Persisted video-thumbnail packs by clip id (opaque LBTN blobs; decoded and
|
||||
/// inserted into the VideoManager by the editor). Clips present here don't need
|
||||
/// their thumbnails regenerated on load.
|
||||
pub thumbnail_blobs: std::collections::HashMap<uuid::Uuid, Vec<u8>>,
|
||||
|
||||
/// List of files that couldn't be found
|
||||
pub missing_files: Vec<MissingFileInfo>,
|
||||
}
|
||||
@@ -239,12 +244,23 @@ fn waveform_media_id(pool_index: usize) -> Uuid {
|
||||
Uuid::from_u128(SENTINEL | (pool_index as u128))
|
||||
}
|
||||
|
||||
/// Deterministic id for the thumbnail-pack media row of a video clip. Derived from
|
||||
/// the clip id by XOR with a fixed constant — bijective and stable across saves, so
|
||||
/// it reuses the row in place, and it can't (in practice) collide with the random
|
||||
/// v4 ids used for other media of a different kind.
|
||||
fn thumbnail_media_id(clip_id: Uuid) -> Uuid {
|
||||
// "LBTN" repeated — moves clip ids into a distinct region of the id space.
|
||||
const SENTINEL: u128 = 0x4C42_544E_4C42_544E_4C42_544E_4C42_544E;
|
||||
Uuid::from_u128(clip_id.as_u128() ^ SENTINEL)
|
||||
}
|
||||
|
||||
pub fn save_beam(
|
||||
path: &Path,
|
||||
document: &Document,
|
||||
audio_project: &mut AudioProject,
|
||||
audio_pool_entries: Vec<AudioPoolEntry>,
|
||||
layer_to_track_map: &std::collections::HashMap<uuid::Uuid, u32>,
|
||||
thumbnail_blobs: &std::collections::HashMap<uuid::Uuid, Vec<u8>>,
|
||||
_settings: &SaveSettings,
|
||||
) -> Result<(), String> {
|
||||
let fn_start = std::time::Instant::now();
|
||||
@@ -400,6 +416,19 @@ pub fn save_beam(
|
||||
}
|
||||
}
|
||||
|
||||
// --- video thumbnail packs -> media rows (opaque LBTN blob), keyed by a
|
||||
// sentinel-derived id from the video clip id ---
|
||||
for clip_id in document.video_clips.keys() {
|
||||
let tn_id = thumbnail_media_id(*clip_id);
|
||||
if let Some(blob) = thumbnail_blobs.get(clip_id) {
|
||||
txn.put_media_packed(tn_id, MediaKind::Thumbnail, "lbtn", blob, MediaMeta::default())?;
|
||||
live_media.insert(tn_id);
|
||||
} else if txn.media_exists(tn_id)? {
|
||||
// Not regenerated this session — keep the stored pack.
|
||||
live_media.insert(tn_id);
|
||||
}
|
||||
}
|
||||
|
||||
// --- orphan cleanup: drop media for removed clips/keyframes ---
|
||||
let removed = txn.retain_media(&live_media)?;
|
||||
|
||||
@@ -576,10 +605,26 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Persisted video thumbnail packs (opaque LBTN blobs), keyed by clip id. The
|
||||
// editor decodes + inserts them and skips regeneration for these clips.
|
||||
let mut thumbnail_blobs = std::collections::HashMap::new();
|
||||
for clip_id in document.video_clips.keys() {
|
||||
let tn_id = thumbnail_media_id(*clip_id);
|
||||
if let Ok(Some(info)) = archive.media_info(tn_id) {
|
||||
if info.kind == MediaKind::Thumbnail {
|
||||
match archive.read_media_full(tn_id) {
|
||||
Ok(bytes) => { thumbnail_blobs.insert(*clip_id, bytes); }
|
||||
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to read thumbnails for {}: {}", clip_id, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"📊 [LOAD_BEAM] ✅ Loaded {} audio entries, {} raster frames in {:.2}ms",
|
||||
"📊 [LOAD_BEAM] ✅ Loaded {} audio entries, {} raster frames, {} thumbnail packs in {:.2}ms",
|
||||
restored_entries.len(),
|
||||
raster_load_count,
|
||||
thumbnail_blobs.len(),
|
||||
fn_start.elapsed().as_secs_f64() * 1000.0
|
||||
);
|
||||
|
||||
@@ -588,6 +633,7 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
audio_project,
|
||||
layer_to_track_map,
|
||||
audio_pool_entries: restored_entries,
|
||||
thumbnail_blobs,
|
||||
missing_files,
|
||||
})
|
||||
}
|
||||
@@ -815,6 +861,7 @@ fn load_beam_zip_legacy(path: &Path) -> Result<LoadedProject, String> {
|
||||
audio_project,
|
||||
layer_to_track_map,
|
||||
audio_pool_entries: restored_entries,
|
||||
thumbnail_blobs: std::collections::HashMap::new(), // legacy ZIP has no thumbnail packs
|
||||
missing_files,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -359,6 +359,7 @@ pub fn generate_keyframe_thumbnails(
|
||||
path: &str,
|
||||
interval_secs: f64,
|
||||
thumb_width: u32,
|
||||
mut should_skip: impl FnMut(f64) -> bool,
|
||||
mut on_thumb: impl FnMut(f64, Arc<Vec<u8>>),
|
||||
) -> Result<(), String> {
|
||||
// Own decoder at thumbnail resolution; builds its own keyframe index. The
|
||||
@@ -383,8 +384,14 @@ pub fn generate_keyframe_thumbnails(
|
||||
if ks - last_emitted < interval_secs {
|
||||
continue;
|
||||
}
|
||||
// This keyframe is a target slot; advance regardless of skip so the chosen
|
||||
// slots are deterministic (lets a resumed pass target the same timestamps).
|
||||
last_emitted = ks;
|
||||
// Skip slots already covered (resume after a partial save / dedup).
|
||||
if should_skip(ks) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(rgba) = decoder.get_frame(ks) {
|
||||
last_emitted = ks;
|
||||
on_thumb(ks, Arc::new(rgba));
|
||||
}
|
||||
}
|
||||
@@ -471,6 +478,11 @@ pub struct VideoManager {
|
||||
/// Low-resolution (64px width) thumbnails for scrubbing
|
||||
thumbnail_cache: HashMap<Uuid, Vec<(f64, Arc<Vec<u8>>)>>,
|
||||
|
||||
/// Clips whose thumbnail generation finished. Only complete sets are worth
|
||||
/// persisting — a partial set (saved mid-generation) is dropped so the load
|
||||
/// regenerates it fully rather than leaving it permanently incomplete.
|
||||
thumbnails_complete: std::collections::HashSet<Uuid>,
|
||||
|
||||
/// Maximum number of frames to cache per decoder
|
||||
cache_size: usize,
|
||||
}
|
||||
@@ -493,6 +505,7 @@ impl VideoManager {
|
||||
frame_cache: LruCache::unbounded(),
|
||||
frame_cache_bytes: 0,
|
||||
thumbnail_cache: HashMap::new(),
|
||||
thumbnails_complete: std::collections::HashSet::new(),
|
||||
cache_size,
|
||||
}
|
||||
}
|
||||
@@ -592,18 +605,57 @@ impl VideoManager {
|
||||
self.decoders.get(clip_id).cloned()
|
||||
}
|
||||
|
||||
/// Insert a thumbnail into the cache (for external thumbnail generation)
|
||||
pub fn insert_thumbnail(&mut self, clip_id: &Uuid, timestamp: f64, data: Arc<Vec<u8>>) {
|
||||
self.thumbnail_cache
|
||||
.entry(*clip_id)
|
||||
.or_insert_with(Vec::new)
|
||||
.push((timestamp, data));
|
||||
/// Snapshot all cached thumbnails for persistence (clip id -> sorted
|
||||
/// (timestamp, rgba) pairs). Cheap: clones the `Arc`s, not the pixel data.
|
||||
/// Partial sets are persisted too — pair with [`complete_thumbnail_clips`] so
|
||||
/// the load knows which clips still need generation resumed.
|
||||
pub fn snapshot_all_thumbnails(&self) -> HashMap<Uuid, Vec<(f64, Arc<Vec<u8>>)>> {
|
||||
self.thumbnail_cache.clone()
|
||||
}
|
||||
|
||||
/// Get the thumbnail closest to the specified timestamp
|
||||
/// The set of clips whose thumbnail generation has finished (a full keyframe
|
||||
/// pass). A persisted set flagged incomplete is resumed on load.
|
||||
pub fn complete_thumbnail_clips(&self) -> std::collections::HashSet<Uuid> {
|
||||
self.thumbnails_complete.clone()
|
||||
}
|
||||
|
||||
/// Mark a clip's thumbnail generation as complete (called when the background
|
||||
/// generator finishes the full keyframe pass).
|
||||
pub fn mark_thumbnails_complete(&mut self, clip_id: &Uuid) {
|
||||
self.thumbnails_complete.insert(*clip_id);
|
||||
}
|
||||
|
||||
/// Whether the clip already has a thumbnail within `tol` seconds of `ts`.
|
||||
/// Lets the generator skip keyframes already covered (resume / dedup).
|
||||
pub fn has_thumbnail_near(&self, clip_id: &Uuid, ts: f64, tol: f64) -> bool {
|
||||
self.thumbnail_cache
|
||||
.get(clip_id)
|
||||
.map_or(false, |v| v.iter().any(|(t, _)| (t - ts).abs() < tol))
|
||||
}
|
||||
|
||||
/// Insert a thumbnail into the cache, keeping it **sorted by timestamp** and
|
||||
/// **deduped** (an existing entry at the same timestamp is replaced). Sorted
|
||||
/// order is required by `get_thumbnail_at`'s binary search, and dedup makes
|
||||
/// concurrent restore + resumed generation idempotent (no double inserts).
|
||||
pub fn insert_thumbnail(&mut self, clip_id: &Uuid, timestamp: f64, data: Arc<Vec<u8>>) {
|
||||
let vec = self.thumbnail_cache.entry(*clip_id).or_default();
|
||||
match vec.binary_search_by(|(t, _)| {
|
||||
t.partial_cmp(×tamp).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}) {
|
||||
Ok(i) => vec[i] = (timestamp, data),
|
||||
Err(i) => vec.insert(i, (timestamp, data)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the thumbnail closest to the specified timestamp.
|
||||
///
|
||||
/// Returns `(actual_timestamp, width, height, data)` — `actual_timestamp` is
|
||||
/// the time of the thumbnail actually chosen (which may differ from the
|
||||
/// requested `timestamp`, and changes as closer thumbnails finish generating).
|
||||
/// Callers key their GPU texture cache on it so the on-clip strip refreshes as
|
||||
/// better thumbnails load instead of freezing on the first one.
|
||||
/// Returns None if no thumbnails have been generated for this clip.
|
||||
pub fn get_thumbnail_at(&self, clip_id: &Uuid, timestamp: f64) -> Option<(u32, u32, Arc<Vec<u8>>)> {
|
||||
pub fn get_thumbnail_at(&self, clip_id: &Uuid, timestamp: f64) -> Option<(f64, u32, u32, Arc<Vec<u8>>)> {
|
||||
let thumbnails = self.thumbnail_cache.get(clip_id)?;
|
||||
|
||||
if thumbnails.is_empty() {
|
||||
@@ -631,14 +683,14 @@ impl VideoManager {
|
||||
}
|
||||
});
|
||||
|
||||
let (_, rgba_data) = &thumbnails[idx];
|
||||
let (actual_ts, rgba_data) = &thumbnails[idx];
|
||||
|
||||
// Return (width, height, data)
|
||||
// Return (actual_timestamp, width, height, data)
|
||||
// Thumbnails are always 128px width
|
||||
let thumb_width = 128;
|
||||
let thumb_height = (rgba_data.len() / (thumb_width * 4)) as u32;
|
||||
|
||||
Some((thumb_width as u32, thumb_height, Arc::clone(rgba_data)))
|
||||
Some((*actual_ts, thumb_width as u32, thumb_height, Arc::clone(rgba_data)))
|
||||
}
|
||||
|
||||
/// Remove a video clip and its cached data
|
||||
@@ -661,6 +713,7 @@ impl VideoManager {
|
||||
|
||||
// Remove thumbnails
|
||||
self.thumbnail_cache.remove(clip_id);
|
||||
self.thumbnails_complete.remove(clip_id);
|
||||
}
|
||||
|
||||
/// Clear all frame caches (useful for memory management)
|
||||
|
||||
Reference in New Issue
Block a user