Pack video into .beam and stream frames + audio from the blob
Video was the only media type always kept external (VideoClip.file_path),
so a project with video wasn't self-contained. Now video packs into the
SQLite container under the same large-media policy as audio (pack < 2 GB
unless the user chose Reference), and both the frames and the embedded audio
track decode by streaming directly from the blob — no temp files.
- New crate ffmpeg-blob-io: an AVIOContext-over-Read+Seek shim (BlobInput)
that lets ffmpeg demux from an arbitrary byte source. Isolates all the
unsafe FFI + ffmpeg ABI coupling (version-pinned =8.0.0/=8.0.1). Manual
Drop teardown order; AVSEEK_SIZE restores the read position (FFmpeg assumes
a size query doesn't move it — required for MP4 moov-at-end).
- Schema/save/load: VideoClip.media_id; save_beam packs/references video as
MediaKind::Video (keyed by clip id); load resolves packed vs referenced and
reports missing sources. A packed clip points its linked video-audio pool
entry's media_id at the video row so the audio streams from the same blob.
- Frames: video.rs VideoSource{Path,Packed} threaded through new/seek/scan/
probe/thumbnails (a fresh BlobReader per open); editor builds the source
from current_file_path (now set before register_loaded_videos).
- Audio: VideoAudioReader::open_source via BlobInput; the disk_reader
StreamSource block on packed video-audio is removed; the engine's existing
factory activation routes it unchanged.
Tests: ffmpeg-blob-io AVIO unit tests (WAV via Cursor, seek, open/drop loop);
core packed_video_stream (blob->AVIO->Input) and beam_archive video round-trip;
daw-backend open_source test (compiles; links/runs only off-container).
Runtime-verified: a packed video plays frames + audio after the source file
is removed.
This commit is contained in:
Generated
+12
-1
@@ -1682,6 +1682,7 @@ dependencies = [
|
||||
"dasp_rms",
|
||||
"dasp_sample",
|
||||
"dasp_signal",
|
||||
"ffmpeg-blob-io",
|
||||
"ffmpeg-next",
|
||||
"hound",
|
||||
"memmap2",
|
||||
@@ -2218,6 +2219,15 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-blob-io"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ffmpeg-next",
|
||||
"ffmpeg-sys-next",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-next"
|
||||
version = "8.0.0"
|
||||
@@ -3480,6 +3490,7 @@ dependencies = [
|
||||
"claxon",
|
||||
"daw-backend",
|
||||
"egui",
|
||||
"ffmpeg-blob-io",
|
||||
"ffmpeg-next",
|
||||
"flacenc",
|
||||
"image",
|
||||
@@ -3505,7 +3516,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightningbeam-editor"
|
||||
version = "1.0.4-alpha"
|
||||
version = "1.0.5-alpha"
|
||||
dependencies = [
|
||||
"beamdsp",
|
||||
"bytemuck",
|
||||
|
||||
@@ -29,6 +29,8 @@ daw-backend = { path = "../../daw-backend" }
|
||||
|
||||
# Video decoding
|
||||
ffmpeg-next = "8.0"
|
||||
# AVIO-over-Read+Seek shim: decode packed video by streaming from the SQLite blob.
|
||||
ffmpeg-blob-io = { path = "../../ffmpeg-blob-io" }
|
||||
lru = "0.12"
|
||||
|
||||
# File I/O
|
||||
@@ -73,3 +75,6 @@ windows-sys = { version = "0.60", features = [
|
||||
version = "0.11"
|
||||
|
||||
[dev-dependencies]
|
||||
# For the packed-video streaming integration test (blob -> AVIO -> ffmpeg Input).
|
||||
ffmpeg-blob-io = { path = "../../ffmpeg-blob-io" }
|
||||
ffmpeg-next = "8.0"
|
||||
|
||||
@@ -343,6 +343,13 @@ pub struct VideoClip {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub linked_audio_clip_id: Option<Uuid>,
|
||||
|
||||
/// When set, the video bytes are packed into the `.beam` container under this
|
||||
/// media id (== the clip id) and decoded by streaming from the SQLite blob.
|
||||
/// `None` means the video is referenced externally via [`Self::file_path`].
|
||||
/// Reconstructed from the archive on load (see `load_beam_sqlite`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub media_id: Option<Uuid>,
|
||||
|
||||
/// Folder this clip belongs to (None = root of category)
|
||||
#[serde(default)]
|
||||
pub folder_id: Option<Uuid>,
|
||||
@@ -367,6 +374,7 @@ impl VideoClip {
|
||||
duration,
|
||||
frame_rate,
|
||||
linked_audio_clip_id: None,
|
||||
media_id: None,
|
||||
folder_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! too (via [`load_beam_zip_legacy`]). Saving always writes the SQLite form, so
|
||||
//! opening a legacy file and saving migrates it.
|
||||
|
||||
use crate::beam_archive::{BeamArchive, MediaKind, MediaMeta, LARGE_MEDIA_THRESHOLD};
|
||||
use crate::beam_archive::{BeamArchive, MediaKind, MediaMeta, MediaStorage, LARGE_MEDIA_THRESHOLD};
|
||||
use crate::document::Document;
|
||||
use daw_backend::audio::pool::AudioPoolEntry;
|
||||
use daw_backend::audio::project::Project as AudioProject;
|
||||
@@ -450,6 +450,65 @@ pub fn save_beam(
|
||||
}
|
||||
}
|
||||
|
||||
// --- video clips -> media rows (Video bytes), keyed by the clip id ---
|
||||
// Mirror the audio pack/reference decision: pack unless the file is
|
||||
// >= LARGE_MEDIA_THRESHOLD and the user didn't choose Pack. Packed video is
|
||||
// decoded by streaming from the blob (see video.rs `VideoSource` + ffmpeg-blob-io).
|
||||
for (clip_id, clip) in &document.video_clips {
|
||||
// In-place re-save: an unchanged packed video keeps its row, never re-streamed.
|
||||
if clip.media_id == Some(*clip_id) && txn.media_exists(*clip_id)? {
|
||||
live_media.insert(*clip_id);
|
||||
continue;
|
||||
}
|
||||
if clip.file_path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let full = if Path::new(&clip.file_path).is_absolute() {
|
||||
PathBuf::from(&clip.file_path)
|
||||
} else {
|
||||
project_dir.join(&clip.file_path)
|
||||
};
|
||||
if !full.is_file() {
|
||||
continue; // source gone — reported missing on load
|
||||
}
|
||||
let size = std::fs::metadata(&full).map(|m| m.len()).unwrap_or(0);
|
||||
let codec = full
|
||||
.extension()
|
||||
.and_then(|x| x.to_str())
|
||||
.unwrap_or("mp4")
|
||||
.to_lowercase();
|
||||
let meta = MediaMeta {
|
||||
width: Some(clip.width as u32),
|
||||
height: Some(clip.height as u32),
|
||||
..Default::default()
|
||||
};
|
||||
let reference_it =
|
||||
size >= LARGE_MEDIA_THRESHOLD && settings.large_media_mode != LargeMediaMode::Pack;
|
||||
if reference_it {
|
||||
txn.put_media_referenced(*clip_id, MediaKind::Video, &codec, &clip.file_path, meta)?;
|
||||
} else {
|
||||
txn.put_media_packed_from_path(*clip_id, MediaKind::Video, &codec, &full, meta)?;
|
||||
// The video's audio track lives in this same blob. Point the linked
|
||||
// video-audio pool entry at the video's media row so its audio streams
|
||||
// from the blob too (instead of re-probing the external file on load).
|
||||
if let Some(aid) = clip.linked_audio_clip_id {
|
||||
if let Some(crate::clip::AudioClipType::Sampled { audio_pool_index }) =
|
||||
document.audio_clips.get(&aid).map(|c| &c.clip_type)
|
||||
{
|
||||
if let Some(e) = modified_entries
|
||||
.iter_mut()
|
||||
.find(|e| e.pool_index == *audio_pool_index)
|
||||
{
|
||||
e.media_id = Some(clip_id.to_string());
|
||||
e.relative_path = None;
|
||||
e.embedded_data = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
live_media.insert(*clip_id);
|
||||
}
|
||||
|
||||
// --- image assets -> media rows (original file bytes), keyed by asset id ---
|
||||
let mut image_count = 0usize;
|
||||
for (id, asset) in &document.image_assets {
|
||||
@@ -646,7 +705,7 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
|
||||
// Missing external files (referenced entries whose file no longer exists).
|
||||
let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
let missing_files: Vec<MissingFileInfo> = restored_entries
|
||||
let mut missing_files: Vec<MissingFileInfo> = restored_entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, entry)| {
|
||||
@@ -670,6 +729,42 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Resolve packed/referenced video bytes per clip (mirrors audio resolution).
|
||||
// A `MediaKind::Video` row keyed by the clip id means the bytes are in the
|
||||
// container; the decoder streams from the blob. Referenced rows update the
|
||||
// external path and report a missing source. Old projects (no Video row) stay
|
||||
// referenced via their existing `file_path`.
|
||||
for (clip_id, clip) in document.video_clips.iter_mut() {
|
||||
match archive.media_info(*clip_id) {
|
||||
Ok(Some(info)) if info.kind == MediaKind::Video => match info.storage {
|
||||
MediaStorage::Packed => {
|
||||
clip.media_id = Some(*clip_id);
|
||||
}
|
||||
MediaStorage::Referenced => {
|
||||
clip.media_id = None;
|
||||
if let Some(p) = info.ext_path.clone() {
|
||||
clip.file_path = p;
|
||||
}
|
||||
let full = if Path::new(&clip.file_path).is_absolute() {
|
||||
PathBuf::from(&clip.file_path)
|
||||
} else {
|
||||
project_dir.join(&clip.file_path)
|
||||
};
|
||||
if !clip.file_path.is_empty() && !full.exists() {
|
||||
missing_files.push(MissingFileInfo {
|
||||
pool_index: 0,
|
||||
original_path: full,
|
||||
file_type: MediaFileType::Video,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
clip.media_id = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
@@ -6,10 +6,71 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::num::NonZeroUsize;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use ffmpeg_next as ffmpeg;
|
||||
use ffmpeg_blob_io::BlobInput;
|
||||
use lru::LruCache;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::beam_archive::BeamArchive;
|
||||
|
||||
/// Where a video clip's bytes live.
|
||||
///
|
||||
/// `Path` is an external file (referenced video, webcam capture, fresh import).
|
||||
/// `Packed` streams from a `MediaKind::Video` blob inside the `.beam` container.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum VideoSource {
|
||||
/// External file path.
|
||||
Path(String),
|
||||
/// Packed in the container: open a fresh `BlobReader` over `media_id` in `db_path`.
|
||||
Packed { db_path: PathBuf, media_id: Uuid },
|
||||
}
|
||||
|
||||
impl VideoSource {
|
||||
/// Open a fresh demuxer input for this source. A new `BlobReader` (own SQLite
|
||||
/// connection) is created per call, so this is safe to call on any thread and
|
||||
/// on every seek-reopen.
|
||||
fn open(&self) -> Result<OwnedInput, String> {
|
||||
match self {
|
||||
VideoSource::Path(p) => ffmpeg::format::input(p)
|
||||
.map(OwnedInput::Path)
|
||||
.map_err(|e| format!("Failed to open video: {}", e)),
|
||||
VideoSource::Packed { db_path, media_id } => {
|
||||
let archive = BeamArchive::open(db_path)?;
|
||||
let hint = archive.media_info(*media_id)?.map(|i| i.codec);
|
||||
let reader = archive.open_blob_reader(db_path, *media_id)?;
|
||||
BlobInput::open(Box::new(reader), hint.as_deref())
|
||||
.map(OwnedInput::Blob)
|
||||
.map_err(|e| format!("Failed to open packed video: {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Short label for logging.
|
||||
fn label(&self) -> String {
|
||||
match self {
|
||||
VideoSource::Path(p) => p.clone(),
|
||||
VideoSource::Packed { media_id, .. } => format!("packed:{}", media_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An open demuxer input, either file-backed or streaming from a container blob.
|
||||
/// Both expose the same `ffmpeg` `Input` for decoding.
|
||||
enum OwnedInput {
|
||||
Path(ffmpeg::format::context::Input),
|
||||
Blob(BlobInput),
|
||||
}
|
||||
|
||||
impl OwnedInput {
|
||||
fn get(&mut self) -> &mut ffmpeg::format::context::Input {
|
||||
match self {
|
||||
OwnedInput::Path(i) => i,
|
||||
OwnedInput::Blob(b) => b.input_mut(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata about a video file
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VideoMetadata {
|
||||
@@ -22,7 +83,7 @@ pub struct VideoMetadata {
|
||||
|
||||
/// Video decoder with LRU frame caching
|
||||
pub struct VideoDecoder {
|
||||
path: String,
|
||||
source: VideoSource,
|
||||
_width: u32, // Original video width
|
||||
_height: u32, // Original video height
|
||||
output_width: u32, // Scaled output width
|
||||
@@ -32,7 +93,7 @@ pub struct VideoDecoder {
|
||||
time_base: f64,
|
||||
stream_index: usize,
|
||||
frame_cache: LruCache<i64, Vec<u8>>, // timestamp -> RGBA data
|
||||
input: Option<ffmpeg::format::context::Input>,
|
||||
input: Option<OwnedInput>,
|
||||
decoder: Option<ffmpeg::decoder::Video>,
|
||||
last_decoded_ts: i64, // Track the last decoded frame timestamp
|
||||
keyframe_positions: Vec<i64>, // Index of keyframe timestamps for fast seeking
|
||||
@@ -45,11 +106,11 @@ impl VideoDecoder {
|
||||
/// Video will be scaled down if larger, preserving aspect ratio.
|
||||
/// `build_keyframes` controls whether to build the keyframe index immediately (slow)
|
||||
/// or defer it for async building later.
|
||||
fn new(path: String, cache_size: usize, max_width: Option<u32>, max_height: Option<u32>, build_keyframes: bool) -> Result<Self, String> {
|
||||
fn new(source: VideoSource, cache_size: usize, max_width: Option<u32>, max_height: Option<u32>, build_keyframes: bool) -> Result<Self, String> {
|
||||
ffmpeg::init().map_err(|e| e.to_string())?;
|
||||
|
||||
let input = ffmpeg::format::input(&path)
|
||||
.map_err(|e| format!("Failed to open video: {}", e))?;
|
||||
let mut owned = source.open()?;
|
||||
let input = owned.get();
|
||||
|
||||
let video_stream = input.streams()
|
||||
.best(ffmpeg::media::Type::Video)
|
||||
@@ -96,17 +157,17 @@ impl VideoDecoder {
|
||||
|
||||
// Optionally build keyframe index for fast seeking
|
||||
let keyframe_positions = if build_keyframes {
|
||||
eprintln!("[Video Decoder] Building keyframe index for {}", path);
|
||||
let positions = Self::scan_keyframes(&path, stream_index)?;
|
||||
eprintln!("[Video Decoder] Building keyframe index for {}", source.label());
|
||||
let positions = Self::scan_keyframes(&source, stream_index)?;
|
||||
eprintln!("[Video Decoder] Found {} keyframes", positions.len());
|
||||
positions
|
||||
} else {
|
||||
eprintln!("[Video Decoder] Deferring keyframe index building for {}", path);
|
||||
eprintln!("[Video Decoder] Deferring keyframe index building for {}", source.label());
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
path,
|
||||
source,
|
||||
_width: width,
|
||||
_height: height,
|
||||
output_width,
|
||||
@@ -125,14 +186,14 @@ impl VideoDecoder {
|
||||
})
|
||||
}
|
||||
|
||||
/// Source file path this decoder reads from.
|
||||
pub fn path(&self) -> &str {
|
||||
&self.path
|
||||
/// The source this decoder reads from (file path or packed container blob).
|
||||
pub fn source(&self) -> VideoSource {
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
/// Parameters needed to scan keyframes off-thread (path + video stream index).
|
||||
pub fn keyframe_scan_params(&self) -> (String, usize) {
|
||||
(self.path.clone(), self.stream_index)
|
||||
/// Parameters needed to scan keyframes off-thread (source + video stream index).
|
||||
pub fn keyframe_scan_params(&self) -> (VideoSource, usize) {
|
||||
(self.source.clone(), self.stream_index)
|
||||
}
|
||||
|
||||
/// Replace the keyframe index (built off-thread via [`VideoDecoder::scan_keyframes`]).
|
||||
@@ -158,9 +219,10 @@ impl VideoDecoder {
|
||||
/// Build an index of all keyframe positions in the video by scanning packets
|
||||
/// from a fresh input. Does not touch `self` — call it off-thread (it is slow
|
||||
/// on long videos) and hand the result to [`VideoDecoder::set_keyframe_index`].
|
||||
pub fn scan_keyframes(path: &str, stream_index: usize) -> Result<Vec<i64>, String> {
|
||||
let mut input = ffmpeg::format::input(path)
|
||||
pub fn scan_keyframes(source: &VideoSource, stream_index: usize) -> Result<Vec<i64>, String> {
|
||||
let mut owned = source.open()
|
||||
.map_err(|e| format!("Failed to open video for indexing: {}", e))?;
|
||||
let input = owned.get();
|
||||
|
||||
let mut keyframes = Vec::new();
|
||||
|
||||
@@ -233,32 +295,34 @@ impl VideoDecoder {
|
||||
eprintln!("[Video Seek] Target: {} | Keyframe(stream): {} | Keyframe(AV): {} | Index size: {}",
|
||||
frame_ts, keyframe_ts_stream, keyframe_ts_av, self.keyframe_positions.len());
|
||||
|
||||
// Reopen input
|
||||
let mut input = ffmpeg::format::input(&self.path)
|
||||
// Reopen input (a fresh BlobReader for packed sources).
|
||||
let mut owned = self.source.open()
|
||||
.map_err(|e| format!("Failed to reopen video: {}", e))?;
|
||||
|
||||
// Seek directly to the keyframe with a 1-unit window
|
||||
// Can't use keyframe_ts..keyframe_ts (empty) or ..= (not supported)
|
||||
input.seek(keyframe_ts_av, keyframe_ts_av..(keyframe_ts_av + 1))
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
{
|
||||
let input = owned.get();
|
||||
// Seek directly to the keyframe with a 1-unit window
|
||||
// Can't use keyframe_ts..keyframe_ts (empty) or ..= (not supported)
|
||||
input.seek(keyframe_ts_av, keyframe_ts_av..(keyframe_ts_av + 1))
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
|
||||
eprintln!("[Video Timing] Seek call took {}ms", t_seek_start.elapsed().as_millis());
|
||||
eprintln!("[Video Timing] Seek call took {}ms", t_seek_start.elapsed().as_millis());
|
||||
|
||||
let context_decoder = ffmpeg::codec::context::Context::from_parameters(
|
||||
input.streams().best(ffmpeg::media::Type::Video).unwrap().parameters()
|
||||
).map_err(|e| e.to_string())?;
|
||||
let context_decoder = ffmpeg::codec::context::Context::from_parameters(
|
||||
input.streams().best(ffmpeg::media::Type::Video).unwrap().parameters()
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
let decoder = context_decoder.decoder().video()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
self.input = Some(input);
|
||||
self.decoder = Some(decoder);
|
||||
let decoder = context_decoder.decoder().video()
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.decoder = Some(decoder);
|
||||
}
|
||||
self.input = Some(owned);
|
||||
// Set last_decoded_ts to just before the seek target so forward playback works
|
||||
// Without this, every frame would trigger a new seek
|
||||
self.last_decoded_ts = frame_ts - 1;
|
||||
}
|
||||
|
||||
let input = self.input.as_mut().unwrap();
|
||||
let input = self.input.as_mut().unwrap().get();
|
||||
let decoder = self.decoder.as_mut().unwrap();
|
||||
|
||||
// Decode frames until we find the one closest to our target timestamp
|
||||
@@ -356,7 +420,7 @@ impl VideoDecoder {
|
||||
/// `get_thumbnail_at`'s 128-wide assumption holds) and tightly packed RGBA is
|
||||
/// handed to `on_thumb` as `(timestamp_secs, data)`.
|
||||
pub fn generate_keyframe_thumbnails(
|
||||
path: &str,
|
||||
source: VideoSource,
|
||||
interval_secs: f64,
|
||||
thumb_width: u32,
|
||||
mut should_skip: impl FnMut(f64) -> bool,
|
||||
@@ -366,7 +430,7 @@ pub fn generate_keyframe_thumbnails(
|
||||
// large max-height lets width be the constraining dimension, so output width
|
||||
// is exactly `thumb_width`.
|
||||
let mut decoder = VideoDecoder::new(
|
||||
path.to_string(),
|
||||
source,
|
||||
4,
|
||||
Some(thumb_width),
|
||||
Some(100_000),
|
||||
@@ -399,11 +463,11 @@ pub fn generate_keyframe_thumbnails(
|
||||
}
|
||||
|
||||
/// Probe video file for metadata without creating a full decoder
|
||||
pub fn probe_video(path: &str) -> Result<VideoMetadata, String> {
|
||||
pub fn probe_video(source: &VideoSource) -> Result<VideoMetadata, String> {
|
||||
ffmpeg::init().map_err(|e| e.to_string())?;
|
||||
|
||||
let input = ffmpeg::format::input(path)
|
||||
.map_err(|e| format!("Failed to open video: {}", e))?;
|
||||
let mut owned = source.open()?;
|
||||
let input = owned.get();
|
||||
|
||||
let video_stream = input.streams()
|
||||
.best(ffmpeg::media::Type::Video)
|
||||
@@ -521,16 +585,16 @@ impl VideoManager {
|
||||
pub fn load_video(
|
||||
&mut self,
|
||||
clip_id: Uuid,
|
||||
path: String,
|
||||
source: VideoSource,
|
||||
target_width: u32,
|
||||
target_height: u32,
|
||||
) -> Result<VideoMetadata, String> {
|
||||
// First probe the video for metadata
|
||||
let metadata = probe_video(&path)?;
|
||||
let metadata = probe_video(&source)?;
|
||||
|
||||
// Create decoder with target dimensions, without building keyframe index
|
||||
let decoder = VideoDecoder::new(
|
||||
path,
|
||||
source,
|
||||
self.cache_size,
|
||||
Some(target_width),
|
||||
Some(target_height),
|
||||
|
||||
@@ -205,3 +205,51 @@ fn overwrite_media_replaces_chunks() {
|
||||
assert_eq!(archive.read_media_full(id).unwrap(), vec![2u8; 50]);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_video_from_path_roundtrips() {
|
||||
// Simulates the save path: stream a video file into a MediaKind::Video blob,
|
||||
// then read it back (frames/audio decode would open this via the AVIO shim).
|
||||
let path = temp_db_path("video_pack");
|
||||
let mut src = std::env::temp_dir();
|
||||
src.push(format!("beam_video_src_{}.mp4", std::process::id()));
|
||||
let bytes: Vec<u8> = (0..(9 * 1024 * 1024u32)).map(|i| (i % 251) as u8).collect();
|
||||
std::fs::write(&src, &bytes).unwrap();
|
||||
|
||||
let id = Uuid::new_v4();
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
{
|
||||
let txn = archive.transaction().unwrap();
|
||||
txn.put_media_packed_from_path(
|
||||
id,
|
||||
MediaKind::Video,
|
||||
"mp4",
|
||||
&src,
|
||||
MediaMeta { width: Some(1920), height: Some(1080), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
txn.commit().unwrap();
|
||||
}
|
||||
|
||||
let info = archive.media_info(id).unwrap().expect("video media row");
|
||||
assert_eq!(info.kind, MediaKind::Video);
|
||||
assert_eq!(info.storage, MediaStorage::Packed);
|
||||
assert_eq!(info.codec, "mp4");
|
||||
assert_eq!(info.total_len, bytes.len() as u64);
|
||||
assert_eq!(info.width, Some(1920));
|
||||
assert_eq!(info.height, Some(1080));
|
||||
assert_eq!(archive.read_media_full(id).unwrap(), bytes);
|
||||
|
||||
// Streaming read mirrors how the decoder pulls bytes via its BlobReader.
|
||||
let mut reader = archive.open_blob_reader(&path, id).unwrap();
|
||||
let mut streamed = Vec::new();
|
||||
reader.read_to_end(&mut streamed).unwrap();
|
||||
assert_eq!(streamed, bytes);
|
||||
reader.seek(SeekFrom::Start(5 * 1024 * 1024)).unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
reader.read_exact(&mut buf).unwrap();
|
||||
assert_eq!(buf[0], ((5 * 1024 * 1024u32) % 251) as u8);
|
||||
|
||||
let _ = std::fs::remove_file(&src);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Integration test for the packed-video streaming path:
|
||||
//! SQLite `MediaKind::Video` blob -> `BlobReader` -> `ffmpeg-blob-io` AVIO shim ->
|
||||
//! ffmpeg `Input`. This is exactly what `video.rs`'s `VideoSource::Packed` does to
|
||||
//! decode frames (and what `daw-backend` does for the embedded audio), minus the
|
||||
//! thin wrapper. We use a hand-built WAV as the packed container — FFmpeg must
|
||||
//! demux it through our blob reader, proving the production byte path end to end.
|
||||
//!
|
||||
//! (Decoding real video frames is left to user runtime verification; here we prove
|
||||
//! the container streams from the blob and exposes its streams.)
|
||||
|
||||
use ffmpeg_blob_io::BlobInput;
|
||||
use lightningbeam_core::beam_archive::{BeamArchive, MediaKind, MediaMeta, MediaStorage};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use uuid::Uuid;
|
||||
|
||||
fn temp_db_path(tag: &str) -> std::path::PathBuf {
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed);
|
||||
let mut p = std::env::temp_dir();
|
||||
p.push(format!("packed_video_it_{}_{}_{}.beam", std::process::id(), tag, n));
|
||||
let _ = std::fs::remove_file(&p);
|
||||
p
|
||||
}
|
||||
|
||||
/// Minimal 16-bit PCM WAV (a real, demuxable container).
|
||||
fn make_wav(sample_rate: u32, channels: u16, samples: &[i16]) -> Vec<u8> {
|
||||
let bits: u16 = 16;
|
||||
let block_align: u16 = channels * (bits / 8);
|
||||
let byte_rate: u32 = sample_rate * block_align as u32;
|
||||
let data_len: u32 = (samples.len() * 2) as u32;
|
||||
let mut v = Vec::new();
|
||||
v.extend_from_slice(b"RIFF");
|
||||
v.extend_from_slice(&(36 + data_len).to_le_bytes());
|
||||
v.extend_from_slice(b"WAVE");
|
||||
v.extend_from_slice(b"fmt ");
|
||||
v.extend_from_slice(&16u32.to_le_bytes());
|
||||
v.extend_from_slice(&1u16.to_le_bytes());
|
||||
v.extend_from_slice(&channels.to_le_bytes());
|
||||
v.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
v.extend_from_slice(&byte_rate.to_le_bytes());
|
||||
v.extend_from_slice(&block_align.to_le_bytes());
|
||||
v.extend_from_slice(&bits.to_le_bytes());
|
||||
v.extend_from_slice(b"data");
|
||||
v.extend_from_slice(&data_len.to_le_bytes());
|
||||
for s in samples {
|
||||
v.extend_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_media_streams_through_avio_to_ffmpeg() {
|
||||
let path = temp_db_path("stream");
|
||||
let id = Uuid::new_v4();
|
||||
let samples: Vec<i16> = (0..4000).map(|i| ((i % 200) as i16 - 100) * 100).collect();
|
||||
let container = make_wav(8000, 1, &samples);
|
||||
|
||||
// Pack as a Video media row (the save path does this for real videos).
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
archive
|
||||
.put_media_packed(id, MediaKind::Video, "wav", &container, MediaMeta::default())
|
||||
.unwrap();
|
||||
let info = archive.media_info(id).unwrap().unwrap();
|
||||
assert_eq!(info.kind, MediaKind::Video);
|
||||
assert_eq!(info.storage, MediaStorage::Packed);
|
||||
drop(archive);
|
||||
|
||||
// Reproduce VideoSource::Packed::open(): fresh read-only archive + blob reader.
|
||||
let archive = BeamArchive::open(&path).unwrap();
|
||||
let hint = archive.media_info(id).unwrap().map(|i| i.codec);
|
||||
let reader = archive.open_blob_reader(&path, id).unwrap();
|
||||
|
||||
let input = BlobInput::open(Box::new(reader), hint.as_deref())
|
||||
.expect("open the packed container by streaming from the SQLite blob");
|
||||
assert!(
|
||||
input.streams().count() >= 1,
|
||||
"demuxer found streams via the blob-backed AVIO shim"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
@@ -4225,6 +4225,12 @@ impl EditorApp {
|
||||
});
|
||||
}
|
||||
|
||||
// Set the loaded container path BEFORE registering videos: a packed video
|
||||
// clip resolves to `VideoSource::Packed { db_path: current_file_path, .. }`,
|
||||
// so this must be in place or the clip falls back to its (possibly missing)
|
||||
// external file and renders black.
|
||||
self.current_file_path = Some(path.clone());
|
||||
|
||||
// Re-register video clips with the VideoManager (decoder + keyframe index +
|
||||
// thumbnails). Restored video_clips carry only metadata + file_path; without
|
||||
// this they render black with no thumbnails.
|
||||
@@ -4235,7 +4241,6 @@ impl EditorApp {
|
||||
// Reset playback state
|
||||
self.playback_time = 0.0;
|
||||
self.is_playing = false;
|
||||
self.current_file_path = Some(path.clone());
|
||||
// Point the raster paging store at the loaded container so faulting works.
|
||||
self.raster_store.set_path(self.current_file_path.clone());
|
||||
|
||||
@@ -4260,26 +4265,37 @@ impl EditorApp {
|
||||
let doc_width = self.action_executor.document().width as u32;
|
||||
let doc_height = self.action_executor.document().height as u32;
|
||||
|
||||
// Snapshot (id, path) so we don't hold the document borrow while locking
|
||||
// the VideoManager / spawning threads.
|
||||
// Snapshot (id, media_id, path) so we don't hold the document borrow while
|
||||
// locking the VideoManager / spawning threads.
|
||||
let db_path = self.current_file_path.clone();
|
||||
let videos: Vec<_> = self
|
||||
.action_executor
|
||||
.document()
|
||||
.video_clips
|
||||
.values()
|
||||
.map(|c| (c.id, c.file_path.clone()))
|
||||
.map(|c| (c.id, c.media_id, c.file_path.clone()))
|
||||
.collect();
|
||||
|
||||
for (clip_id, file_path) in videos {
|
||||
if !std::path::Path::new(&file_path).exists() {
|
||||
eprintln!("⚠️ [APPLY] Video file not found, skipping: {}", file_path);
|
||||
continue;
|
||||
}
|
||||
for (clip_id, media_id, file_path) in videos {
|
||||
// Packed video streams from the container blob; referenced video opens
|
||||
// its external file (skip if it's gone).
|
||||
let source = match (media_id, &db_path) {
|
||||
(Some(mid), Some(db)) => {
|
||||
lightningbeam_core::video::VideoSource::Packed { db_path: db.clone(), media_id: mid }
|
||||
}
|
||||
_ => {
|
||||
if !std::path::Path::new(&file_path).exists() {
|
||||
eprintln!("⚠️ [APPLY] Video file not found, skipping: {}", file_path);
|
||||
continue;
|
||||
}
|
||||
lightningbeam_core::video::VideoSource::Path(file_path.clone())
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
let mut video_mgr = self.video_manager.lock().unwrap();
|
||||
if let Err(e) = video_mgr.load_video(clip_id, file_path.clone(), doc_width, doc_height) {
|
||||
eprintln!("⚠️ [APPLY] Failed to load video {}: {}", file_path, e);
|
||||
if let Err(e) = video_mgr.load_video(clip_id, source, doc_width, doc_height) {
|
||||
eprintln!("⚠️ [APPLY] Failed to load video {}: {}", clip_id, e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -4308,13 +4324,13 @@ impl EditorApp {
|
||||
};
|
||||
let Some(decoder_arc) = decoder_arc else { return; };
|
||||
|
||||
let (path, stream_index) = {
|
||||
let (source, stream_index) = {
|
||||
let decoder = decoder_arc.lock().unwrap();
|
||||
decoder.keyframe_scan_params()
|
||||
};
|
||||
|
||||
// Slow scan, no locks held.
|
||||
match lightningbeam_core::video::VideoDecoder::scan_keyframes(&path, stream_index) {
|
||||
match lightningbeam_core::video::VideoDecoder::scan_keyframes(&source, stream_index) {
|
||||
Ok(positions) => {
|
||||
let count = positions.len();
|
||||
decoder_arc.lock().unwrap().set_keyframe_index(positions);
|
||||
@@ -4333,22 +4349,22 @@ impl EditorApp {
|
||||
fn spawn_thumbnail_generation(&self, clip_id: uuid::Uuid) {
|
||||
let video_manager = Arc::clone(&self.video_manager);
|
||||
std::thread::spawn(move || {
|
||||
// Grab the source path from the playback decoder (brief lock), then do
|
||||
// all decoding on an independent decoder.
|
||||
let path = {
|
||||
// Grab the source from the playback decoder (brief lock), then do all
|
||||
// decoding on an independent decoder (a fresh BlobReader for packed video).
|
||||
let source = {
|
||||
let decoder_arc = {
|
||||
let vm = video_manager.lock().unwrap();
|
||||
vm.get_decoder(&clip_id)
|
||||
};
|
||||
let Some(decoder_arc) = decoder_arc else { return; };
|
||||
let decoder = decoder_arc.lock().unwrap();
|
||||
decoder.path().to_string()
|
||||
decoder.source()
|
||||
};
|
||||
|
||||
let vm_insert = Arc::clone(&video_manager);
|
||||
let vm_skip = Arc::clone(&video_manager);
|
||||
let result = lightningbeam_core::video::generate_keyframe_thumbnails(
|
||||
&path,
|
||||
source,
|
||||
5.0,
|
||||
128,
|
||||
// Resume: skip keyframes already covered (e.g. restored from a
|
||||
@@ -4624,8 +4640,9 @@ impl EditorApp {
|
||||
|
||||
let path_str = path.to_string_lossy().to_string();
|
||||
|
||||
// Probe video for metadata
|
||||
let metadata = match probe_video(&path_str) {
|
||||
// Probe video for metadata (freshly imported video is referenced until the
|
||||
// first save packs it).
|
||||
let metadata = match probe_video(&lightningbeam_core::video::VideoSource::Path(path_str.clone())) {
|
||||
Ok(meta) => meta,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to probe video '{}': {}", name, e);
|
||||
@@ -4650,7 +4667,12 @@ impl EditorApp {
|
||||
let doc_height = self.action_executor.document().height as u32;
|
||||
|
||||
let mut video_mgr = self.video_manager.lock().unwrap();
|
||||
if let Err(e) = video_mgr.load_video(clip_id, path_str.clone(), doc_width, doc_height) {
|
||||
if let Err(e) = video_mgr.load_video(
|
||||
clip_id,
|
||||
lightningbeam_core::video::VideoSource::Path(path_str.clone()),
|
||||
doc_width,
|
||||
doc_height,
|
||||
) {
|
||||
eprintln!("Failed to load video '{}': {}", name, e);
|
||||
return None;
|
||||
}
|
||||
@@ -6670,7 +6692,7 @@ impl eframe::App for EditorApp {
|
||||
eprintln!("[WEBCAM] Recording saved to: {} (recorder duration={:.4}s)", file_path_str, result.duration);
|
||||
// Create VideoClip + ClipInstance from recorded file
|
||||
if let Some(layer_id) = webcam_layer_id {
|
||||
match lightningbeam_core::video::probe_video(&file_path_str) {
|
||||
match lightningbeam_core::video::probe_video(&lightningbeam_core::video::VideoSource::Path(file_path_str.clone())) {
|
||||
Ok(info) => {
|
||||
use lightningbeam_core::clip::{VideoClip, ClipInstance};
|
||||
let clip = VideoClip {
|
||||
@@ -6685,6 +6707,7 @@ impl eframe::App for EditorApp {
|
||||
duration: info.duration,
|
||||
frame_rate: info.fps,
|
||||
linked_audio_clip_id: None,
|
||||
media_id: None,
|
||||
folder_id: None,
|
||||
};
|
||||
let clip_id = clip.id;
|
||||
@@ -6723,7 +6746,7 @@ impl eframe::App for EditorApp {
|
||||
// for the display rect.
|
||||
{
|
||||
let mut vm = self.video_manager.lock().unwrap();
|
||||
if let Err(e) = vm.load_video(clip_id, file_path_str, info.width, info.height) {
|
||||
if let Err(e) = vm.load_video(clip_id, lightningbeam_core::video::VideoSource::Path(file_path_str.clone()), info.width, info.height) {
|
||||
eprintln!("[WEBCAM] Failed to load recorded video: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user