mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-02 02:34:37 -06:00
interchange: read AAF WAVE and PCM descriptors through craft-aaf (craft-libs#778)
Open FilmCraft-style AAFs that reference one external mono PCM WAV per channel. The file descriptor's class, SampleRate, Length and declared PCM channel count come from craft_aaf::aaf::linked_audio (craft-libs#3180); locators, slot policy and limits stay here.
This commit is contained in:
Generated
+1
@@ -5026,6 +5026,7 @@ name = "soundcraft-engine"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"craft-aaf",
|
||||
"craft-audio",
|
||||
"craft-docpath",
|
||||
"craft-score",
|
||||
|
||||
@@ -33,6 +33,7 @@ winsafe = { version = "0.0.29", features = ["kernel"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cfb.workspace = true
|
||||
craft-aaf.workspace = true
|
||||
proptest.workspace = true
|
||||
zip.workspace = true
|
||||
|
||||
|
||||
@@ -437,3 +437,105 @@ fn repeated_local_mob_references_fail_before_property_expansion() {
|
||||
let err = f.preview().unwrap_err().to_string();
|
||||
assert!(err.contains("duplicate local reference in mobs"), "{err}");
|
||||
}
|
||||
|
||||
/// A FilmCraft-style AAF that references one external mono PCM WAV per channel, written by the
|
||||
/// shared `craft-aaf` writer around WAVs generated here.
|
||||
struct MonoWavAaf {
|
||||
dir: PathBuf,
|
||||
}
|
||||
impl MonoWavAaf {
|
||||
fn new(wav_channels: usize) -> Self {
|
||||
use craft_aaf::model::{CClip, CItem, CKind, CTrack, Composition, Document, Source};
|
||||
use craft_aaf::time::{FrameRate, Tick};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-aaf-mono-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let frames = 96_000;
|
||||
let options = EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(BitDepth::Int16);
|
||||
let mut sources = Vec::new();
|
||||
let mut tracks = Vec::new();
|
||||
for (i, name) in ["Dialogue.A1.wav", "Dialogue.A2.wav"].into_iter().enumerate() {
|
||||
let audio = AudioBuffer { sample_rate: 48000, channels: vec![vec![0.25; frames]; wav_channels] };
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, craft_audio::encode(&audio, &options).unwrap()).unwrap();
|
||||
sources.push(Source {
|
||||
key: "item:1".into(),
|
||||
name: name.into(),
|
||||
kind: CKind::Sound,
|
||||
path: Some(path.display().to_string()),
|
||||
channel: None,
|
||||
channels: 1,
|
||||
file_channels: 1,
|
||||
width: 0,
|
||||
height: 0,
|
||||
frame_rate: FrameRate::FPS_25,
|
||||
sample_rate: 48000,
|
||||
bits: 16,
|
||||
length: Tick::from_units(frames as i64, 48000),
|
||||
offset: Tick::ZERO,
|
||||
start_tc: None,
|
||||
tc_rate: FrameRate::FPS_25,
|
||||
embedded: None,
|
||||
markers: Vec::new(),
|
||||
nested: None,
|
||||
});
|
||||
let clip = CClip { len: Tick::from_units(25, 25), source: i, start: Tick::ZERO, gain: None, name: format!("Cut {}", i + 1) };
|
||||
tracks.push(CTrack {
|
||||
kind: CKind::Sound,
|
||||
name: format!("A{}", i + 1),
|
||||
number: i as u32 + 1,
|
||||
channels: 1,
|
||||
items: vec![CItem::Clip(clip)],
|
||||
});
|
||||
}
|
||||
let composition = Composition {
|
||||
name: "Separate mono".into(),
|
||||
aaf_mob_id: None,
|
||||
rate: FrameRate::FPS_25,
|
||||
sample_rate: 48000,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
start_tc: 0,
|
||||
drop: false,
|
||||
tracks,
|
||||
markers: Vec::new(),
|
||||
};
|
||||
let doc = Document { compositions: vec![composition], sources, ..Document::default() };
|
||||
let identity =
|
||||
craft_aaf::Identity { company: "Craft", product: "soundcraft tests", version: "1", platform: "test", product_id: *b"soundcraft-test." };
|
||||
let bytes =
|
||||
craft_aaf::aaf::write(&doc, &craft_aaf::aaf::WriteOptions { identity, small_sectors: false }, &mut craft_aaf::Report::default()).unwrap();
|
||||
std::fs::write(dir.join("Separate mono.aaf"), bytes).unwrap();
|
||||
Self { dir }
|
||||
}
|
||||
fn preview(&self) -> soundcraft_engine::Result<Value> {
|
||||
Engine::default().execute("file.preview_aaf", &json!({"path": self.dir.join("Separate mono.aaf"), "media_dir": self.dir}))
|
||||
}
|
||||
}
|
||||
impl Drop for MonoWavAaf {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_mono_pcm_wav_aaf_imports_one_mono_track_per_file() {
|
||||
let f = MonoWavAaf::new(1);
|
||||
let preview = f.preview().unwrap();
|
||||
let plan = &preview["plan"];
|
||||
let channels: Vec<_> = plan["sources"].as_array().unwrap().iter().map(|s| s["channels"].as_u64().unwrap()).collect();
|
||||
assert_eq!(channels, [1, 1]);
|
||||
let mut e = Engine::default();
|
||||
e.execute("file.import_aaf", &json!({"plan": plan, "media_dir": f.dir, "selected": [0, 1]})).unwrap();
|
||||
assert_eq!(e.session().tracks.len(), 2);
|
||||
assert!(e.session().tracks.iter().all(|t| t.channels() == 1 && t.clips().len() == 1));
|
||||
let sources: Vec<_> = e.session().tracks.iter().map(|t| t.clips()[0].source()).collect();
|
||||
assert_ne!(sources[0], sources[1], "each channel file is its own source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pcm_descriptor_whose_channel_count_differs_from_its_wav_is_refused() {
|
||||
let f = MonoWavAaf::new(2);
|
||||
let err = f.preview().unwrap_err().to_string();
|
||||
assert!(err.contains("channel counts differ"), "{err}");
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! Reads the AAF structured-storage object model directly (properties streams, strong
|
||||
//! reference vectors/sets and dictionary weak references) for a deliberately small subset:
|
||||
//! one CompositionMob whose timeline slots hold Sequences of SourceClip and Filler, resolved
|
||||
//! through MasterMobs to SourceMobs with a WAVEDescriptor and one external NetworkLocator.
|
||||
//! through MasterMobs to SourceMobs with a WAVE or PCM descriptor and one external NetworkLocator.
|
||||
//! Anything else in an audio slot aborts instead of producing a misleading montage.
|
||||
//!
|
||||
//! No filesystem access happens here: the caller passes the opened AAF and a [`MediaResolver`]
|
||||
@@ -32,6 +32,7 @@
|
||||
//! locator resolves under the AAF's folder (see `locator_path`). A file that cannot be found
|
||||
//! is reported and its edits skipped; it does not abort the import.
|
||||
use crate::{ImportClip, ImportError, ImportTrack, Media, Plan, Rational, TimecodeRate};
|
||||
use craft_aaf::aaf::linked_audio::{AudioFileDescriptor, DescriptorFieldError, DescriptorKind, DescriptorProperty};
|
||||
use craft_aaf::aaf::properties::{Properties, Property, PropertyError};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
@@ -80,8 +81,6 @@ const PID_CONTENT_ESSENCE: u16 = 0x1902;
|
||||
const PID_DEF_NAME: u16 = 0x1B02;
|
||||
const PID_ESSENCE_MOB_ID: u16 = 0x2701;
|
||||
const PID_DESCRIPTOR_LOCATORS: u16 = 0x2F01;
|
||||
const PID_FILE_SAMPLE_RATE: u16 = 0x3001;
|
||||
const PID_FILE_LENGTH: u16 = 0x3002;
|
||||
const PID_HEADER_CONTENT: u16 = 0x3B03;
|
||||
const PID_URL_STRING: u16 = 0x4001;
|
||||
const PID_MOB_ID: u16 = 0x4401;
|
||||
@@ -230,6 +229,8 @@ impl Q {
|
||||
struct Obj {
|
||||
path: String,
|
||||
class: String,
|
||||
/// The class AUID in on-disk byte order, as the shared descriptor view classifies it.
|
||||
auid: [u8; 16],
|
||||
// Cached objects are cloned along source and dictionary walks; share their property payload.
|
||||
props: Rc<HashMap<u16, (u16, Vec<u8>)>>,
|
||||
}
|
||||
@@ -269,6 +270,16 @@ impl Obj {
|
||||
fn is(&self, class: &str) -> bool {
|
||||
self.class == class
|
||||
}
|
||||
/// The shared typed view of a WAVE or PCM file descriptor (craft-libs#3180); `None` for any
|
||||
/// other class.
|
||||
fn audio_descriptor<'a>(&'a self) -> Option<AudioFileDescriptor<impl Fn(u16) -> DescriptorProperty<'a> + 'a>> {
|
||||
let kind = DescriptorKind::from_auid_le(self.auid)?;
|
||||
Some(AudioFileDescriptor::new(kind, move |pid| match self.props.get(&pid) {
|
||||
None => DescriptorProperty::Missing,
|
||||
Some((form, data)) if *form == SF_DATA => DescriptorProperty::Data(data),
|
||||
Some(_) => DescriptorProperty::OtherForm,
|
||||
}))
|
||||
}
|
||||
/// Class name for messages; unknown (extension) classes print their AUID.
|
||||
fn kind(&self) -> &str {
|
||||
CLASS_NAMES.iter().find(|(id, _)| *id == self.class).map_or(self.class.as_str(), |(_, n)| n)
|
||||
@@ -295,6 +306,13 @@ fn property_error(path: &str, e: PropertyError) -> ImportError {
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor_error(field: &str, e: DescriptorFieldError) -> ImportError {
|
||||
match e {
|
||||
DescriptorFieldError::Missing | DescriptorFieldError::Truncated => fail(format!("missing or short descriptor {field}")),
|
||||
DescriptorFieldError::OtherForm => fail(format!("descriptor {field} is not a data property")),
|
||||
}
|
||||
}
|
||||
|
||||
fn property_total(current: usize, additional: usize) -> Result<usize> {
|
||||
current.checked_add(additional).filter(|total| *total <= MAX_PROPERTY_BYTES).ok_or_else(|| fail("AAF retained property data exceeds 128 MiB"))
|
||||
}
|
||||
@@ -391,6 +409,7 @@ impl<F: Read + Seek> Store<F> {
|
||||
return Err(fail(format!("{path}: not an AAF object")));
|
||||
}
|
||||
let class = entry.clsid().to_string();
|
||||
let auid = entry.clsid().to_bytes_le();
|
||||
let props_path = if path == "/" { "/properties".to_string() } else { format!("{path}/properties") };
|
||||
let d = self.stream(&props_path)?.ok_or_else(|| fail(format!("{path}: missing properties")))?;
|
||||
if d.first() != Some(&0x4c) {
|
||||
@@ -411,7 +430,7 @@ impl<F: Read + Seek> Store<F> {
|
||||
let Property { id, form, payload } = record.map_err(|e| property_error(path, e))?;
|
||||
props.insert(id, (form, payload.to_vec()));
|
||||
}
|
||||
let object = Obj { path: path.to_string(), class, props: Rc::new(props) };
|
||||
let object = Obj { path: path.to_string(), class, auid, props: Rc::new(props) };
|
||||
self.objects.insert(path.to_string(), object.clone());
|
||||
Ok(object)
|
||||
}
|
||||
@@ -670,7 +689,7 @@ impl<F: Read + Seek> Builder<'_, F> {
|
||||
}
|
||||
if mob.is(CLASS_SOURCE_MOB) {
|
||||
let desc = self.store.opt_strong(&mob, PID_SOURCE_MOB_DESCRIPTOR, "EssenceDescription")?;
|
||||
if let Some(desc) = desc.filter(|d| d.is(CLASS_WAVE_DESCRIPTOR)) {
|
||||
if let Some(desc) = desc.filter(|d| d.audio_descriptor().is_some()) {
|
||||
return self.file_source(&mob, &slot, &desc, key_urn, offset);
|
||||
}
|
||||
}
|
||||
@@ -691,8 +710,10 @@ impl<F: Read + Seek> Builder<'_, F> {
|
||||
}
|
||||
|
||||
fn file_source(&mut self, mob: &Obj, slot: &Obj, desc: &Obj, key: String, offset: Q) -> Result<(String, Q)> {
|
||||
// Full interleaved WAV only: selecting one physical channel needs a channel map.
|
||||
if !matches!(slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?, None | Some(0)) {
|
||||
// Full interleaved WAV only: selecting one physical channel needs a channel map. Track 1
|
||||
// of a mono file is the whole file (checked once the file is probed).
|
||||
let physical = slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?;
|
||||
if !matches!(physical, None | Some(0 | 1)) {
|
||||
return Err(fail("Physical channel selection / split stereo unsupported"));
|
||||
}
|
||||
// Each source file is located, probed and reported once, however many edits use it.
|
||||
@@ -721,12 +742,23 @@ impl<F: Read + Seek> Builder<'_, F> {
|
||||
if !matches!(info.channels, 1 | 2) {
|
||||
return Err(fail("Only mono/stereo PCM WAV supported"));
|
||||
}
|
||||
if desc.rational(PID_FILE_SAMPLE_RATE, "descriptor SampleRate")? != Q::int(i64::from(info.sample_rate)) {
|
||||
let fields =
|
||||
desc.audio_descriptor().ok_or_else(|| fail(format!("Unsupported referenced mob/descriptor: {}", name.clone().unwrap_or_default())))?;
|
||||
let (num, den) = fields.sample_rate().map_err(|e| descriptor_error("SampleRate", e))?;
|
||||
if Q::new(i128::from(num), i128::from(den))? != Q::int(i64::from(info.sample_rate)) {
|
||||
return Err(fail(format!("Descriptor/file sample rates differ: {}", name.unwrap_or_default())));
|
||||
}
|
||||
if u64::try_from(desc.i64(PID_FILE_LENGTH, "descriptor Length")?).ok() != Some(info.frames) {
|
||||
if u64::try_from(fields.length().map_err(|e| descriptor_error("Length", e))?).ok() != Some(info.frames) {
|
||||
return Err(fail(format!("Descriptor/file lengths differ: {}", name.unwrap_or_default())));
|
||||
}
|
||||
if let Some(declared) = fields.pcm_channels().map_err(|e| descriptor_error("Channels", e))?
|
||||
&& declared != u32::from(info.channels)
|
||||
{
|
||||
return Err(fail(format!("Descriptor/file channel counts differ: {}", name.unwrap_or_default())));
|
||||
}
|
||||
if physical == Some(1) && info.channels != 1 {
|
||||
return Err(fail("Physical channel selection / split stereo unsupported"));
|
||||
}
|
||||
let stem = Path::new(&info.path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
self.sources.push(Media {
|
||||
key: key.clone(),
|
||||
|
||||
Reference in New Issue
Block a user