Rust bindings¶
Two crates over the C API, both in-tree under
bindings/rust/:
iclforge-sys: raw FFI declarations, generated bybindgenfromiclforge_c/iclforge.h. Its build script compiles the C library from the same checkout and regenerates the declarations at every build, so the two cannot drift apart.iclforge: a safe wrapper withResultandOptionin place of status codes and out-parameters, owned handles that free themselves on drop, and slices in place of raw pointers.
The crates cover most of the C API's scope: AC-3, E-AC-3, Atmos (OAMD + JOC) and AC-4 (iclforge::ac4,
below) — see AC-4 for the wider C++ library both mirror a subset of. The C API's TrueHD and MLP
functions (iclforge_truehd_*) are declared in iclforge-sys and wrapped by nothing, and build.rs lists no
libs/truehd path (What is not wrapped).
Cargo is not part of the root CMake build, the same arrangement as apps/demos/android and Gradle. CI
builds and tests the workspace on Linux, Windows and macOS (build-rust in
.github/workflows/_build.yml: cargo build, cargo test, cargo clippy -D warnings,
cargo fmt --check), against the toolchain pinned in bindings/rust/rust-toolchain.toml. Build
prerequisites (CMake, a C++23 compiler, libclang) and how the shared library is found at run time
are in
bindings/rust/README.md.
Encoding¶
Every config type calls the raw iclforge_*_config_init() function through Default::default()
and lets you override only the fields you need, the _init() convention the C header documents.
The Rust side never restates a C++ default. ObjectPlacement::default() follows the same rule and
gives room centre, unity gain and no LFE send.
let config = EncoderConfig {
sample_rate: SampleRate::Hz48000,
bitrate_kbps: 192,
acmod: Acmod::Stereo,
..Default::default()
};
let mut encoder = Encoder::new(&config).expect("failed to create AC-3 encoder");
That excerpt is from
bindings/rust/iclforge/examples/encode_decode_ac3.rs;
encode_decode_eac3.rs
is the E-AC-3 counterpart. Both run with cargo run --example <name> -p iclforge.
Decoding¶
Decoder and Eac3Decoder mirror iclforge_decoder_t and iclforge_eac3_decoder_t. Every
accessor on a DecodedFrame, DecodedSubstream or DecodedAccessUnit borrows from &self, so a
slice from channel_samples() cannot outlive the frame it came from. The compiler enforces the
"valid until destroyed" contract the C header states (see C API).
Eac3Decoder::decode_substream and decode_access_unit return Result<Option<_>, Error>. None
is not an error: transient pre-noise processing is holding that frame's PCM back, and flush()
collects it at the end of the stream. The C API reports the same case as ICLFORGE_OK with a null
out-parameter.
let decoded = decoder
.decode_substream(&encoded)
.expect("decode_substream failed")
.expect("auto_tools without transient pre-noise never holds a frame back");
That excerpt is from encode_decode_eac3.rs.
Karaoke and lyrics¶
Decoder::with_karaoke(&DecoderConfig, &KaraokeConfig) (iclforge_decoder_create_with_karaoke)
reproduces an Annex C karaoke stream - bsmod 7 with a layout above mono, L and R, a guide melody
and one or two vocals - as a karaoke-aware or karaoke-capable decoder does. Build a
KaraokeConfig from Default::default() (off, both vocals, every level 0 dB) and override what
you need:
let karaoke = KaraokeConfig {
reproduction: KaraokeReproduction::Capable,
vocals: KaraokeVocals::V1,
melody_db: -6.0, // against Table C.2.3; 0.0 is the table, KARAOKE_MIN_LEVEL_DB is off
..Default::default()
};
let mut decoder = Decoder::with_karaoke(&DecoderConfig::default(), &karaoke)?;
let frame = decoder.decode_frame(syncframe)?;
if frame.karaoke_reproduced() {
// three channels (four with the LFE): L, C, R where five were coded.
assert_eq!(frame.output_acmod(), Some(Acmod::Channels3_0));
}
DecodedFrame::acmod() still says what was coded; output_acmod() and output_lfe() say what
channel_count() and channel_samples() are, is_karaoke() and bsmod() what the stream is, and
karaoke_reproduced() whether the decoder replaced the layout. The levels are the capable
decoder's alone, over KARAOKE_MIN_LEVEL_DB to KARAOKE_MAX_LEVEL_DB (-24, which is off, to 12),
the span and units Hearth's sliders use. The reproduction is the 3/0 form; Eac3Decoder and AC-4
have none (C API).
iclforge::lyrics::Lyrics::parse(&bytes, duration_ms) reads a lyrics file's bytes - LRC in UTF-8
or UTF-16, SubRip, Advanced SubStation Alpha or MIDI karaoke, told by their content - and refuses
the rest with LyricsError::Unreadable(reason). lines() and Line::words() borrow the lyrics;
position(position_ms, delay_ms) is the stateless cursor and Word::state(position_ms) says
whether a word is sung, being sung or not yet. The reader is compiled into the C library from
libs/lyrics; reading a file is the caller's, as the C API's is.
AC-4¶
iclforge::ac4 wraps iclforge_ac4_decoder_t/iclforge_ac4_encoder_t (ETSI TS 103 190-1 V1.4.1,
TS 103 190-2 V1.3.1) the same way iclforge::ac3 wraps the AC-3 C API — Decoder/Encoder with
Result/Option in place of status codes and out-parameters, DecoderConfig/EncoderConfig
built through Default::default() (which calls the raw iclforge_ac4_*_config_init() first, same
"never restate a C++ default" rule as every other config type in this crate). No Cargo feature
gates it. The C library has ICLFORGE_BUILD_AC4, but iclforge-sys's build script leaves it at its
default, on, so the module is always there; a C library built without AC-4 answers every AC-4 call
with ICLFORGE_ERROR_UNSUPPORTED, which iclforge::Error reports as Error::Other(4).
use iclforge::ac4::{Decoder, DecoderConfig, Encoder, EncoderConfig};
let config = EncoderConfig { channels: 6, bitrate_kbps: 256, ..Default::default() }; // 5.1
let mut encoder = Encoder::new(&config).expect("failed to create AC-4 encoder");
let mut decoder = Decoder::new(&DecoderConfig::default()).expect("failed to create AC-4 decoder");
for frame in encoder.encode(&channels).unwrap() { // any equal-length spans, one per channel
if let Some(decoded) = decoder.decode(frame.data()).unwrap() { // None: no output yet, not an error
println!("{:?} {}", decoded.speaker(0), decoded.channel_samples(0).len());
}
}
That shape is bindings/rust/iclforge/tests/ac4_roundtrip.rs's; no
bindings/rust/iclforge/examples/ program covers AC-4. Encoder::encode takes any equal-length slices (the
encoder buffers input to its own frame length internally, unlike iclforge::Encoder::encode's fixed
frame), and Encoder::flush pads to the end of the last frame and returns whatever the delay still
held. Encoder::toc() returns a Toc — build_dac4(), dac4_refusal(), media_timing() and
samples_per_frame() for a container muxer, mirroring iclforge_ac4_toc_t — and the free function
iclforge::ac4::sync_frame() wraps a raw frame with Annex G.3.1's sync word and an optional CRC.
Encoder::codec_mode() is what kAuto chose, and delay_samples() and decoder_delay_samples()
say where an input sample lands in the decoded output.
Decoder::decode returns Result<Option<DecodedFrame>, Error>: None means the frame has no
output yet, not an error, the same convention Eac3Decoder::decode_substream uses above.
DecodedFrame::channel_samples/speaker borrow from &self, so a slice cannot outlive the frame
it came from — samples_per_channel() is a real per-frame method rather than a crate-wide
constant, since AC-4's frame length varies by frame rate. Decoder::presentations() reads the last
frame's table of contents; Decoder::metadata_loudness() reads the selected presentation's
loudness fields; set_output() and set_presentation() change the output processing and the
chosen presentation from the next frame, and refusal_reason(), latency_samples() and reset()
are the C++ decoder's own. DecodedFrame::objects() reads whatever object audio a presentation carries —
empty for channel-based and channel-based-immersive content (mono, stereo, 5.0, 5.1, 5.0.4, 5.1.4)
— each DecodedObject with its properties in force at the frame's first sample and its
updates within the frame (ObjectUpdate: the output sample it takes effect at, ramp_samples
and properties).
Every ICLFORGE_ERROR_AC4_* status gets its own Error variant (Ac4DecodeTruncated,
Ac4DecodeInvalidToc, Ac4DecodeInvalidStream, Ac4DecodeUnsupported,
Ac4DecodeMissingIFrame, Ac4EncodeInvalidConfig, Ac4EncodeInvalidInput) rather than folding
into Error::Other — unlike the scan errors below, which do not. Encoder::refusal_reason(&config)
says which rule an Ac4EncodeInvalidConfig breaks.
Encoding objects¶
EncoderConfig::objects takes an ObjectsConfig — a Vec<ObjectConfig> (one input channel each:
a bed object from a BedChannel, a dynamic object, or the LFE, with the ObjectProperties in
force from the first sample) and how they are coded (ObjectCoding, AjocDownmix,
downmix_signals, decorrelation, parameter_bands and the rest of iclforge::ac4::ObjectsConfig) — and
the object substream is experimental, so experimental.objects has to be set beside it.
ObjectProperties is the struct DecodedObject::properties returns and the encoder takes the same
fields (position, gain_db, priority, width, zone_mask, screen_factor,
depth_exponent, distance, divergence, headphone_render_mode and the rest, each with its
range and step in its doc comment); ObjectProperties::default() calls the raw
iclforge_ac4_object_properties_init(), so it has the C++ defaults (priority 1, depth exponent 1,
the room's centre). EncoderConfig owns vectors now (iframes, fragment_starts, the objects),
so it is Clone and not Copy.
use iclforge::ac4::{
BedChannel, Encoder, EncoderConfig, Experimental, ObjectConfig, ObjectMetadataUpdate,
ObjectProperties, ObjectsConfig,
};
let config = EncoderConfig {
bitrate_kbps: 256,
experimental: Experimental { objects: true, ..Default::default() },
objects: Some(ObjectsConfig {
objects: vec![
ObjectConfig {
properties: ObjectProperties { position: [0.1, 0.2, 0.0], gain_db: -3.0, ..Default::default() },
..Default::default()
},
ObjectConfig { lfe: true, ..Default::default() },
ObjectConfig { bed: Some(BedChannel::Left), ..Default::default() },
],
..Default::default()
}),
..Default::default()
};
let mut encoder = Encoder::new(&config)
.unwrap_or_else(|_| panic!("{}", Encoder::refusal_reason(&config)));
// One slice of PCM per object, and the changes to the objects' metadata with the input they
// belong to: from input sample 5000 of this call, object 0 moves over 1024 samples.
let moves = [ObjectMetadataUpdate {
object: 0,
sample: 5000,
ramp_samples: 1024,
properties: ObjectProperties { position: [0.75, 0.25, 0.4], gain_db: -12.0, ..Default::default() },
}];
let frames = encoder.encode_objects(&pcm, &moves).unwrap();
The limits are the encoder's: 1 to ICLFORGE_AC4_MAX_OBJECTS (64) objects, at most one the LFE and at
least one that is not; frame_rate_index 13 only; an A-JOC downmix of 1 to
ICLFORGE_AC4_MAX_DOWNMIX_SIGNALS (11) signals, no more than there are full-band objects, or a
static 5.0 or 5.1 bed; direct-coded objects are dynamic objects and the LFE with no bed objects. An
update for an object the configuration lacks, before the input's first sample, or with a property
off its range is Ac4EncodeInvalidInput. The decoder reports the objects in its own order, not the
encoder's: the LFE first, then the bed objects, then the dynamic objects, each group in the order
the configuration lists it.
Tests are in bindings/rust/iclforge/tests/ac4_roundtrip.rs
and ac4_objects.rs:
stereo and 5.1 round trips against real synthesized tones (checked for signal level, not silence),
the 5.1 speaker order, a corrupted frame's decode failure, Toc/build_dac4/media_timing,
sync_frame's sync word and CRC byte, and the channel-count refusal above; and an A-JOC scene and
a direct-coded one encoded through the crate and through the raw iclforge_sys calls with structs
built by hand (the same bytes), read back within what each field's code can hold, with its own tone
and a metadata update at the sample its input sample comes out, with the limits, the I-frame lists
and the experimental flags held to the encoder.
What is covered¶
| Module | Wraps |
|---|---|
iclforge::ac3 |
Encoder, EncoderConfig (including dual mono, DRC, heavy compression and the mix levels), Decoder, DecodedFrame |
iclforge::ac3::eac3 |
Eac3Encoder, Eac3FrameConfig (the Annex E tools through auto_tools or the individual flags; substream identity and chanmap), Eac3FrameMetadata, AccessUnitEncoder and AccessUnit for wide layouts built from several substreams, Eac3Decoder with decode_substream, decode_access_unit and flush, DecodedSubstream, DecodedAccessUnit |
iclforge::atmos |
AtmosEncoder, AtmosConfig, ObjectPlacement; the OAMD and JOC accessors (has_object_metadata, dynamic_object, object_audio and their counts) on DecodedSubstream and DecodedAccessUnit |
iclforge::ac4 |
Encoder, EncoderConfig (with ObjectsConfig, ObjectConfig, Experimental, iframes and fragment_starts), ObjectMetadataUpdate, ObjectProperties, Decoder, DecoderConfig, OutputConfig, PresentationChoice, DecodedFrame (channels, speakers, concealment, objects and their ObjectUpdates), PresentationInfo, LoudnessInfo, Toc and sync_frame — see AC-4 above |
iclforge::ac3 (karaoke) |
Decoder::with_karaoke, KaraokeConfig, KaraokeReproduction, KaraokeVocals, and the bsmod, is_karaoke, output_acmod, output_lfe and karaoke_reproduced accessors of DecodedFrame |
iclforge::lyrics |
Lyrics::parse, LyricsError, Line, Word, Singer, WordState, LyricPosition |
iclforge::stream |
split_frames, split_access_units, stream_bsid, scan and ScannedStream (kind, sample rate, layout, rendered channel count, each access unit's slice and sample count, bsid, the Atmos complexity index). The slices borrow the input buffer |
iclforge::meter |
LoudnessMeter (the acmod/lfe constructor and the BS.1770-5 chanmap constructor) and dialnorm_from_lkfs |
iclforge |
Bytes (an owned encoded buffer that derefs to [u8]), Error, Latency and the latency accessors on the encoders and decoders, version(), SAMPLES_PER_FRAME |
iclforge::Error mirrors iclforge_status_t and adds Error::Other(u32) for a status value this
crate does not know, so a newer library cannot make it panic or report the wrong error. It has no
variants for the scan errors (ICLFORGE_ERROR_SCAN_*); a failed stream::scan reports
Error::Other with the raw code. A lyrics file the reader refuses is Error::LyricsUnreadable,
which lyrics::Lyrics::parse returns with the reason as LyricsError::Unreadable.
Tests are in bindings/rust/iclforge/tests/: round trips for every acmod/LFE combination, a wide-layout
5.1.2 encode and decode, Atmos objects round-tripped with their positions and audio, and the
stream and meter helpers.
What is not wrapped¶
The raw iclforge-sys crate declares every C function. The safe crate leaves these out, so
reaching them means calling iclforge_sys directly:
- the caller-buffer decode forms (
iclforge_decoder_decode_frame_into,iclforge_eac3_decoder_decode_access_unit_into); - the level meter (
iclforge_level_meter_*) and the QC gates (iclforge_qc_*,iclforge_evaluate_qc_gate); - the per-programme, timing and DVB/ATSC descriptor accessors of a scanned stream
(
iclforge_scanned_stream_programme_*,..._access_unit_timing,..._duration_*,..._associated_substream_*and the rawbsmod,dsurmodandchannel_mapfields); - the per-frame metadata words on decoded frames (
compr,dynrng, the second channel'sdialnorm2), a substream'schanmapand location map, the programme's bed and LFE flags, and a decoded access unit's layout; iclforge_latency_msand the bare sample-count latency functions (Latency::total_samples()sums the four terms instead).
The E-AC-3 config leaves out what the C struct leaves out, listed under
What is deliberately out of scope. Scene files
(iclforge::objects::oba::ObjectScene) are not in the C API and so not here either.
Notes for the next binding¶
Building this crate turned up four things about the C header, recorded in bindings/rust/README.md:
iclforge_object_placement_thad no_init(), unlike every other config struct, so a zero-initialized one encoded a muted object (gain0.0) rather than the documented unity gain.iclforge_object_placement_init()was added.- Four decoded-audio accessors lacked the pointer-lifetime comment their AC-3 sibling has. It was added.
- bindgen types C enums as
i32on MSVC andu32on the Unix targets, so a wrapper that stores a raw status must not assume either.Error::Othercasts on the way in and out. - The header does not say whether an enum may gain values in a later minor release. A binding
should treat C enums as open sets, which is why
Errorhas anOther(u32)variant.
Any binding should link forge_c_shared, which statically embeds the codec core, and should call
each _config_init function before overriding fields, since a zero-initialized struct is wrong for
several of them (dialnorm 0 is invalid).