Stream audio & video from .beam container; waveform LOD pyramid + persistence
Migrate the .beam container to SQLite and stream media from it instead of decoding whole files into RAM on import/load. Container & large files: - SQLite .beam container (beam_archive) with in-place transactional saves and an incremental BlobReader; supports both packed (chunked blobs) and referenced (external path) media, with a user preference + first-import prompt for files over the large-media threshold. Audio streaming: - Stream packed compressed audio on load via an inversion-of-control blob factory (AudioBlobSourceFactory): daw-backend defines the trait, core implements it over BlobReader, so the audio engine stays container-agnostic. - Bulk-activate disk streaming for all loaded clips after SetProject. - Sample-accurate compressed seek (SeekMode::Accurate; Coarse mislands on VBR). Video: - Video frames decoded/streamed on demand; thumbnails generated asynchronously on a dedicated decoder so import/load never blocks the UI. - The video's audio track is streamed on demand via an ffmpeg VideoAudioReader as a separate editable AudioClip (no /tmp WAV extraction). Waveform overview: - Streaming min/max LOD pyramid (waveform_pyramid), bounded memory, configurable floor B; serialized into the container and restored on load (or generated in the background from the packed blob when absent), so no re-decode on reload. - GPU min/max upload path; integer-LOD textureLoad fixes zoom-dependent wobble.
This commit is contained in:
@@ -36,6 +36,9 @@ zip = "0.6"
|
||||
chrono = "0.4"
|
||||
base64 = "0.21"
|
||||
pathdiff = "0.2"
|
||||
# .beam container: SQLite database file. `bundled` compiles SQLite from source
|
||||
# (no system dependency); `blob` enables incremental blob I/O for streaming.
|
||||
rusqlite = { version = "0.31", features = ["bundled", "blob"] }
|
||||
|
||||
# Audio encoding for embedded files
|
||||
flacenc = "0.4" # For FLAC encoding (lossless)
|
||||
|
||||
@@ -235,11 +235,22 @@ impl Action for AddClipInstanceAction {
|
||||
}
|
||||
}
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
// `trim_*` / `clip.duration` are in SECONDS (audio content time),
|
||||
// while `timeline_*` and the backend's `duration` are in BEATS.
|
||||
let internal_start = self.clip_instance.trim_start;
|
||||
let internal_end = self.clip_instance.trim_end.unwrap_or(clip.duration);
|
||||
let effective_duration = self.clip_instance.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
let start_time = self.clip_instance.timeline_start;
|
||||
// `effective_duration` is in BEATS. When `timeline_duration` is set
|
||||
// it already is; otherwise the clip occupies its natural content
|
||||
// length, so convert that seconds-span to beats at the clip's start
|
||||
// (NOT `internal_end - internal_start`, which is seconds — that was
|
||||
// the seconds-as-beats bug that made clips stop early off 60 BPM).
|
||||
let effective_duration = self.clip_instance.timeline_duration.unwrap_or_else(|| {
|
||||
let tempo_map = document.tempo_map();
|
||||
let content_secs = internal_end - internal_start;
|
||||
tempo_map.inverse_transform(tempo_map.transform(start_time) + content_secs)
|
||||
- start_time
|
||||
});
|
||||
|
||||
let instance_id = controller.add_audio_clip(
|
||||
*backend_track_id,
|
||||
|
||||
@@ -0,0 +1,778 @@
|
||||
//! SQLite-backed `.beam` project container.
|
||||
//!
|
||||
//! The `.beam` format is a single SQLite database file. It replaces the older
|
||||
//! ZIP-archive format. SQLite gives us, in one file:
|
||||
//!
|
||||
//! - **Streaming reads** — packed media is split into chunk rows and read on
|
||||
//! demand through [`BlobReader`] (`Read + Seek`), so arbitrary-length audio /
|
||||
//! video never has to be fully decoded into RAM on load.
|
||||
//! - **In-place, crash-safe mutation** — raster frame write-back and re-save are
|
||||
//! transactional `UPDATE`s rather than rewriting a whole archive.
|
||||
//! - **Single-file UX** — behaves like a file on every platform.
|
||||
//!
|
||||
//! ## Media storage
|
||||
//!
|
||||
//! Each media item is one row in `media` plus, when *packed*, N rows in
|
||||
//! `media_chunk`:
|
||||
//!
|
||||
//! - **Packed** (`MediaStorage::Packed`) — bytes live in the database, split
|
||||
//! into [`CHUNK_SIZE`]-byte chunks. Chunking keeps each blob well under
|
||||
//! SQLite's ~2 GB per-blob ceiling and bounds the working set of a streaming
|
||||
//! reader to a single chunk.
|
||||
//! - **Referenced** (`MediaStorage::Referenced`) — only an external path is
|
||||
//! stored; the bytes stay on disk (useful for shared media on a network drive,
|
||||
//! or media too large/volatile to pack). Callers open the path directly.
|
||||
//!
|
||||
//! `project.json` (the serialized `BeamProject`) is stored verbatim in the
|
||||
//! single-row `project_json` table; only the container and media storage change
|
||||
//! relative to the legacy format.
|
||||
|
||||
use rusqlite::blob::Blob;
|
||||
use rusqlite::{Connection, DatabaseName, OpenFlags, OptionalExtension};
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
use std::path::Path;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Default packed-media chunk size: 4 MiB.
|
||||
///
|
||||
/// Small enough to bound a streaming reader's per-chunk work and any
|
||||
/// whole-chunk buffering, large enough to keep row counts modest (a 1 GB file
|
||||
/// is 256 rows). Comfortably under SQLite's ~2 GB per-blob limit.
|
||||
pub const CHUNK_SIZE: u64 = 4 * 1024 * 1024;
|
||||
|
||||
/// Files at or above this size prompt the user to pick packed vs referenced
|
||||
/// (and the choice is then persisted as the default). Matches SQLite's
|
||||
/// practical large-blob threshold.
|
||||
pub const LARGE_MEDIA_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
|
||||
|
||||
/// Kind of media stored in the `media` table.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MediaKind {
|
||||
Audio = 0,
|
||||
Video = 1,
|
||||
Raster = 2,
|
||||
ImageAsset = 3,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
fn from_i64(v: i64) -> Option<Self> {
|
||||
match v {
|
||||
0 => Some(Self::Audio),
|
||||
1 => Some(Self::Video),
|
||||
2 => Some(Self::Raster),
|
||||
3 => Some(Self::ImageAsset),
|
||||
4 => Some(Self::Waveform),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a media item's bytes are stored.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MediaStorage {
|
||||
/// Bytes are chunked into `media_chunk` rows inside the database.
|
||||
Packed = 0,
|
||||
/// Only an external path is stored; bytes live on disk.
|
||||
Referenced = 1,
|
||||
}
|
||||
|
||||
impl MediaStorage {
|
||||
fn from_i64(v: i64) -> Option<Self> {
|
||||
match v {
|
||||
0 => Some(Self::Packed),
|
||||
1 => Some(Self::Referenced),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata row for a media item (no bytes).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MediaInfo {
|
||||
pub id: Uuid,
|
||||
pub kind: MediaKind,
|
||||
/// Original codec / container extension, e.g. `"flac"`, `"mp3"`, `"png"`.
|
||||
pub codec: String,
|
||||
pub storage: MediaStorage,
|
||||
/// Set when `storage == Referenced`.
|
||||
pub ext_path: Option<String>,
|
||||
/// Total byte length of the media payload (packed only; 0 for referenced).
|
||||
pub total_len: u64,
|
||||
// Kind-specific metadata (nullable; meaning depends on `kind`).
|
||||
pub channels: Option<u32>,
|
||||
pub sample_rate: Option<u32>,
|
||||
pub width: Option<u32>,
|
||||
pub height: Option<u32>,
|
||||
}
|
||||
|
||||
/// Optional kind-specific metadata supplied when writing a media item.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct MediaMeta {
|
||||
pub channels: Option<u32>,
|
||||
pub sample_rate: Option<u32>,
|
||||
pub width: Option<u32>,
|
||||
pub height: Option<u32>,
|
||||
}
|
||||
|
||||
/// A `.beam` project container backed by a SQLite database.
|
||||
pub struct BeamArchive {
|
||||
conn: Connection,
|
||||
chunk_size: u64,
|
||||
}
|
||||
|
||||
impl BeamArchive {
|
||||
/// Schema version stored in `meta` under `"schema_version"`.
|
||||
pub const SCHEMA_VERSION: i64 = 1;
|
||||
|
||||
/// Create a new (empty) archive at `path`, replacing any existing file.
|
||||
pub fn create(path: &Path) -> Result<Self, String> {
|
||||
// Remove any existing file so we start from a clean schema.
|
||||
if path.exists() {
|
||||
std::fs::remove_file(path).map_err(|e| format!("Failed to replace {:?}: {}", path, e))?;
|
||||
}
|
||||
let conn = Connection::open(path).map_err(map_sql)?;
|
||||
let mut archive = Self { conn, chunk_size: CHUNK_SIZE };
|
||||
archive.init_schema()?;
|
||||
Ok(archive)
|
||||
}
|
||||
|
||||
/// Open an existing archive for read/write.
|
||||
pub fn open(path: &Path) -> Result<Self, String> {
|
||||
let conn = Connection::open(path).map_err(map_sql)?;
|
||||
let archive = Self { conn, chunk_size: CHUNK_SIZE };
|
||||
archive.verify_schema()?;
|
||||
Ok(archive)
|
||||
}
|
||||
|
||||
/// Quick check: does `path` look like a SQLite database (vs. a legacy ZIP)?
|
||||
/// Reads the 16-byte SQLite header magic. Used to route between the SQLite
|
||||
/// loader and the legacy-ZIP migration path.
|
||||
pub fn is_sqlite(path: &Path) -> bool {
|
||||
use std::io::Read as _;
|
||||
let mut f = match std::fs::File::open(path) {
|
||||
Ok(f) => f,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let mut magic = [0u8; 16];
|
||||
if f.read_exact(&mut magic).is_err() {
|
||||
return false;
|
||||
}
|
||||
&magic == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
fn init_schema(&mut self) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"BEGIN;
|
||||
CREATE TABLE media (
|
||||
id BLOB PRIMARY KEY, -- 16-byte Uuid
|
||||
kind INTEGER NOT NULL,
|
||||
codec TEXT NOT NULL,
|
||||
storage INTEGER NOT NULL,
|
||||
ext_path TEXT,
|
||||
total_len INTEGER NOT NULL DEFAULT 0,
|
||||
channels INTEGER,
|
||||
sample_rate INTEGER,
|
||||
width INTEGER,
|
||||
height INTEGER
|
||||
);
|
||||
CREATE TABLE media_chunk (
|
||||
id INTEGER PRIMARY KEY, -- rowid, for blob_open
|
||||
media_id BLOB NOT NULL,
|
||||
chunk_index INTEGER NOT NULL,
|
||||
bytes BLOB NOT NULL,
|
||||
UNIQUE (media_id, chunk_index)
|
||||
);
|
||||
CREATE TABLE project_json (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 0),
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
self.set_meta("schema_version", &Self::SCHEMA_VERSION.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_schema(&self) -> Result<(), String> {
|
||||
let v: Option<String> = self.get_meta("schema_version")?;
|
||||
match v.as_deref().and_then(|s| s.parse::<i64>().ok()) {
|
||||
Some(n) if n <= Self::SCHEMA_VERSION => Ok(()),
|
||||
Some(n) => Err(format!(
|
||||
"Unsupported .beam schema version {} (this build supports up to {})",
|
||||
n,
|
||||
Self::SCHEMA_VERSION
|
||||
)),
|
||||
None => Err("Not a valid .beam archive (missing schema_version)".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Begin a write transaction grouping multiple media/json writes into one
|
||||
/// atomic, crash-safe commit. Used by saves so unchanged (large) media is
|
||||
/// never rewritten — only dirty rows are touched, in place.
|
||||
pub fn transaction(&mut self) -> Result<BeamTxn<'_>, String> {
|
||||
let tx = self.conn.transaction().map_err(map_sql)?;
|
||||
Ok(BeamTxn { tx, chunk_size: self.chunk_size })
|
||||
}
|
||||
|
||||
// -- meta key/value --------------------------------------------------
|
||||
|
||||
pub fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
|
||||
set_meta_conn(&self.conn, key, value)
|
||||
}
|
||||
|
||||
pub fn get_meta(&self, key: &str) -> Result<Option<String>, String> {
|
||||
self.conn
|
||||
.query_row("SELECT value FROM meta WHERE key = ?1", [key], |r| r.get(0))
|
||||
.optional()
|
||||
.map_err(map_sql)
|
||||
}
|
||||
|
||||
// -- project.json ----------------------------------------------------
|
||||
|
||||
/// Store the serialized `project.json` (single row).
|
||||
pub fn set_project_json(&self, json: &str) -> Result<(), String> {
|
||||
set_project_json_conn(&self.conn, json)
|
||||
}
|
||||
|
||||
/// Read the serialized `project.json`.
|
||||
pub fn get_project_json(&self) -> Result<String, String> {
|
||||
self.conn
|
||||
.query_row("SELECT data FROM project_json WHERE id = 0", [], |r| r.get(0))
|
||||
.optional()
|
||||
.map_err(map_sql)?
|
||||
.ok_or_else(|| "Archive has no project.json".to_string())
|
||||
}
|
||||
|
||||
// -- media write -----------------------------------------------------
|
||||
|
||||
/// Write a media item whose bytes are packed (chunked) into the database.
|
||||
/// Replaces any existing rows for `id`.
|
||||
pub fn put_media_packed(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
bytes: &[u8],
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let tx = self.conn.transaction().map_err(map_sql)?;
|
||||
write_media_packed(&tx, self.chunk_size, id, kind, codec, bytes, meta)?;
|
||||
tx.commit().map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write a media item that references an external file by path (no bytes
|
||||
/// stored). Replaces any existing rows for `id`.
|
||||
pub fn put_media_referenced(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
ext_path: &str,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let tx = self.conn.transaction().map_err(map_sql)?;
|
||||
write_media_referenced(&tx, id, kind, codec, ext_path, meta)?;
|
||||
tx.commit().map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -- media read ------------------------------------------------------
|
||||
|
||||
/// Look up a media item's metadata.
|
||||
pub fn media_info(&self, id: Uuid) -> Result<Option<MediaInfo>, String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height
|
||||
FROM media WHERE id = ?1",
|
||||
[&id_bytes],
|
||||
|r| {
|
||||
Ok((
|
||||
r.get::<_, i64>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, i64>(2)?,
|
||||
r.get::<_, Option<String>>(3)?,
|
||||
r.get::<_, i64>(4)?,
|
||||
r.get::<_, Option<u32>>(5)?,
|
||||
r.get::<_, Option<u32>>(6)?,
|
||||
r.get::<_, Option<u32>>(7)?,
|
||||
r.get::<_, Option<u32>>(8)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(map_sql)?
|
||||
.map(|(kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)| {
|
||||
Ok(MediaInfo {
|
||||
id,
|
||||
kind: MediaKind::from_i64(kind)
|
||||
.ok_or_else(|| format!("Unknown media kind {}", kind))?,
|
||||
codec,
|
||||
storage: MediaStorage::from_i64(storage)
|
||||
.ok_or_else(|| format!("Unknown media storage {}", storage))?,
|
||||
ext_path,
|
||||
total_len: total_len.max(0) as u64,
|
||||
channels,
|
||||
sample_rate,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// List every media item of a given kind.
|
||||
pub fn media_ids_of_kind(&self, kind: MediaKind) -> Result<Vec<Uuid>, String> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT id FROM media WHERE kind = ?1")
|
||||
.map_err(map_sql)?;
|
||||
let rows = stmt
|
||||
.query_map([kind as i64], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let bytes = row.map_err(map_sql)?;
|
||||
out.push(uuid_from_bytes(&bytes)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read an entire packed media item into memory. Convenience for small
|
||||
/// media (raster frames, image assets); large media should stream via
|
||||
/// [`BeamArchive::open_blob_reader`] instead.
|
||||
pub fn read_media_full(&self, id: Uuid) -> Result<Vec<u8>, String> {
|
||||
let info = self
|
||||
.media_info(id)?
|
||||
.ok_or_else(|| format!("Media {} not found", id))?;
|
||||
if info.storage != MediaStorage::Packed {
|
||||
return Err(format!("Media {} is referenced, not packed", id));
|
||||
}
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT bytes FROM media_chunk WHERE media_id = ?1 ORDER BY chunk_index")
|
||||
.map_err(map_sql)?;
|
||||
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);
|
||||
for row in rows {
|
||||
out.extend_from_slice(&row.map_err(map_sql)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Open a streaming reader over a packed media item. The reader owns its own
|
||||
/// SQLite connection (read-only) so it can live on a separate thread (e.g.
|
||||
/// the audio disk reader) independent of this archive handle.
|
||||
pub fn open_blob_reader(&self, db_path: &Path, id: Uuid) -> Result<BlobReader, String> {
|
||||
let info = self
|
||||
.media_info(id)?
|
||||
.ok_or_else(|| format!("Media {} not found", id))?;
|
||||
if info.storage != MediaStorage::Packed {
|
||||
return Err(format!("Media {} is referenced, not packed", id));
|
||||
}
|
||||
BlobReader::open(db_path, id, info.total_len, self.chunk_size)
|
||||
}
|
||||
|
||||
/// Override the chunk size (testing / tuning). Affects subsequent writes.
|
||||
#[doc(hidden)]
|
||||
pub fn set_chunk_size(&mut self, chunk_size: u64) {
|
||||
assert!(chunk_size > 0);
|
||||
self.chunk_size = chunk_size;
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming reader (`Read + Seek`) over a packed media item's chunk rows.
|
||||
///
|
||||
/// Owns a dedicated read-only SQLite connection so it is independent of the
|
||||
/// writing [`BeamArchive`] handle and can be moved to another thread. Each
|
||||
/// `read` opens a blob handle on the current chunk's row via `blob_open` (no
|
||||
/// per-read query — chunk rowids are resolved once up front) and reads up to the
|
||||
/// chunk boundary; callers that issue many tiny reads should wrap this in a
|
||||
/// `BufReader`.
|
||||
pub struct BlobReader {
|
||||
conn: Connection,
|
||||
chunk_rowids: Vec<i64>,
|
||||
chunk_size: u64,
|
||||
total_len: u64,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl BlobReader {
|
||||
fn open(db_path: &Path, id: Uuid, total_len: u64, chunk_size: u64) -> Result<Self, String> {
|
||||
let conn = Connection::open_with_flags(
|
||||
db_path,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT id FROM media_chunk WHERE media_id = ?1 ORDER BY chunk_index")
|
||||
.map_err(map_sql)?;
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, i64>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut chunk_rowids = Vec::new();
|
||||
for row in rows {
|
||||
chunk_rowids.push(row.map_err(map_sql)?);
|
||||
}
|
||||
drop(stmt);
|
||||
Ok(Self { conn, chunk_rowids, chunk_size, total_len, pos: 0 })
|
||||
}
|
||||
|
||||
/// Total length of the media payload in bytes.
|
||||
pub fn len(&self) -> u64 {
|
||||
self.total_len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.total_len == 0
|
||||
}
|
||||
|
||||
fn chunk_blob(&self, chunk_index: usize) -> io::Result<Blob<'_>> {
|
||||
let rowid = *self
|
||||
.chunk_rowids
|
||||
.get(chunk_index)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "chunk index out of range"))?;
|
||||
self.conn
|
||||
.blob_open(DatabaseName::Main, "media_chunk", "bytes", rowid, true)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for BlobReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.pos >= self.total_len || buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let chunk_index = (self.pos / self.chunk_size) as usize;
|
||||
let off_in_chunk = self.pos % self.chunk_size;
|
||||
|
||||
// The chunk's length is derivable from total_len/chunk_size, so we don't
|
||||
// depend on Blob::len(): every chunk but the last is exactly chunk_size.
|
||||
let chunk_start = chunk_index as u64 * self.chunk_size;
|
||||
let chunk_len = (self.total_len - chunk_start).min(self.chunk_size);
|
||||
let avail_in_chunk = (chunk_len - off_in_chunk) as usize;
|
||||
let avail_total = (self.total_len - self.pos) as usize;
|
||||
let want = buf.len().min(avail_in_chunk).min(avail_total);
|
||||
|
||||
// Scope the blob borrow (it borrows `self.conn`) so it ends before we
|
||||
// mutate `self.pos`.
|
||||
let n = {
|
||||
let mut blob = self.chunk_blob(chunk_index)?;
|
||||
blob.seek(SeekFrom::Start(off_in_chunk))?;
|
||||
blob.read(&mut buf[..want])?
|
||||
};
|
||||
self.pos += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for BlobReader {
|
||||
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||
let new_pos = match pos {
|
||||
SeekFrom::Start(n) => n as i64,
|
||||
SeekFrom::End(n) => self.total_len as i64 + n,
|
||||
SeekFrom::Current(n) => self.pos as i64 + n,
|
||||
};
|
||||
if new_pos < 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"seek before start of media",
|
||||
));
|
||||
}
|
||||
// Allow seeking to/past end (reads then return 0), matching File semantics.
|
||||
self.pos = new_pos as u64;
|
||||
Ok(self.pos)
|
||||
}
|
||||
}
|
||||
|
||||
/// A write transaction over a [`BeamArchive`]. All writes are buffered until
|
||||
/// [`BeamTxn::commit`]; dropping without committing rolls back. Lets a save
|
||||
/// touch only the rows that changed, in place, without rewriting unchanged media.
|
||||
pub struct BeamTxn<'a> {
|
||||
tx: rusqlite::Transaction<'a>,
|
||||
chunk_size: u64,
|
||||
}
|
||||
|
||||
impl BeamTxn<'_> {
|
||||
pub fn put_media_packed(
|
||||
&self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
bytes: &[u8],
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
write_media_packed(&self.tx, self.chunk_size, id, kind, codec, bytes, meta)
|
||||
}
|
||||
|
||||
pub fn put_media_referenced(
|
||||
&self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
ext_path: &str,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
write_media_referenced(&self.tx, id, kind, codec, ext_path, meta)
|
||||
}
|
||||
|
||||
/// Like [`BeamTxn::put_media_packed`] but streams the bytes from a file on
|
||||
/// disk chunk-by-chunk, so an arbitrarily large file is never fully loaded
|
||||
/// into memory. `total_len` is taken from the bytes actually read.
|
||||
pub fn put_media_packed_from_path(
|
||||
&self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
path: &Path,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
write_media_packed_from_path(&self.tx, self.chunk_size, id, kind, codec, path, meta)
|
||||
}
|
||||
|
||||
pub fn set_project_json(&self, json: &str) -> Result<(), String> {
|
||||
set_project_json_conn(&self.tx, json)
|
||||
}
|
||||
|
||||
pub fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
|
||||
set_meta_conn(&self.tx, key, value)
|
||||
}
|
||||
|
||||
/// Does a media row with this id already exist?
|
||||
pub fn media_exists(&self, id: Uuid) -> Result<bool, String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let n: i64 = self
|
||||
.tx
|
||||
.query_row("SELECT COUNT(*) FROM media WHERE id = ?1", [&id_bytes], |r| r.get(0))
|
||||
.map_err(map_sql)?;
|
||||
Ok(n > 0)
|
||||
}
|
||||
|
||||
/// Every media id currently in the archive.
|
||||
pub fn all_media_ids(&self) -> Result<Vec<Uuid>, String> {
|
||||
let mut stmt = self.tx.prepare("SELECT id FROM media").map_err(map_sql)?;
|
||||
let rows = stmt.query_map([], |r| r.get::<_, Vec<u8>>(0)).map_err(map_sql)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(uuid_from_bytes(&row.map_err(map_sql)?)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Delete a media row (and its chunks).
|
||||
pub fn delete_media(&self, id: Uuid) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
self.tx
|
||||
.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
self.tx
|
||||
.execute("DELETE FROM media WHERE id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete every media row whose id is not in `keep` (orphan cleanup).
|
||||
pub fn retain_media(&self, keep: &std::collections::HashSet<Uuid>) -> Result<usize, String> {
|
||||
let mut removed = 0;
|
||||
for id in self.all_media_ids()? {
|
||||
if !keep.contains(&id) {
|
||||
self.delete_media(id)?;
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn commit(self) -> Result<(), String> {
|
||||
self.tx.commit().map_err(map_sql)
|
||||
}
|
||||
}
|
||||
|
||||
// -- shared write helpers (used by both BeamArchive and BeamTxn) --------------
|
||||
|
||||
fn write_media_packed(
|
||||
conn: &Connection,
|
||||
chunk_size: u64,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
bytes: &[u8],
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
conn.execute("DELETE FROM media WHERE id = ?1", [&id_bytes]).map_err(map_sql)?;
|
||||
conn.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
conn.execute(
|
||||
"INSERT INTO media
|
||||
(id, kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)
|
||||
VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
id_bytes,
|
||||
kind as i64,
|
||||
codec,
|
||||
MediaStorage::Packed as i64,
|
||||
bytes.len() as i64,
|
||||
meta.channels,
|
||||
meta.sample_rate,
|
||||
meta.width,
|
||||
meta.height,
|
||||
],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
for (chunk_index, chunk) in bytes.chunks(chunk_size as usize).enumerate() {
|
||||
conn.execute(
|
||||
"INSERT INTO media_chunk (media_id, chunk_index, bytes) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![id_bytes, chunk_index as i64, chunk],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_media_packed_from_path(
|
||||
conn: &Connection,
|
||||
chunk_size: u64,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
path: &Path,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
conn.execute("DELETE FROM media WHERE id = ?1", [&id_bytes]).map_err(map_sql)?;
|
||||
conn.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
|
||||
let file = std::fs::File::open(path).map_err(|e| format!("Failed to open {:?}: {}", path, e))?;
|
||||
let mut reader = std::io::BufReader::new(file);
|
||||
let mut buf = vec![0u8; chunk_size as usize];
|
||||
let mut chunk_index: i64 = 0;
|
||||
let mut total_len: u64 = 0;
|
||||
|
||||
loop {
|
||||
// Fill `buf` up to chunk_size, tolerating short reads.
|
||||
let mut filled = 0usize;
|
||||
while filled < buf.len() {
|
||||
let n = reader
|
||||
.read(&mut buf[filled..])
|
||||
.map_err(|e| format!("Failed to read {:?}: {}", path, e))?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
filled += n;
|
||||
}
|
||||
if filled == 0 {
|
||||
break;
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO media_chunk (media_id, chunk_index, bytes) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![id_bytes, chunk_index, &buf[..filled]],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
chunk_index += 1;
|
||||
total_len += filled as u64;
|
||||
if filled < buf.len() {
|
||||
break; // reached EOF
|
||||
}
|
||||
}
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO media
|
||||
(id, kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)
|
||||
VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
id_bytes,
|
||||
kind as i64,
|
||||
codec,
|
||||
MediaStorage::Packed as i64,
|
||||
total_len as i64,
|
||||
meta.channels,
|
||||
meta.sample_rate,
|
||||
meta.width,
|
||||
meta.height,
|
||||
],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_media_referenced(
|
||||
conn: &Connection,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
ext_path: &str,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
conn.execute("DELETE FROM media WHERE id = ?1", [&id_bytes]).map_err(map_sql)?;
|
||||
conn.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
conn.execute(
|
||||
"INSERT INTO media
|
||||
(id, kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
id_bytes,
|
||||
kind as i64,
|
||||
codec,
|
||||
MediaStorage::Referenced as i64,
|
||||
ext_path,
|
||||
meta.channels,
|
||||
meta.sample_rate,
|
||||
meta.width,
|
||||
meta.height,
|
||||
],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_project_json_conn(conn: &Connection, json: &str) -> Result<(), String> {
|
||||
conn.execute(
|
||||
"INSERT INTO project_json (id, data) VALUES (0, ?1)
|
||||
ON CONFLICT(id) DO UPDATE SET data = excluded.data",
|
||||
[json],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_meta_conn(conn: &Connection, key: &str, value: &str) -> Result<(), String> {
|
||||
conn.execute(
|
||||
"INSERT INTO meta (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
rusqlite::params![key, value],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_sql(e: rusqlite::Error) -> String {
|
||||
format!("SQLite error: {}", e)
|
||||
}
|
||||
|
||||
fn uuid_from_bytes(bytes: &[u8]) -> Result<Uuid, String> {
|
||||
let arr: [u8; 16] = bytes
|
||||
.try_into()
|
||||
.map_err(|_| format!("Invalid uuid blob length {}", bytes.len()))?;
|
||||
Ok(Uuid::from_bytes(arr))
|
||||
}
|
||||
|
||||
// Tests live in `tests/beam_archive.rs` (integration tests), so they compile the
|
||||
// library in non-test mode and don't depend on the crate's other `#[cfg(test)]`
|
||||
// modules.
|
||||
@@ -1,20 +1,25 @@
|
||||
//! File I/O for .beam project files
|
||||
//!
|
||||
//! This module handles saving and loading Lightningbeam projects in the .beam format,
|
||||
//! which is a ZIP archive containing:
|
||||
//! - project.json (compressed) - Project metadata and structure
|
||||
//! - media/ directory (uncompressed) - Embedded media files (FLAC for audio)
|
||||
//! The `.beam` format is a single **SQLite database** (see [`crate::beam_archive`]):
|
||||
//! - `project_json` table — serialized project metadata and structure
|
||||
//! - `media` / `media_chunk` tables — audio and raster media (packed as chunked
|
||||
//! blobs, or referenced by external path)
|
||||
//!
|
||||
//! Older `.beam` files are ZIP archives; [`load_beam`] detects and reads those
|
||||
//! 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::document::Document;
|
||||
use daw_backend::audio::pool::AudioPoolEntry;
|
||||
use daw_backend::audio::project::Project as AudioProject;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use zip::write::FileOptions;
|
||||
use zip::{CompressionMethod, ZipArchive, ZipWriter};
|
||||
use flacenc::error::Verify;
|
||||
use uuid::Uuid;
|
||||
use zip::ZipArchive;
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
|
||||
|
||||
/// File format version
|
||||
@@ -51,9 +56,7 @@ pub struct SerializedAudioBackend {
|
||||
/// Audio project (tracks, MIDI clips, etc.)
|
||||
pub project: AudioProject,
|
||||
|
||||
/// Audio pool entries (metadata and paths for audio files)
|
||||
/// Note: embedded_data field from daw-backend is ignored; embedded files
|
||||
/// are stored as FLAC in the ZIP's media/audio/ directory instead
|
||||
/// Audio pool entries (metadata and media references for audio files)
|
||||
pub audio_pool_entries: Vec<AudioPoolEntry>,
|
||||
|
||||
/// Mapping from UI layer UUIDs to backend TrackIds
|
||||
@@ -63,6 +66,25 @@ pub struct SerializedAudioBackend {
|
||||
|
||||
}
|
||||
|
||||
/// How to store a media file at or above [`LARGE_MEDIA_THRESHOLD`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LargeMediaMode {
|
||||
/// Not yet decided — prompt the user the first time a large file is imported.
|
||||
/// Treated as [`LargeMediaMode::Reference`] at save time. Resetting the
|
||||
/// preference to `Ask` re-triggers the prompt (useful for testing).
|
||||
Ask,
|
||||
/// Pack the bytes into the `.beam` container (chunked, streamed from disk).
|
||||
Pack,
|
||||
/// Keep the file external and store only a path reference.
|
||||
Reference,
|
||||
}
|
||||
|
||||
impl Default for LargeMediaMode {
|
||||
fn default() -> Self {
|
||||
LargeMediaMode::Ask
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings for saving a project
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SaveSettings {
|
||||
@@ -74,6 +96,10 @@ pub struct SaveSettings {
|
||||
|
||||
/// Force linking all media files (don't embed any)
|
||||
pub force_link_all: bool,
|
||||
|
||||
/// How to store files at/above [`LARGE_MEDIA_THRESHOLD`] (pack vs reference).
|
||||
/// `Ask` behaves as `Reference` here (safe default: don't bloat the DB).
|
||||
pub large_media_mode: LargeMediaMode,
|
||||
}
|
||||
|
||||
impl Default for SaveSettings {
|
||||
@@ -82,6 +108,7 @@ impl Default for SaveSettings {
|
||||
auto_embed_threshold_bytes: 10_000_000, // 10 MB
|
||||
force_embed_all: false,
|
||||
force_link_all: false,
|
||||
large_media_mode: LargeMediaMode::Ask,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,23 +152,93 @@ pub enum MediaFileType {
|
||||
Image,
|
||||
}
|
||||
|
||||
/// Save a project to a .beam file
|
||||
/// Save a project to a `.beam` file (SQLite container).
|
||||
///
|
||||
/// This function:
|
||||
/// 1. Prepares audio project for save (saves AudioGraph presets)
|
||||
/// 2. Serializes project data to JSON
|
||||
/// 3. Creates ZIP archive with compressed project.json
|
||||
/// 4. Embeds media files as FLAC (for audio) in media/ directory
|
||||
/// Re-saving an existing SQLite `.beam` updates it **in place** inside a single
|
||||
/// transaction: unchanged (large) media is never rewritten, only changed rows
|
||||
/// are touched, and the commit is atomic/crash-safe. A brand-new file or a
|
||||
/// legacy-ZIP migration is written to a temp file and atomically renamed (there
|
||||
/// is no large existing container to copy in that case).
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `path` - Path to save the .beam file
|
||||
/// * `document` - UI document state
|
||||
/// * `audio_project` - Audio backend project
|
||||
/// * `audio_pool_entries` - Serialized audio pool entries
|
||||
/// * `settings` - Save settings (embedding preferences)
|
||||
///
|
||||
/// # Returns
|
||||
/// Ok(()) on success, or error message
|
||||
/// Audio and raster media become rows in the `media` table — packed as chunked
|
||||
/// blobs, or referenced by external path for files at/above
|
||||
/// [`LARGE_MEDIA_THRESHOLD`]. `project.json` goes in the `project_json` table.
|
||||
/// Whether a stored media codec is an audio format the disk reader (Symphonia)
|
||||
/// can stream directly from a packed blob. Video-container audio tracks and any
|
||||
/// unknown formats fall back to the legacy reconstitution-and-decode path.
|
||||
fn is_streamable_audio_codec(codec: &str) -> bool {
|
||||
matches!(
|
||||
codec.to_lowercase().as_str(),
|
||||
"mp3" | "flac" | "ogg" | "oga" | "wav" | "wave" | "aiff" | "aif"
|
||||
| "aac" | "m4a" | "opus" | "alac" | "caf"
|
||||
)
|
||||
}
|
||||
|
||||
/// A `Sync` wrapper over core's `BlobReader` so it satisfies Symphonia's
|
||||
/// `MediaSource: Send + Sync`. `BlobReader` holds a rusqlite `Connection`
|
||||
/// (`Send` but `!Sync`); the disk reader uses it single-threaded, so the
|
||||
/// hot Read/Seek path goes through `Mutex::get_mut` (no runtime locking).
|
||||
struct SyncBlobReader {
|
||||
inner: std::sync::Mutex<crate::beam_archive::BlobReader>,
|
||||
len: u64,
|
||||
}
|
||||
|
||||
impl std::io::Read for SyncBlobReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.inner.get_mut().unwrap().read(buf)
|
||||
}
|
||||
}
|
||||
impl std::io::Seek for SyncBlobReader {
|
||||
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.inner.get_mut().unwrap().seek(pos)
|
||||
}
|
||||
}
|
||||
impl daw_backend::audio::MediaByteSource for SyncBlobReader {
|
||||
fn byte_len(&self) -> u64 {
|
||||
self.len
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's packed-media byte-source factory: opens an independent streaming
|
||||
/// reader over a `.beam` container's packed audio by media id. Installed into the
|
||||
/// engine on load so container-packed audio streams without a full decode.
|
||||
#[derive(Debug)]
|
||||
struct BeamBlobFactory {
|
||||
db_path: PathBuf,
|
||||
}
|
||||
|
||||
impl daw_backend::audio::AudioBlobSourceFactory for BeamBlobFactory {
|
||||
fn open(
|
||||
&self,
|
||||
media_id: &str,
|
||||
) -> Result<Box<dyn daw_backend::audio::MediaByteSource>, String> {
|
||||
let id = Uuid::parse_str(media_id).map_err(|e| format!("bad media id {}: {}", media_id, e))?;
|
||||
let archive = BeamArchive::open(&self.db_path)?;
|
||||
let reader = archive.open_blob_reader(&self.db_path, id)?;
|
||||
let len = reader.len();
|
||||
Ok(Box::new(SyncBlobReader { inner: std::sync::Mutex::new(reader), len }))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a packed-media byte-source factory for a `.beam` file, to install into
|
||||
/// the engine (`EngineController::set_blob_source_factory`) before loading so its
|
||||
/// packed audio can be streamed.
|
||||
pub fn blob_source_factory(
|
||||
beam_path: &Path,
|
||||
) -> std::sync::Arc<dyn daw_backend::audio::AudioBlobSourceFactory> {
|
||||
std::sync::Arc::new(BeamBlobFactory { db_path: beam_path.to_path_buf() })
|
||||
}
|
||||
|
||||
/// Deterministic id for the waveform-pyramid media row of audio pool entry
|
||||
/// `pool_index`, within a single project container. Stable across saves (so an
|
||||
/// in-place re-save reuses the row instead of orphaning/rewriting it) and
|
||||
/// independent of how the audio bytes are stored. The top 32 bits are a fixed
|
||||
/// "LBWF" sentinel so it can't collide with the random v4 ids used elsewhere.
|
||||
fn waveform_media_id(pool_index: usize) -> Uuid {
|
||||
const SENTINEL: u128 = 0x4C42_5746u128 << 96; // "LBWF" in the high 32 bits
|
||||
Uuid::from_u128(SENTINEL | (pool_index as u128))
|
||||
}
|
||||
|
||||
pub fn save_beam(
|
||||
path: &Path,
|
||||
document: &Document,
|
||||
@@ -151,256 +248,166 @@ pub fn save_beam(
|
||||
_settings: &SaveSettings,
|
||||
) -> Result<(), String> {
|
||||
let fn_start = std::time::Instant::now();
|
||||
eprintln!("📊 [SAVE_BEAM] Starting save_beam()...");
|
||||
eprintln!("📊 [SAVE_BEAM] Starting save_beam() (SQLite container)...");
|
||||
|
||||
// 1. Create backup if file exists and open it for reading old audio files
|
||||
let step1_start = std::time::Instant::now();
|
||||
let mut old_zip = if path.exists() {
|
||||
let backup_path = path.with_extension("beam.backup");
|
||||
std::fs::copy(path, &backup_path)
|
||||
.map_err(|e| format!("Failed to create backup: {}", e))?;
|
||||
let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
let in_place = path.exists() && BeamArchive::is_sqlite(path);
|
||||
|
||||
// Open the backup as a ZIP archive for reading
|
||||
match File::open(&backup_path) {
|
||||
Ok(file) => match ZipArchive::new(file) {
|
||||
Ok(archive) => {
|
||||
eprintln!("📊 [SAVE_BEAM] Step 1: Create backup and open for reading took {:.2}ms", step1_start.elapsed().as_secs_f64() * 1000.0);
|
||||
Some(archive)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ [SAVE_BEAM] Failed to open backup as ZIP: {}, will not copy old audio files", e);
|
||||
eprintln!("📊 [SAVE_BEAM] Step 1: Create backup took {:.2}ms", step1_start.elapsed().as_secs_f64() * 1000.0);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ [SAVE_BEAM] Failed to open backup: {}, will not copy old audio files", e);
|
||||
eprintln!("📊 [SAVE_BEAM] Step 1: Create backup took {:.2}ms", step1_start.elapsed().as_secs_f64() * 1000.0);
|
||||
None
|
||||
}
|
||||
}
|
||||
// In-place for an existing SQLite container (don't rewrite unchanged media);
|
||||
// temp + atomic rename for new files / legacy-ZIP migration.
|
||||
let tmp_path = path.with_extension("beam.tmp");
|
||||
let mut archive = if in_place {
|
||||
BeamArchive::open(path)?
|
||||
} else {
|
||||
eprintln!("📊 [SAVE_BEAM] Step 1: No backup needed (new file)");
|
||||
None
|
||||
BeamArchive::create(&tmp_path)?
|
||||
};
|
||||
|
||||
// 2. Graph presets are already populated by the engine thread (in GetProject handler)
|
||||
// before cloning. Do NOT call prepare_for_save() here — the cloned project has
|
||||
// default empty graphs (AudioTrack::clone() doesn't copy the graph), so calling
|
||||
// prepare_for_save() would overwrite the good presets with empty ones.
|
||||
let step2_start = std::time::Instant::now();
|
||||
eprintln!("📊 [SAVE_BEAM] Step 2: (graph presets already prepared) took {:.2}ms", step2_start.elapsed().as_secs_f64() * 1000.0);
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let created = if in_place {
|
||||
archive.get_meta("created").ok().flatten().unwrap_or_else(|| now.clone())
|
||||
} else {
|
||||
now.clone()
|
||||
};
|
||||
|
||||
// 3. Create ZIP writer
|
||||
let step3_start = std::time::Instant::now();
|
||||
let file = File::create(path)
|
||||
.map_err(|e| format!("Failed to create file: {}", e))?;
|
||||
let mut zip = ZipWriter::new(file);
|
||||
eprintln!("📊 [SAVE_BEAM] Step 3: Create ZIP writer took {:.2}ms", step3_start.elapsed().as_secs_f64() * 1000.0);
|
||||
let txn = archive.transaction()?;
|
||||
|
||||
// 4. Process audio pool entries and write embedded audio files to ZIP
|
||||
// Priority: old ZIP file > external file > encode PCM as FLAC
|
||||
let step4_start = std::time::Instant::now();
|
||||
let mut modified_entries = Vec::new();
|
||||
let mut flac_encode_time = 0.0;
|
||||
let mut zip_write_time = 0.0;
|
||||
let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
// --- audio pool entries -> media rows (packed) or external references ---
|
||||
let mut modified_entries = Vec::with_capacity(audio_pool_entries.len());
|
||||
let mut live_media: HashSet<Uuid> = HashSet::new();
|
||||
|
||||
for entry in &audio_pool_entries {
|
||||
let mut modified_entry = entry.clone();
|
||||
let mut e = entry.clone();
|
||||
let existing_id = entry.media_id.as_ref().and_then(|s| Uuid::parse_str(s).ok());
|
||||
|
||||
// Try to get audio data from various sources (in priority order)
|
||||
let audio_source: Option<(Vec<u8>, String)> = if let Some(ref rel_path) = entry.relative_path {
|
||||
// Priority 1: Check if file is in the old ZIP
|
||||
if rel_path.starts_with("media/audio/") {
|
||||
if let Some(ref mut old_zip_archive) = old_zip {
|
||||
match old_zip_archive.by_name(rel_path) {
|
||||
Ok(mut file) => {
|
||||
let mut bytes = Vec::new();
|
||||
if file.read_to_end(&mut bytes).is_ok() {
|
||||
let extension = rel_path.split('.').last().unwrap_or("bin").to_string();
|
||||
eprintln!("📊 [SAVE_BEAM] Copying from old ZIP: {}", rel_path);
|
||||
Some((bytes, extension))
|
||||
} else {
|
||||
eprintln!("⚠️ [SAVE_BEAM] Failed to read {} from old ZIP", rel_path);
|
||||
None
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
eprintln!("⚠️ [SAVE_BEAM] File {} not found in old ZIP", rel_path);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
// Already packed in this archive (in-place re-save): leave the bytes
|
||||
// untouched, just keep the reference.
|
||||
if let Some(id) = existing_id {
|
||||
if txn.media_exists(id)? {
|
||||
live_media.insert(id);
|
||||
e.media_id = Some(id.to_string());
|
||||
e.relative_path = None;
|
||||
e.embedded_data = None;
|
||||
modified_entries.push(e);
|
||||
continue;
|
||||
}
|
||||
// Priority 2: Check external filesystem
|
||||
else {
|
||||
let full_path = project_dir.join(rel_path);
|
||||
if full_path.exists() {
|
||||
match std::fs::read(&full_path) {
|
||||
Ok(bytes) => {
|
||||
let extension = full_path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("bin")
|
||||
.to_string();
|
||||
eprintln!("📊 [SAVE_BEAM] Using external file: {:?}", full_path);
|
||||
Some((bytes, extension))
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ [SAVE_BEAM] Failed to read {:?}: {}", full_path, e);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!("⚠️ [SAVE_BEAM] External file not found: {:?}", full_path);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some((audio_bytes, extension)) = audio_source {
|
||||
// We have the original file - copy it directly
|
||||
let zip_filename = format!("media/audio/{}.{}", entry.pool_index, extension);
|
||||
|
||||
let file_options = FileOptions::default()
|
||||
.compression_method(CompressionMethod::Stored);
|
||||
|
||||
zip.start_file(&zip_filename, file_options)
|
||||
.map_err(|e| format!("Failed to create {} in ZIP: {}", zip_filename, e))?;
|
||||
|
||||
let write_start = std::time::Instant::now();
|
||||
zip.write_all(&audio_bytes)
|
||||
.map_err(|e| format!("Failed to write {}: {}", zip_filename, e))?;
|
||||
zip_write_time += write_start.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
// Update entry to point to ZIP file
|
||||
modified_entry.embedded_data = None;
|
||||
modified_entry.relative_path = Some(zip_filename);
|
||||
|
||||
} else if let Some(ref embedded_data) = entry.embedded_data {
|
||||
// Priority 3: No original file - encode PCM as FLAC
|
||||
eprintln!("📊 [SAVE_BEAM] Encoding PCM to FLAC for pool {} (no original file)", entry.pool_index);
|
||||
// Embedded data is always PCM - encode as FLAC
|
||||
let audio_bytes = BASE64_STANDARD.decode(&embedded_data.data_base64)
|
||||
.map_err(|e| format!("Failed to decode base64 audio data for pool index {}: {}", entry.pool_index, e))?;
|
||||
|
||||
let zip_filename = format!("media/audio/{}.flac", entry.pool_index);
|
||||
|
||||
let file_options = FileOptions::default()
|
||||
.compression_method(CompressionMethod::Stored);
|
||||
|
||||
zip.start_file(&zip_filename, file_options)
|
||||
.map_err(|e| format!("Failed to create {} in ZIP: {}", zip_filename, e))?;
|
||||
|
||||
// Encode PCM samples to FLAC
|
||||
let flac_start = std::time::Instant::now();
|
||||
|
||||
// The audio_bytes are raw PCM samples (interleaved f32 little-endian)
|
||||
let samples: Vec<f32> = audio_bytes
|
||||
.chunks_exact(4)
|
||||
.map(|chunk| f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
|
||||
.collect();
|
||||
|
||||
// Convert f32 samples to i32 for FLAC encoding
|
||||
let samples_i32: Vec<i32> = samples
|
||||
.iter()
|
||||
.map(|&s| {
|
||||
let clamped = s.clamp(-1.0, 1.0);
|
||||
(clamped * 8388607.0) as i32
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Configure FLAC encoder
|
||||
let config = flacenc::config::Encoder::default()
|
||||
.into_verified()
|
||||
.map_err(|(_, e)| format!("FLAC encoder config error: {:?}", e))?;
|
||||
|
||||
let source = flacenc::source::MemSource::from_samples(
|
||||
&samples_i32,
|
||||
entry.channels as usize,
|
||||
24,
|
||||
entry.sample_rate as usize,
|
||||
);
|
||||
|
||||
// Encode to FLAC
|
||||
let flac_stream = flacenc::encode_with_fixed_block_size(
|
||||
&config,
|
||||
source,
|
||||
config.block_size,
|
||||
).map_err(|e| format!("FLAC encoding failed: {:?}", e))?;
|
||||
|
||||
// Convert stream to bytes
|
||||
use flacenc::component::BitRepr;
|
||||
let mut sink = flacenc::bitsink::ByteSink::new();
|
||||
flac_stream.write(&mut sink)
|
||||
.map_err(|e| format!("Failed to write FLAC stream: {:?}", e))?;
|
||||
let flac_bytes = sink.as_slice();
|
||||
|
||||
flac_encode_time += flac_start.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
let write_start = std::time::Instant::now();
|
||||
zip.write_all(flac_bytes)
|
||||
.map_err(|e| format!("Failed to write {}: {}", zip_filename, e))?;
|
||||
zip_write_time += write_start.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
// Update entry to point to ZIP file instead of embedding data
|
||||
modified_entry.embedded_data = None;
|
||||
modified_entry.relative_path = Some(zip_filename);
|
||||
}
|
||||
|
||||
modified_entries.push(modified_entry);
|
||||
}
|
||||
eprintln!("📊 [SAVE_BEAM] Step 4: Process audio pool ({} entries) took {:.2}ms",
|
||||
audio_pool_entries.len(), step4_start.elapsed().as_secs_f64() * 1000.0);
|
||||
if flac_encode_time > 0.0 {
|
||||
eprintln!("📊 [SAVE_BEAM] - FLAC encoding: {:.2}ms", flac_encode_time);
|
||||
}
|
||||
if zip_write_time > 0.0 {
|
||||
eprintln!("📊 [SAVE_BEAM] - ZIP writing: {:.2}ms", zip_write_time);
|
||||
// Otherwise resolve the source: external file (Priority 2, streamed from
|
||||
// disk so a huge file is never fully loaded), or embedded data (Priority 3).
|
||||
let meta = MediaMeta {
|
||||
channels: Some(entry.channels),
|
||||
sample_rate: Some(entry.sample_rate),
|
||||
..Default::default()
|
||||
};
|
||||
let mut wrote_packed: Option<Uuid> = None;
|
||||
let mut referenced: Option<String> = None;
|
||||
|
||||
if let Some(rel) = entry.relative_path.as_ref() {
|
||||
let full = if Path::new(rel).is_absolute() {
|
||||
PathBuf::from(rel)
|
||||
} else {
|
||||
project_dir.join(rel)
|
||||
};
|
||||
if full.exists() {
|
||||
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("bin")
|
||||
.to_lowercase();
|
||||
// Large files honor the user's pack-vs-reference choice (`Ask` ==
|
||||
// reference); smaller files are always packed.
|
||||
let reference_it = size >= LARGE_MEDIA_THRESHOLD
|
||||
&& _settings.large_media_mode != LargeMediaMode::Pack;
|
||||
if reference_it {
|
||||
referenced = Some(rel.clone());
|
||||
} else {
|
||||
let id = existing_id.unwrap_or_else(Uuid::new_v4);
|
||||
txn.put_media_packed_from_path(id, MediaKind::Audio, &codec, &full, meta)?;
|
||||
wrote_packed = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if wrote_packed.is_none() && referenced.is_none() {
|
||||
if let Some(ed) = entry.embedded_data.as_ref() {
|
||||
if let Ok(bytes) = BASE64_STANDARD.decode(&ed.data_base64) {
|
||||
let id = existing_id.unwrap_or_else(Uuid::new_v4);
|
||||
txn.put_media_packed(id, MediaKind::Audio, &ed.format.to_lowercase(), &bytes, meta)?;
|
||||
wrote_packed = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(id) = wrote_packed {
|
||||
live_media.insert(id);
|
||||
e.media_id = Some(id.to_string());
|
||||
e.relative_path = None;
|
||||
e.embedded_data = None;
|
||||
} else if let Some(rel) = referenced {
|
||||
e.media_id = None;
|
||||
e.relative_path = Some(rel);
|
||||
e.embedded_data = None;
|
||||
} // else: nothing available — keep original references (reported missing on load)
|
||||
|
||||
// Persist this entry's waveform pyramid (keyed by pool index, independent
|
||||
// of the audio storage above). Reuse the row in place on re-save.
|
||||
let wf_id = waveform_media_id(entry.pool_index);
|
||||
if let Some(blob) = entry.waveform_blob.as_ref() {
|
||||
txn.put_media_packed(wf_id, MediaKind::Waveform, "lbwf", blob, MediaMeta::default())?;
|
||||
live_media.insert(wf_id);
|
||||
} else if txn.media_exists(wf_id)? {
|
||||
// Unchanged this save — keep the stored waveform row.
|
||||
live_media.insert(wf_id);
|
||||
}
|
||||
|
||||
modified_entries.push(e);
|
||||
}
|
||||
|
||||
// 4b. Write raster layer PNG buffers to ZIP (media/raster/<keyframe-uuid>.png)
|
||||
let step4b_start = std::time::Instant::now();
|
||||
let raster_file_options = FileOptions::default()
|
||||
.compression_method(CompressionMethod::Stored); // PNG is already compressed
|
||||
// --- raster keyframes -> media rows (PNG), keyed by keyframe id ---
|
||||
// (Phase 0 writes all resident frames each save; a disk-dirty flag to skip
|
||||
// unchanged frames in place is deferred to Phase 3.)
|
||||
let mut raster_count = 0usize;
|
||||
for layer in &document.root.children {
|
||||
if let crate::layer::AnyLayer::Raster(rl) = layer {
|
||||
for kf in &rl.keyframes {
|
||||
if !kf.raw_pixels.is_empty() {
|
||||
// Encode raw RGBA to PNG for storage
|
||||
let img = crate::brush_engine::image_from_raw(
|
||||
kf.raw_pixels.clone(), kf.width, kf.height,
|
||||
);
|
||||
let img =
|
||||
crate::brush_engine::image_from_raw(kf.raw_pixels.clone(), kf.width, kf.height);
|
||||
match crate::brush_engine::encode_png(&img) {
|
||||
Ok(png_bytes) => {
|
||||
let zip_path = kf.media_path.clone();
|
||||
zip.start_file(&zip_path, raster_file_options)
|
||||
.map_err(|e| format!("Failed to create {} in ZIP: {}", zip_path, e))?;
|
||||
zip.write_all(&png_bytes)
|
||||
.map_err(|e| format!("Failed to write {}: {}", zip_path, e))?;
|
||||
txn.put_media_packed(
|
||||
kf.id,
|
||||
MediaKind::Raster,
|
||||
"png",
|
||||
&png_bytes,
|
||||
MediaMeta {
|
||||
width: Some(kf.width),
|
||||
height: Some(kf.height),
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
live_media.insert(kf.id);
|
||||
raster_count += 1;
|
||||
}
|
||||
Err(e) => eprintln!("⚠️ [SAVE_BEAM] Failed to encode raster PNG {}: {}", kf.media_path, e),
|
||||
Err(e) => eprintln!("⚠️ [SAVE_BEAM] Failed to encode raster {}: {}", kf.id, e),
|
||||
}
|
||||
} else if txn.media_exists(kf.id)? {
|
||||
// Pixels not resident but already stored — keep the row.
|
||||
live_media.insert(kf.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("📊 [SAVE_BEAM] Step 4b: Write {} raster PNG buffers took {:.2}ms",
|
||||
raster_count, step4b_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// 5. Build BeamProject structure with modified entries
|
||||
let step5_start = std::time::Instant::now();
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
// --- orphan cleanup: drop media for removed clips/keyframes ---
|
||||
let removed = txn.retain_media(&live_media)?;
|
||||
|
||||
// --- project.json + meta ---
|
||||
let beam_project = BeamProject {
|
||||
version: BEAM_VERSION.to_string(),
|
||||
created: now.clone(),
|
||||
modified: now,
|
||||
created: created.clone(),
|
||||
modified: now.clone(),
|
||||
ui_state: document.clone(),
|
||||
audio_backend: SerializedAudioBackend {
|
||||
sample_rate: 48000, // TODO: Get from audio engine
|
||||
@@ -409,52 +416,187 @@ pub fn save_beam(
|
||||
layer_to_track_map: layer_to_track_map.clone(),
|
||||
},
|
||||
};
|
||||
eprintln!("📊 [SAVE_BEAM] Step 5: Build BeamProject structure took {:.2}ms", step5_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// 6. Write project.json (compressed with DEFLATE)
|
||||
let step6_start = std::time::Instant::now();
|
||||
let json_options = FileOptions::default()
|
||||
.compression_method(CompressionMethod::Deflated)
|
||||
.compression_level(Some(6));
|
||||
|
||||
zip.start_file("project.json", json_options)
|
||||
.map_err(|e| format!("Failed to create project.json in ZIP: {}", e))?;
|
||||
|
||||
let json = serde_json::to_string_pretty(&beam_project)
|
||||
let json = serde_json::to_string(&beam_project)
|
||||
.map_err(|e| format!("JSON serialization failed: {}", e))?;
|
||||
txn.set_project_json(&json)?;
|
||||
txn.set_meta("version", BEAM_VERSION)?;
|
||||
txn.set_meta("created", &created)?;
|
||||
txn.set_meta("modified", &now)?;
|
||||
txn.commit()?;
|
||||
|
||||
zip.write_all(json.as_bytes())
|
||||
.map_err(|e| format!("Failed to write project.json: {}", e))?;
|
||||
eprintln!("📊 [SAVE_BEAM] Step 6: Write project.json ({} bytes) took {:.2}ms", json.len(), step6_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// 7. Finalize ZIP
|
||||
let step7_start = std::time::Instant::now();
|
||||
zip.finish()
|
||||
.map_err(|e| format!("Failed to finalize ZIP: {}", e))?;
|
||||
eprintln!("📊 [SAVE_BEAM] Step 7: Finalize ZIP took {:.2}ms", step7_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
eprintln!("📊 [SAVE_BEAM] ✅ Total save_beam() time: {:.2}ms", fn_start.elapsed().as_secs_f64() * 1000.0);
|
||||
// Close the connection before renaming (required on Windows; harmless elsewhere).
|
||||
drop(archive);
|
||||
if !in_place {
|
||||
std::fs::rename(&tmp_path, path)
|
||||
.map_err(|e| format!("Failed to finalize {:?}: {}", path, e))?;
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"📊 [SAVE_BEAM] ✅ Saved {} audio + {} raster media, {} orphans removed, in {:.2}ms",
|
||||
audio_pool_entries.len(),
|
||||
raster_count,
|
||||
removed,
|
||||
fn_start.elapsed().as_secs_f64() * 1000.0
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load a project from a .beam file
|
||||
/// Load a project from a `.beam` file.
|
||||
///
|
||||
/// This function:
|
||||
/// 1. Opens ZIP archive and reads project.json
|
||||
/// 2. Deserializes project data
|
||||
/// 3. Loads embedded media files from archive
|
||||
/// 4. Attempts to load external media files
|
||||
/// 5. Rebuilds AudioGraphs from presets with correct sample_rate
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `path` - Path to the .beam file
|
||||
///
|
||||
/// # Returns
|
||||
/// LoadedProject on success (with missing_files list), or error message
|
||||
/// Detects the container format: SQLite (current) or legacy ZIP, and dispatches
|
||||
/// accordingly. Both produce an identical [`LoadedProject`].
|
||||
pub fn load_beam(path: &Path) -> Result<LoadedProject, String> {
|
||||
if BeamArchive::is_sqlite(path) {
|
||||
load_beam_sqlite(path)
|
||||
} else {
|
||||
load_beam_zip_legacy(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load a project from a SQLite `.beam` container.
|
||||
///
|
||||
/// Phase 0 reconstitutes packed audio into each entry's `embedded_data` so the
|
||||
/// existing (full-decode) audio pool loader keeps working unchanged; Phase 1b
|
||||
/// replaces this with streaming reads via `BlobReader`.
|
||||
fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
let fn_start = std::time::Instant::now();
|
||||
eprintln!("📊 [LOAD_BEAM] Starting load_beam()...");
|
||||
eprintln!("📊 [LOAD_BEAM] Starting load_beam() (SQLite container)...");
|
||||
|
||||
let archive = BeamArchive::open(path)?;
|
||||
let json = archive.get_project_json()?;
|
||||
let beam_project: BeamProject = serde_json::from_str(&json)
|
||||
.map_err(|e| format!("Failed to deserialize project.json: {}", e))?;
|
||||
|
||||
if beam_project.version != BEAM_VERSION {
|
||||
return Err(format!(
|
||||
"Unsupported file version: {} (expected {})",
|
||||
beam_project.version, BEAM_VERSION
|
||||
));
|
||||
}
|
||||
|
||||
let mut document = beam_project.ui_state;
|
||||
document.tempo_map_mut().rebuild_seconds();
|
||||
let mut audio_project = beam_project.audio_backend.project;
|
||||
audio_project
|
||||
.rebuild_audio_graphs(DEFAULT_BUFFER_SIZE)
|
||||
.map_err(|e| format!("Failed to rebuild audio graphs: {}", e))?;
|
||||
let layer_to_track_map = beam_project.audio_backend.layer_to_track_map;
|
||||
|
||||
// For each packed audio item: stream it (leave `embedded_data` empty so the
|
||||
// pool builds a Compressed placeholder backed by the blob factory) when it's a
|
||||
// recognized audio codec; otherwise fall back to the legacy reconstitution
|
||||
// (whole bytes → base64 → decode), which still covers video-container audio
|
||||
// tracks symphonia can't stream and any unknown formats.
|
||||
let mut restored_entries = Vec::with_capacity(beam_project.audio_backend.audio_pool_entries.len());
|
||||
for entry in &beam_project.audio_backend.audio_pool_entries {
|
||||
let mut e = entry.clone();
|
||||
if let Some(id) = entry.media_id.as_ref().and_then(|s| Uuid::parse_str(s).ok()) {
|
||||
match archive.media_info(id) {
|
||||
Ok(Some(info)) => {
|
||||
if is_streamable_audio_codec(&info.codec) {
|
||||
// Stream: keep media_id, no embedded bytes. The engine opens
|
||||
// the packed blob via the factory at activation time.
|
||||
e.embedded_data = None;
|
||||
e.relative_path = None;
|
||||
} else {
|
||||
match archive.read_media_full(id) {
|
||||
Ok(bytes) => {
|
||||
e.embedded_data = Some(daw_backend::audio::pool::EmbeddedAudioData {
|
||||
data_base64: BASE64_STANDARD.encode(&bytes),
|
||||
format: info.codec,
|
||||
});
|
||||
e.relative_path = None;
|
||||
}
|
||||
Err(err) => eprintln!("⚠️ [LOAD_BEAM] Failed to read audio media {}: {}", id, err),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => eprintln!("⚠️ [LOAD_BEAM] Audio media {} missing from archive", id),
|
||||
Err(err) => eprintln!("⚠️ [LOAD_BEAM] media_info({}) failed: {}", id, err),
|
||||
}
|
||||
}
|
||||
|
||||
// Restore this entry's persisted waveform pyramid, if present — avoids
|
||||
// re-decoding the source media just to redraw the overview.
|
||||
let wf_id = waveform_media_id(entry.pool_index);
|
||||
if let Ok(Some(_)) = archive.media_info(wf_id) {
|
||||
match archive.read_media_full(wf_id) {
|
||||
Ok(bytes) => e.waveform_blob = Some(bytes),
|
||||
Err(err) => eprintln!("⚠️ [LOAD_BEAM] Failed to read waveform {}: {}", wf_id, err),
|
||||
}
|
||||
}
|
||||
|
||||
restored_entries.push(e);
|
||||
}
|
||||
|
||||
// Raster keyframes: load PNG bytes from media rows into raw_pixels.
|
||||
let mut raster_load_count = 0usize;
|
||||
for layer in document.root.children.iter_mut() {
|
||||
if let crate::layer::AnyLayer::Raster(rl) = layer {
|
||||
for kf in &mut rl.keyframes {
|
||||
if let Ok(Some(_)) = archive.media_info(kf.id) {
|
||||
match archive.read_media_full(kf.id) {
|
||||
Ok(png_bytes) => match crate::brush_engine::decode_png(&png_bytes) {
|
||||
Ok(rgba) => {
|
||||
kf.raw_pixels = rgba.into_raw();
|
||||
raster_load_count += 1;
|
||||
}
|
||||
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to decode raster {}: {}", kf.id, e),
|
||||
},
|
||||
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to read raster {}: {}", kf.id, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, entry)| {
|
||||
if entry.embedded_data.is_none() && entry.media_id.is_none() {
|
||||
if let Some(rel) = entry.relative_path.as_ref() {
|
||||
let full = if Path::new(rel).is_absolute() {
|
||||
PathBuf::from(rel)
|
||||
} else {
|
||||
project_dir.join(rel)
|
||||
};
|
||||
if !full.exists() {
|
||||
return Some(MissingFileInfo {
|
||||
pool_index: idx,
|
||||
original_path: full,
|
||||
file_type: MediaFileType::Audio,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect();
|
||||
|
||||
eprintln!(
|
||||
"📊 [LOAD_BEAM] ✅ Loaded {} audio entries, {} raster frames in {:.2}ms",
|
||||
restored_entries.len(),
|
||||
raster_load_count,
|
||||
fn_start.elapsed().as_secs_f64() * 1000.0
|
||||
);
|
||||
|
||||
Ok(LoadedProject {
|
||||
document,
|
||||
audio_project,
|
||||
layer_to_track_map,
|
||||
audio_pool_entries: restored_entries,
|
||||
missing_files,
|
||||
})
|
||||
}
|
||||
|
||||
/// Load a project from a legacy ZIP `.beam` archive (pre-SQLite format).
|
||||
/// Retained for backward compatibility; saving converts to SQLite.
|
||||
fn load_beam_zip_legacy(path: &Path) -> Result<LoadedProject, String> {
|
||||
let fn_start = std::time::Instant::now();
|
||||
eprintln!("📊 [LOAD_BEAM] Starting load_beam() (legacy ZIP)...");
|
||||
|
||||
// 1. Open ZIP archive
|
||||
let step1_start = std::time::Instant::now();
|
||||
|
||||
@@ -42,6 +42,7 @@ pub mod segment_builder;
|
||||
pub mod planar_graph;
|
||||
pub mod file_types;
|
||||
pub mod file_io;
|
||||
pub mod beam_archive;
|
||||
pub mod export;
|
||||
pub mod clipboard;
|
||||
pub(crate) mod clipboard_platform;
|
||||
|
||||
@@ -97,7 +97,7 @@ 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::build_keyframe_index(&path, stream_index)?;
|
||||
let positions = Self::scan_keyframes(&path, stream_index)?;
|
||||
eprintln!("[Video Decoder] Found {} keyframes", positions.len());
|
||||
positions
|
||||
} else {
|
||||
@@ -125,14 +125,19 @@ impl VideoDecoder {
|
||||
})
|
||||
}
|
||||
|
||||
/// Build keyframe index for this decoder
|
||||
/// This can be called asynchronously after decoder creation
|
||||
fn build_and_set_keyframe_index(&mut self) -> Result<(), String> {
|
||||
eprintln!("[Video Decoder] Building keyframe index for {}", self.path);
|
||||
let positions = Self::build_keyframe_index(&self.path, self.stream_index)?;
|
||||
eprintln!("[Video Decoder] Found {} keyframes", positions.len());
|
||||
/// Source file path this decoder reads from.
|
||||
pub fn path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// Replace the keyframe index (built off-thread via [`VideoDecoder::scan_keyframes`]).
|
||||
pub fn set_keyframe_index(&mut self, positions: Vec<i64>) {
|
||||
self.keyframe_positions = positions;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the output width (scaled dimensions)
|
||||
@@ -150,9 +155,10 @@ impl VideoDecoder {
|
||||
self.get_frame(timestamp)
|
||||
}
|
||||
|
||||
/// Build an index of all keyframe positions in the video
|
||||
/// This enables fast seeking by knowing exactly where keyframes are
|
||||
fn build_keyframe_index(path: &str, stream_index: usize) -> Result<Vec<i64>, String> {
|
||||
/// 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)
|
||||
.map_err(|e| format!("Failed to open video for indexing: {}", e))?;
|
||||
|
||||
@@ -340,6 +346,51 @@ impl VideoDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate timeline thumbnails for a video using a **dedicated** decoder that
|
||||
/// is independent of any shared playback decoder — so thumbnail work never holds
|
||||
/// a lock the UI/playback needs.
|
||||
///
|
||||
/// Thumbnails are sampled at keyframes ~`interval_secs` apart. Decoding at a
|
||||
/// keyframe is cheap (≈one frame) versus decoding forward to an arbitrary
|
||||
/// timestamp (the whole GOP). Frames are decoded directly at `thumb_width` (so
|
||||
/// `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,
|
||||
interval_secs: f64,
|
||||
thumb_width: u32,
|
||||
mut on_thumb: impl FnMut(f64, Arc<Vec<u8>>),
|
||||
) -> Result<(), String> {
|
||||
// Own decoder at thumbnail resolution; builds its own keyframe index. The
|
||||
// large max-height lets width be the constraining dimension, so output width
|
||||
// is exactly `thumb_width`.
|
||||
let mut decoder = VideoDecoder::new(
|
||||
path.to_string(),
|
||||
4,
|
||||
Some(thumb_width),
|
||||
Some(100_000),
|
||||
true, // build keyframe index (needed to sample at keyframes)
|
||||
)?;
|
||||
|
||||
let keyframe_secs: Vec<f64> = decoder
|
||||
.keyframe_positions
|
||||
.iter()
|
||||
.map(|&ts| ts as f64 * decoder.time_base)
|
||||
.collect();
|
||||
|
||||
let mut last_emitted = f64::NEG_INFINITY;
|
||||
for ks in keyframe_secs {
|
||||
if ks - last_emitted < interval_secs {
|
||||
continue;
|
||||
}
|
||||
if let Ok(rgba) = decoder.get_frame(ks) {
|
||||
last_emitted = ks;
|
||||
on_thumb(ks, Arc::new(rgba));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Probe video file for metadata without creating a full decoder
|
||||
pub fn probe_video(path: &str) -> Result<VideoMetadata, String> {
|
||||
ffmpeg::init().map_err(|e| e.to_string())?;
|
||||
@@ -440,8 +491,9 @@ impl VideoManager {
|
||||
/// `target_width` and `target_height` specify the maximum dimensions
|
||||
/// for decoded frames. Video will be scaled down if larger.
|
||||
///
|
||||
/// The keyframe index is NOT built during this call - use `build_keyframe_index_async`
|
||||
/// in a background thread to build it asynchronously.
|
||||
/// The keyframe index is NOT built during this call — scan it off-thread via
|
||||
/// [`VideoDecoder::scan_keyframes`] and store it with
|
||||
/// [`VideoDecoder::set_keyframe_index`] so the slow scan never blocks playback.
|
||||
pub fn load_video(
|
||||
&mut self,
|
||||
clip_id: Uuid,
|
||||
@@ -467,20 +519,6 @@ impl VideoManager {
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Build keyframe index for a loaded video asynchronously
|
||||
///
|
||||
/// This should be called from a background thread after load_video()
|
||||
/// to avoid blocking the UI during import.
|
||||
pub fn build_keyframe_index(&self, clip_id: &Uuid) -> Result<(), String> {
|
||||
let decoder_arc = self.decoders.get(clip_id)
|
||||
.ok_or_else(|| format!("Video clip {} not found", clip_id))?;
|
||||
|
||||
let mut decoder = decoder_arc.lock()
|
||||
.map_err(|e| format!("Failed to lock decoder: {}", e))?;
|
||||
|
||||
decoder.build_and_set_keyframe_index()
|
||||
}
|
||||
|
||||
/// Get a decoded frame for a specific clip at a specific timestamp
|
||||
///
|
||||
/// Returns None if the clip is not loaded or decoding fails.
|
||||
@@ -517,62 +555,6 @@ impl VideoManager {
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
/// Generate thumbnails for a video clip (single batch version - use generate_thumbnails_progressive instead)
|
||||
///
|
||||
/// Thumbnails are generated every 5 seconds at 128px width.
|
||||
/// This should be called in a background thread to avoid blocking.
|
||||
/// Thumbnails are inserted into the cache progressively as they're generated,
|
||||
/// allowing the UI to display them immediately.
|
||||
///
|
||||
/// DEPRECATED: Use generate_thumbnails_progressive which releases the lock between thumbnails.
|
||||
pub fn generate_thumbnails(&mut self, clip_id: &Uuid, duration: f64) -> Result<(), String> {
|
||||
let decoder_arc = self.decoders.get(clip_id)
|
||||
.ok_or("Clip not loaded")?
|
||||
.clone();
|
||||
|
||||
let mut decoder = decoder_arc.lock()
|
||||
.map_err(|e| format!("Failed to lock decoder: {}", e))?;
|
||||
|
||||
// Initialize thumbnail cache entry with empty vec
|
||||
self.thumbnail_cache.insert(*clip_id, Vec::new());
|
||||
|
||||
let interval = 5.0; // Generate thumbnail every 5 seconds
|
||||
let mut t = 0.0;
|
||||
|
||||
while t < duration {
|
||||
// Decode frame at this timestamp
|
||||
if let Ok(rgba_data) = decoder.get_frame(t) {
|
||||
// Decode already scaled to output dimensions, but we want 128px width for thumbnails
|
||||
// We need to scale down further
|
||||
let current_width = decoder.output_width;
|
||||
let current_height = decoder.output_height;
|
||||
|
||||
// Calculate thumbnail dimensions (128px width, maintain aspect ratio)
|
||||
let thumb_width = 128u32;
|
||||
let aspect_ratio = current_height as f32 / current_width as f32;
|
||||
let thumb_height = (thumb_width as f32 * aspect_ratio) as u32;
|
||||
|
||||
// Simple nearest-neighbor downsampling for thumbnails
|
||||
let thumb_data = downsample_rgba(
|
||||
&rgba_data,
|
||||
current_width,
|
||||
current_height,
|
||||
thumb_width,
|
||||
thumb_height,
|
||||
);
|
||||
|
||||
// Insert thumbnail into cache immediately so UI can display it
|
||||
if let Some(thumbnails) = self.thumbnail_cache.get_mut(clip_id) {
|
||||
thumbnails.push((t, Arc::new(thumb_data)));
|
||||
}
|
||||
}
|
||||
|
||||
t += interval;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the decoder Arc for a clip (for external thumbnail generation)
|
||||
/// This allows external code to decode frames without holding the VideoManager lock
|
||||
pub fn get_decoder(&self, clip_id: &Uuid) -> Option<Arc<Mutex<VideoDecoder>>> {
|
||||
@@ -650,211 +632,3 @@ impl Default for VideoManager {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Simple nearest-neighbor downsampling for RGBA images
|
||||
pub fn downsample_rgba_public(
|
||||
src: &[u8],
|
||||
src_width: u32,
|
||||
src_height: u32,
|
||||
dst_width: u32,
|
||||
dst_height: u32,
|
||||
) -> Vec<u8> {
|
||||
downsample_rgba(src, src_width, src_height, dst_width, dst_height)
|
||||
}
|
||||
|
||||
/// Simple nearest-neighbor downsampling for RGBA images (internal)
|
||||
fn downsample_rgba(
|
||||
src: &[u8],
|
||||
src_width: u32,
|
||||
src_height: u32,
|
||||
dst_width: u32,
|
||||
dst_height: u32,
|
||||
) -> Vec<u8> {
|
||||
let mut dst = Vec::with_capacity((dst_width * dst_height * 4) as usize);
|
||||
|
||||
let x_ratio = src_width as f32 / dst_width as f32;
|
||||
let y_ratio = src_height as f32 / dst_height as f32;
|
||||
|
||||
for y in 0..dst_height {
|
||||
for x in 0..dst_width {
|
||||
let src_x = (x as f32 * x_ratio) as u32;
|
||||
let src_y = (y as f32 * y_ratio) as u32;
|
||||
|
||||
let src_idx = ((src_y * src_width + src_x) * 4) as usize;
|
||||
|
||||
// Copy RGBA bytes
|
||||
dst.push(src[src_idx]); // R
|
||||
dst.push(src[src_idx + 1]); // G
|
||||
dst.push(src[src_idx + 2]); // B
|
||||
dst.push(src[src_idx + 3]); // A
|
||||
}
|
||||
}
|
||||
|
||||
dst
|
||||
}
|
||||
|
||||
/// Extracted audio data from a video file
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExtractedAudio {
|
||||
pub samples: Vec<f32>,
|
||||
pub channels: u32,
|
||||
pub sample_rate: u32,
|
||||
pub duration: f64,
|
||||
}
|
||||
|
||||
/// Extract audio from a video file
|
||||
///
|
||||
/// This function performs the slow FFmpeg decoding without holding any locks.
|
||||
/// The caller can then quickly add the audio to the DAW backend in a background thread.
|
||||
///
|
||||
/// Returns None if the video has no audio stream.
|
||||
pub fn extract_audio_from_video(path: &str) -> Result<Option<ExtractedAudio>, String> {
|
||||
ffmpeg::init().map_err(|e| e.to_string())?;
|
||||
|
||||
// Open video file
|
||||
let mut input = ffmpeg::format::input(path)
|
||||
.map_err(|e| format!("Failed to open video: {}", e))?;
|
||||
|
||||
// Find audio stream
|
||||
let audio_stream_opt = input.streams()
|
||||
.best(ffmpeg::media::Type::Audio);
|
||||
|
||||
// Return None if no audio stream
|
||||
if audio_stream_opt.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let audio_stream = audio_stream_opt.unwrap();
|
||||
let audio_index = audio_stream.index();
|
||||
|
||||
// Get audio properties
|
||||
let context_decoder = ffmpeg::codec::context::Context::from_parameters(
|
||||
audio_stream.parameters()
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
let mut audio_decoder = context_decoder.decoder().audio()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let sample_rate = audio_decoder.rate();
|
||||
let channels = audio_decoder.channels() as u32;
|
||||
|
||||
// Decode all audio frames
|
||||
let mut audio_samples: Vec<f32> = Vec::new();
|
||||
|
||||
for (stream, packet) in input.packets() {
|
||||
if stream.index() == audio_index {
|
||||
audio_decoder.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut audio_frame = ffmpeg::util::frame::Audio::empty();
|
||||
while audio_decoder.receive_frame(&mut audio_frame).is_ok() {
|
||||
// Convert audio to f32 packed format
|
||||
let format = audio_frame.format();
|
||||
let frame_channels = audio_frame.channels() as usize;
|
||||
|
||||
// Create resampler to convert to f32 packed
|
||||
let mut resampler = ffmpeg::software::resampling::context::Context::get(
|
||||
format,
|
||||
audio_frame.channel_layout(),
|
||||
sample_rate,
|
||||
ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),
|
||||
audio_frame.channel_layout(),
|
||||
sample_rate,
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
let mut resampled_frame = ffmpeg::util::frame::Audio::empty();
|
||||
resampler.run(&audio_frame, &mut resampled_frame)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Extract f32 samples (interleaved format)
|
||||
let data_ptr = resampled_frame.data(0).as_ptr() as *const f32;
|
||||
let total_samples = resampled_frame.samples() * frame_channels;
|
||||
|
||||
// Safety checks before creating slice from FFmpeg data
|
||||
// 1. Verify f32 alignment (required: 4 bytes)
|
||||
if data_ptr.align_offset(std::mem::align_of::<f32>()) != 0 {
|
||||
return Err("FFmpeg audio data is not properly aligned for f32".to_string());
|
||||
}
|
||||
|
||||
// 2. Verify the frame actually has enough data
|
||||
let byte_size = resampled_frame.data(0).len();
|
||||
let expected_bytes = total_samples * std::mem::size_of::<f32>();
|
||||
if byte_size < expected_bytes {
|
||||
return Err(format!(
|
||||
"FFmpeg frame buffer too small: {} bytes, need {} bytes",
|
||||
byte_size, expected_bytes
|
||||
));
|
||||
}
|
||||
|
||||
// SAFETY: We verified alignment and bounds above.
|
||||
// The slice lifetime is tied to resampled_frame which lives until
|
||||
// after extend_from_slice completes.
|
||||
let samples_slice = unsafe {
|
||||
std::slice::from_raw_parts(data_ptr, total_samples)
|
||||
};
|
||||
|
||||
audio_samples.extend_from_slice(samples_slice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush audio decoder
|
||||
audio_decoder.send_eof().map_err(|e| e.to_string())?;
|
||||
let mut audio_frame = ffmpeg::util::frame::Audio::empty();
|
||||
while audio_decoder.receive_frame(&mut audio_frame).is_ok() {
|
||||
let format = audio_frame.format();
|
||||
let frame_channels = audio_frame.channels() as usize;
|
||||
|
||||
let mut resampler = ffmpeg::software::resampling::context::Context::get(
|
||||
format,
|
||||
audio_frame.channel_layout(),
|
||||
sample_rate,
|
||||
ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),
|
||||
audio_frame.channel_layout(),
|
||||
sample_rate,
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
let mut resampled_frame = ffmpeg::util::frame::Audio::empty();
|
||||
resampler.run(&audio_frame, &mut resampled_frame)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let data_ptr = resampled_frame.data(0).as_ptr() as *const f32;
|
||||
let total_samples = resampled_frame.samples() * frame_channels;
|
||||
|
||||
// Safety checks before creating slice from FFmpeg data
|
||||
// 1. Verify f32 alignment (required: 4 bytes)
|
||||
if data_ptr.align_offset(std::mem::align_of::<f32>()) != 0 {
|
||||
return Err("FFmpeg audio data is not properly aligned for f32".to_string());
|
||||
}
|
||||
|
||||
// 2. Verify the frame actually has enough data
|
||||
let byte_size = resampled_frame.data(0).len();
|
||||
let expected_bytes = total_samples * std::mem::size_of::<f32>();
|
||||
if byte_size < expected_bytes {
|
||||
return Err(format!(
|
||||
"FFmpeg frame buffer too small: {} bytes, need {} bytes",
|
||||
byte_size, expected_bytes
|
||||
));
|
||||
}
|
||||
|
||||
// SAFETY: We verified alignment and bounds above.
|
||||
// The slice lifetime is tied to resampled_frame which lives until
|
||||
// after extend_from_slice completes.
|
||||
let samples_slice = unsafe {
|
||||
std::slice::from_raw_parts(data_ptr, total_samples)
|
||||
};
|
||||
|
||||
audio_samples.extend_from_slice(samples_slice);
|
||||
}
|
||||
|
||||
// Calculate duration
|
||||
let total_samples_per_channel = audio_samples.len() / channels as usize;
|
||||
let duration = total_samples_per_channel as f64 / sample_rate as f64;
|
||||
|
||||
Ok(Some(ExtractedAudio {
|
||||
samples: audio_samples,
|
||||
channels,
|
||||
sample_rate,
|
||||
duration,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Integration tests for the SQLite-backed `.beam` container.
|
||||
//!
|
||||
//! These are integration tests (not `#[cfg(test)]` unit tests) so they build the
|
||||
//! library in normal mode and exercise only the public API — independent of any
|
||||
//! pre-existing breakage in the crate's internal test modules.
|
||||
|
||||
use lightningbeam_core::beam_archive::{BeamArchive, MediaKind, MediaMeta, MediaStorage};
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
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!("beam_archive_it_{}_{}_{}.beam", std::process::id(), tag, n));
|
||||
let _ = std::fs::remove_file(&p);
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_json_roundtrip() {
|
||||
let path = temp_db_path("json");
|
||||
let archive = BeamArchive::create(&path).unwrap();
|
||||
archive.set_project_json("{\"hello\":\"world\"}").unwrap();
|
||||
assert_eq!(archive.get_project_json().unwrap(), "{\"hello\":\"world\"}");
|
||||
drop(archive);
|
||||
let archive = BeamArchive::open(&path).unwrap();
|
||||
assert_eq!(archive.get_project_json().unwrap(), "{\"hello\":\"world\"}");
|
||||
assert!(BeamArchive::is_sqlite(&path));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_media_roundtrip_full() {
|
||||
let path = temp_db_path("full");
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
let id = Uuid::from_u128(0x1234);
|
||||
archive.set_chunk_size(1000);
|
||||
let data: Vec<u8> = (0..3500u32).map(|i| (i % 251) as u8).collect();
|
||||
archive
|
||||
.put_media_packed(
|
||||
id,
|
||||
MediaKind::Audio,
|
||||
"flac",
|
||||
&data,
|
||||
MediaMeta { channels: Some(2), sample_rate: Some(44100), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let info = archive.media_info(id).unwrap().unwrap();
|
||||
assert_eq!(info.kind, MediaKind::Audio);
|
||||
assert_eq!(info.codec, "flac");
|
||||
assert_eq!(info.storage, MediaStorage::Packed);
|
||||
assert_eq!(info.total_len, 3500);
|
||||
assert_eq!(info.channels, Some(2));
|
||||
assert_eq!(info.sample_rate, Some(44100));
|
||||
|
||||
assert_eq!(archive.read_media_full(id).unwrap(), data);
|
||||
assert_eq!(archive.media_ids_of_kind(MediaKind::Audio).unwrap(), vec![id]);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blob_reader_streams_and_seeks() {
|
||||
let path = temp_db_path("stream");
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
archive.set_chunk_size(1000);
|
||||
let id = Uuid::from_u128(0xBEEF);
|
||||
let data: Vec<u8> = (0..3500u32).map(|i| (i % 251) as u8).collect();
|
||||
archive
|
||||
.put_media_packed(id, MediaKind::Audio, "mp3", &data, MediaMeta::default())
|
||||
.unwrap();
|
||||
|
||||
let mut reader = archive.open_blob_reader(&path, id).unwrap();
|
||||
assert_eq!(reader.len(), 3500);
|
||||
|
||||
// Sequential read in odd-sized buffers crosses chunk boundaries.
|
||||
let mut got = Vec::new();
|
||||
let mut buf = [0u8; 333];
|
||||
loop {
|
||||
let n = reader.read(&mut buf).unwrap();
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
got.extend_from_slice(&buf[..n]);
|
||||
}
|
||||
assert_eq!(got, data);
|
||||
|
||||
// Seek to a mid-chunk position and read across a boundary.
|
||||
reader.seek(SeekFrom::Start(990)).unwrap();
|
||||
let mut window = [0u8; 20];
|
||||
let mut filled = 0;
|
||||
while filled < window.len() {
|
||||
let n = reader.read(&mut window[filled..]).unwrap();
|
||||
assert!(n > 0);
|
||||
filled += n;
|
||||
}
|
||||
assert_eq!(&window[..], &data[990..1010]);
|
||||
|
||||
// Seek from end and read the tail.
|
||||
reader.seek(SeekFrom::End(-10)).unwrap();
|
||||
let mut tail = Vec::new();
|
||||
reader.read_to_end(&mut tail).unwrap();
|
||||
assert_eq!(tail, &data[3490..]);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn referenced_media_records_path() {
|
||||
let path = temp_db_path("ref");
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
let id = Uuid::from_u128(0xCAFE);
|
||||
archive
|
||||
.put_media_referenced(
|
||||
id,
|
||||
MediaKind::Video,
|
||||
"mp4",
|
||||
"/mnt/share/big.mp4",
|
||||
MediaMeta { width: Some(3840), height: Some(2160), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
let info = archive.media_info(id).unwrap().unwrap();
|
||||
assert_eq!(info.storage, MediaStorage::Referenced);
|
||||
assert_eq!(info.ext_path.as_deref(), Some("/mnt/share/big.mp4"));
|
||||
assert_eq!(info.width, Some(3840));
|
||||
// Streaming a referenced item is an error (caller opens the path directly).
|
||||
assert!(archive.open_blob_reader(&path, id).is_err());
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_groups_writes_and_orphan_cleanup() {
|
||||
let path = temp_db_path("txn");
|
||||
let keep = Uuid::from_u128(1);
|
||||
let orphan = Uuid::from_u128(2);
|
||||
|
||||
// First save: two media items committed in one transaction.
|
||||
{
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
let txn = archive.transaction().unwrap();
|
||||
txn.put_media_packed(keep, MediaKind::Audio, "flac", &vec![9u8; 10], MediaMeta::default())
|
||||
.unwrap();
|
||||
txn.put_media_packed(orphan, MediaKind::Audio, "mp3", &vec![8u8; 10], MediaMeta::default())
|
||||
.unwrap();
|
||||
txn.set_project_json("{}").unwrap();
|
||||
txn.commit().unwrap();
|
||||
}
|
||||
{
|
||||
let archive = BeamArchive::open(&path).unwrap();
|
||||
assert!(archive.media_info(keep).unwrap().is_some());
|
||||
assert!(archive.media_info(orphan).unwrap().is_some());
|
||||
}
|
||||
|
||||
// Second save (in place): keep only `keep`; `orphan` should be retained-out.
|
||||
{
|
||||
let mut archive = BeamArchive::open(&path).unwrap();
|
||||
let txn = archive.transaction().unwrap();
|
||||
// `keep` already present → in-place save leaves it untouched.
|
||||
assert!(txn.media_exists(keep).unwrap());
|
||||
let mut live = std::collections::HashSet::new();
|
||||
live.insert(keep);
|
||||
let removed = txn.retain_media(&live).unwrap();
|
||||
assert_eq!(removed, 1);
|
||||
txn.commit().unwrap();
|
||||
}
|
||||
{
|
||||
let archive = BeamArchive::open(&path).unwrap();
|
||||
assert!(archive.media_info(keep).unwrap().is_some());
|
||||
assert!(archive.media_info(orphan).unwrap().is_none());
|
||||
// `keep`'s bytes survived untouched.
|
||||
assert_eq!(archive.read_media_full(keep).unwrap(), vec![9u8; 10]);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolled_back_transaction_writes_nothing() {
|
||||
let path = temp_db_path("rollback");
|
||||
let id = Uuid::from_u128(42);
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
{
|
||||
let txn = archive.transaction().unwrap();
|
||||
txn.put_media_packed(id, MediaKind::Audio, "flac", &vec![1u8; 5], MediaMeta::default())
|
||||
.unwrap();
|
||||
// Drop without commit → rollback.
|
||||
}
|
||||
assert!(archive.media_info(id).unwrap().is_none());
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overwrite_media_replaces_chunks() {
|
||||
let path = temp_db_path("overwrite");
|
||||
let mut archive = BeamArchive::create(&path).unwrap();
|
||||
archive.set_chunk_size(100);
|
||||
let id = Uuid::from_u128(7);
|
||||
archive
|
||||
.put_media_packed(id, MediaKind::Raster, "png", &vec![1u8; 250], MediaMeta::default())
|
||||
.unwrap();
|
||||
// Overwrite with shorter data — stale chunks must be gone.
|
||||
archive
|
||||
.put_media_packed(id, MediaKind::Raster, "png", &vec![2u8; 50], MediaMeta::default())
|
||||
.unwrap();
|
||||
assert_eq!(archive.read_media_full(id).unwrap(), vec![2u8; 50]);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
Reference in New Issue
Block a user