Merge pull request #1378 from alehel/claude/packet-encoder-2064de

craft-audio: PacketEncoder, a codec-agnostic packet encoder (#1230 point 3)
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 11:01:44 +01:00
commit 7ecf7576bb
9 files changed
+1120 -362

No files matched your search

+2 -1
View File
@@ -24,7 +24,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-
# The symphonia fallback for the formats with no native decoder yet.
symphonia = ["decode-native", "dep:symphonia"]
# Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders.
# All but Opus are also file formats of `encode` and `FileEncoder`.
# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`.
encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"]
# Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files.
lossless-encode = ["pcm-encode", "flac-encode"]
@@ -54,6 +54,7 @@ qoa-encode = []
g722 = []
# ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s).
g726 = []
# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`.
opus-encode = []
# GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own.
gsm = ["gsm-decode", "gsm-encode"]
+72 -8
View File
@@ -34,17 +34,17 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none |
| `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` |
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` |
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` |
| `alac-decode` | `alac::Decoder` | none |
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` |
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none |
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` |
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | none |
| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` |
| `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` |
| `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` |
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` |
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` |
| `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` |
| `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` |
| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` |
| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` |
| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` |
| `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` |
| `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none |
@@ -313,12 +313,76 @@ file needs that step before it is written again.
An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame
written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no
place for that (see [Limits](#limits)). For a container of your own, use the codec modules below.
place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below.
### Encode packets for your own container
`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC,
ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export
to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded
formats through it.
```rust
use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder};
let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000);
let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?;
for block in blocks { // planar f32 in WAV order, any length
for p in enc.encode(&block.channels, block.frames())? {
mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate
}
}
for p in enc.finish()? {
mux.write(p.pts, p.duration, &p.data)?;
}
let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes
let priming = enc.priming(); // decoded samples before the first input frame
let padding = enc.padding(); // decoded samples after the last one
```
It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC
`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will
do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the
channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth.
`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count
(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose.
| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` |
|---|---|---|---|---|
| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 |
| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 |
| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 |
| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 |
| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip |
The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name;
Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec
with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take
get the error `EncodeOptions::check` gives for the format.
Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample,
so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder
returns every input frame, and the durations add up to `priming() + frames() + padding()`. With no
input there are no packets: the durations add up to 0 and `padding()` is 0, while `priming()` still
reports the codec's delay. A muxer
skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus:
the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit,
Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit
rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by
quality); `bit_depth()` is ALAC's.
`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`,
and encodes nothing; the encoder stays usable, so the caller can correct the block and call again.
After `finish`, or after encoding itself failed (the block's packets are lost), every call returns
an error.
E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see
[Limits](#limits)).
### Encode AAC packets
For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it,
for muxing into a container of your own:
For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order,
`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings
`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS):
```rust
use craft_audio::AudioError;
+21
View File
@@ -23,6 +23,9 @@
//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`,
//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder.
//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`,
//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC,
//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer.
//! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`],
//! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF
//! file bit for bit, and minimal files around such PCM, for essence embedded in other containers.
@@ -64,6 +67,15 @@ pub mod mp3;
pub mod mpa;
#[cfg(any(feature = "opus-decode", feature = "opus-encode"))]
pub mod opus;
#[cfg(any(
feature = "aac-encode",
feature = "alac-encode",
feature = "mp3-encode",
feature = "ac3-encode",
feature = "eac3-encode",
feature = "opus-encode"
))]
mod packet;
#[cfg(any(
feature = "aac-decode",
feature = "alac-decode",
@@ -157,6 +169,15 @@ pub use buffer::AudioBuffer;
pub use craft_media;
pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource};
pub use layout::{ChannelLayout, Speaker};
#[cfg(any(
feature = "aac-encode",
feature = "alac-encode",
feature = "mp3-encode",
feature = "ac3-encode",
feature = "eac3-encode",
feature = "opus-encode"
))]
pub use packet::{EncodedPacket, PacketEncoder};
#[cfg(feature = "decode-native")]
pub use read::SharedSource;
#[cfg(feature = "decode-native")]
+696
View File
@@ -0,0 +1,696 @@
//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for
//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order,
//! maps the channels onto the codec's order, and returns packets with their timing; the coded
//! formats of [`FileEncoder`](crate::FileEncoder) are written through it.
// Each codec is its own feature: with only some of them built, the other halves of the shared
// code are unused.
#![cfg_attr(
not(all(
feature = "aac-encode",
feature = "alac-encode",
feature = "mp3-encode",
feature = "ac3-encode",
feature = "eac3-encode",
feature = "opus-encode"
)),
allow(dead_code, unused_imports, unused_variables, unused_mut)
)]
use crate::layout::channel_map;
use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result};
/// Maximum frames handed to a codec per internal call, bounding that call's input and output.
/// `PacketEncoder::encode` collects packets across all chunks, so its returned vector grows with
/// the caller's input block. Also the frames of an ALAC packet.
pub(crate) const CHUNK: usize = 4096;
/// Bits per second per channel when no rate is asked for: AAC and Opus.
const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per
/// full-bandwidth channel).
const DEFAULT_KBPS_PER_CHANNEL: u32 = 96;
/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R).
const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]];
/// One packet from a [`PacketEncoder`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedPacket {
/// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame,
/// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet.
pub data: Vec<u8>,
/// Where the packet's decoded audio starts, in samples at the sample rate from the first
/// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first,
/// so input frame `n` is at `n + priming`.
pub pts: u64,
/// The samples per channel the packet decodes to, the last packet's padding included.
pub duration: u32,
}
/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side
/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the
/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control,
/// the layout, and for ALAC the bit depth and dither.
///
/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets
/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container
/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec,
/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout),
/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding).
///
/// | Codec | Feature | Packet | `extradata` | Priming |
/// |---|---|---|---|---|
/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 |
/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 |
/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 |
/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 |
/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip |
///
/// ```
/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] {
/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder};
///
/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000);
/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?;
/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel
/// let mut packets = enc.encode(&block, 4800)?;
/// packets.extend(enc.finish()?);
/// assert_eq!(enc.priming(), 1024);
/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::<u64>(), 1024 + 4800 + enc.padding());
///
/// // The description a muxer writes is what a decoder reads.
/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?;
/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024);
/// # }
/// # Ok::<(), craft_audio::AudioError>(())
/// ```
pub struct PacketEncoder {
codec: CodecId,
inner: Inner,
sample_rate: u32,
/// The speakers of the channels encoded, in WAV order.
layout: ChannelLayout,
/// For each codec channel, the caller's channel that feeds it.
map: Vec<usize>,
bitrate: Option<u32>,
/// The integer depth of a lossless codec.
bit_depth: Option<u8>,
/// Where the next packet starts.
pts: u64,
/// Frames of input taken.
frames: u64,
finished: bool,
/// Set when a call failed: the packets of that block are lost, so the stream has a gap and
/// every later call is refused.
failed: bool,
}
impl std::fmt::Debug for PacketEncoder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PacketEncoder")
.field("codec", &self.codec)
.field("sample_rate", &self.sample_rate)
.field("layout", &self.layout)
.field("frames", &self.frames)
.finish_non_exhaustive()
}
}
/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order.
enum Inner {
#[cfg(feature = "aac-encode")]
Aac(Box<crate::aac::Encoder>),
#[cfg(feature = "alac-encode")]
Alac {
enc: Box<crate::alac::Encoder>,
quantizers: Vec<crate::write::pcm::Quantizer>,
/// Quantized samples of the packet being filled, per channel.
pending: Vec<Vec<i32>>,
},
#[cfg(feature = "mp3-encode")]
Mp3 {
enc: Box<crate::mp3::Encoder>,
/// Bytes the encoder returned that do not yet make a whole frame.
bytes: Vec<u8>,
},
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Ac3 {
enc: Box<crate::ac3::encoder::Encoder>,
/// The block with every sample finite and within ±1, as the encoder requires.
planes: Vec<Vec<f32>>,
},
#[cfg(feature = "opus-encode")]
Opus {
enc: Box<crate::opus::encoder::Encoder>,
/// Interleaved samples of the frame being filled.
pending: Vec<f32>,
/// Frames of the decoded stream the packets so far cover.
coded: u64,
},
}
/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`.
fn labels(mask: u32) -> String {
ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::<Vec<_>>().join(" ")
}
/// The speakers of the caller's layout, for an error message.
fn given(layout: &ChannelLayout) -> String {
layout.mask().map_or_else(|| "without speaker assignment".into(), labels)
}
/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and
/// that layout; or why the audio does not fit.
fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec<usize>, ChannelLayout)> {
let Some(&mask) = masks.first() else {
return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels())));
};
let map = channel_map(mask, order, layout).ok_or_else(|| {
AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout)))
})?;
Ok((map, ChannelLayout::from_mask(mask)))
}
/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for
/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc.
#[cfg(feature = "aac-encode")]
pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> {
if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) }
}
/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256
/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a
/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s).
#[cfg(feature = "aac-encode")]
fn aac_floor_per_channel(sample_rate: u32) -> u32 {
(sample_rate / 4).max(6000)
}
/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a
/// quality of 0–1 spans the encoder's VBR range.
#[cfg(feature = "aac-encode")]
pub(super) fn aac_mode(rate: Option<RateControl>, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode {
use crate::aac::BitrateMode;
let (lo, hi) = crate::aac::cbr_range(sample_rate, channels);
let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo));
// An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone.
let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps };
match rate {
None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))),
Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)),
// NaN stays NaN, which the encoder refuses.
Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)),
}
}
/// The bit rate in bits per second for a codec with constant bit rates only.
fn constant_bps(name: &str, rate: Option<RateControl>, default: u32) -> Result<u32> {
match rate {
None => Ok(default),
Some(RateControl::Bitrate(bps)) => Ok(bps),
Some(RateControl::Quality(_)) => {
Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality")))
}
}
}
/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding
/// mode whose speakers the layout names, at the nearest bit rate the stream can carry.
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
pub(super) fn ac3_config(
codec: crate::ac3::encoder::Codec,
sample_rate: u32,
layout: &ChannelLayout,
rate: Option<RateControl>,
) -> Result<(crate::ac3::encoder::Config, Vec<usize>)> {
use crate::ac3::encoder::{Codec, CodingMode, Config};
use CodingMode::*;
let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" };
let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71];
let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| {
// 7.1 is an E-AC-3 programme with an LFE; the encoder has no other.
if mode == Surround71 && (codec != Codec::Eac3 || !lfe) {
return None;
}
let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe };
let map = channel_map(config.channel_layout().mask()?, None, layout)?;
Some((config, map))
});
let Some((mut config, map)) = found else {
return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout))));
};
let full = config.mode.channels() as u32;
let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000;
// What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of
// the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold.
let least = if config.mode == Surround71 { 384 } else { 32 * full };
config.bitrate_kbps = match codec {
Codec::Ac3 => {
let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least);
crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor)
}
Codec::Eac3 => {
let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 };
want.clamp(least, most.max(least))
}
};
Ok((config, map))
}
/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here.
fn feature(codec: CodecId) -> Option<&'static str> {
Some(match codec {
CodecId::Aac => "aac-encode",
CodecId::Alac => "alac-encode",
CodecId::Mp3 => "mp3-encode",
CodecId::Ac3 => "ac3-encode",
CodecId::Eac3 => "eac3-encode",
CodecId::Opus => "opus-encode",
_ => return None,
})
}
impl PacketEncoder {
/// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads
/// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of
/// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and
/// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored.
///
/// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none
/// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has
/// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A
/// rate, channel count, layout or rate control the codec cannot take is refused with the error
/// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control).
pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result<PacketEncoder> {
let Some(feature) = feature(codec) else {
return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name())));
};
let built = [
(CodecId::Aac, cfg!(feature = "aac-encode")),
(CodecId::Alac, cfg!(feature = "alac-encode")),
(CodecId::Mp3, cfg!(feature = "mp3-encode")),
(CodecId::Ac3, cfg!(feature = "ac3-encode")),
(CodecId::Eac3, cfg!(feature = "eac3-encode")),
(CodecId::Opus, cfg!(feature = "opus-encode")),
];
if !built.contains(&(codec, true)) {
return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name())));
}
let n = usize::from(channels);
// As the file writers word it.
if channels == 0 {
return Err(AudioError::Encode("buffer has no channels".into()));
}
if sample_rate == 0 {
return Err(AudioError::Encode("sample rate is 0".into()));
}
if let Some(layout) = &opts.layout
&& layout.channels() != channels
{
return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels())));
}
let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels));
let (inner, map, layout, bitrate, bit_depth) = match codec {
#[cfg(feature = "aac-encode")]
CodecId::Aac => {
let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?;
let mode = aac_mode(opts.rate_control, sample_rate, n);
let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) };
let bitrate = match mode {
crate::aac::BitrateMode::Cbr(bps) => Some(bps),
crate::aac::BitrateMode::Vbr(_) => None,
};
(Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None)
}
#[cfg(feature = "alac-encode")]
CodecId::Alac => {
let count = u8::try_from(channels).unwrap_or(u8::MAX);
let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?;
let bits = match opts.bit_depth {
crate::BitDepth::Int16 => 16,
crate::BitDepth::Int24 => 24,
crate::BitDepth::Int32 => 32,
crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())),
};
let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32);
let enc = crate::alac::Encoder::new(config)?;
let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n);
(Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits))
}
#[cfg(feature = "mp3-encode")]
CodecId::Mp3 => {
let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?;
let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000;
// A sample rate MP3 has not is the encoder's to refuse.
let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want);
let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?;
(Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None)
}
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
CodecId::Ac3 | CodecId::Eac3 => {
let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 };
let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?;
let enc = crate::ac3::encoder::Encoder::new(config)?;
let layout = enc.channel_layout();
let bitrate = Some(config.bitrate_kbps.saturating_mul(1000));
(Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None)
}
#[cfg(feature = "opus-encode")]
CodecId::Opus => {
let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default();
let (map, layout) = fixed_map(masks, "Opus", None, &given)?;
if sample_rate != 48_000 {
return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz")));
}
let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?;
let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?;
let bitrate = Some(enc.bitrate());
(Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None)
}
#[allow(unreachable_patterns)]
_ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))),
};
Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false })
}
/// The codec of the packets.
pub fn codec(&self) -> CodecId {
self.codec
}
/// The sample rate of the audio and of the packets' timing.
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
/// The number of channels.
pub fn channels(&self) -> u16 {
self.layout.channels()
}
/// The speakers of the channels encoded, in WAV order: the codec's layout for the channel
/// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the
/// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back
/// ones), whichever pair the caller's layout named.
pub fn layout(&self) -> ChannelLayout {
self.layout
}
/// The constant bit rate in bits per second for all channels together, as
/// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and
/// for AAC at a constant quality.
pub fn bitrate(&self) -> Option<u32> {
self.bitrate
}
/// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones.
pub fn bit_depth(&self) -> Option<u8> {
self.bit_depth
}
/// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds`
/// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box
/// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3.
/// ALAC's records the largest packet and the average bit rate so far, so read it after
/// [`finish`](Self::finish).
pub fn extradata(&self) -> Vec<u8> {
match &self.inner {
#[cfg(feature = "aac-encode")]
Inner::Aac(enc) => enc.audio_specific_config(),
#[cfg(feature = "alac-encode")]
Inner::Alac { enc, .. } => enc.cookie(),
#[cfg(feature = "opus-encode")]
Inner::Opus { enc, .. } => enc.opus_head(),
#[allow(unreachable_patterns)]
_ => Vec::new(),
}
}
/// The codec, sample rate, channels and [`extradata`](Self::extradata): the description
/// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs.
pub fn codec_params(&self) -> CodecParams {
CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata())
}
/// Decoded samples before the first input frame: the encoder's delay, which a container
/// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which
/// `OpusHead` already holds). 0 for ALAC.
///
/// This is the codec's delay and does not depend on the input. An encoder that is given no
/// input returns no packets, and this still reports the delay.
pub fn priming(&self) -> u32 {
match &self.inner {
#[cfg(feature = "aac-encode")]
Inner::Aac(enc) => enc.priming_samples(),
#[cfg(feature = "mp3-encode")]
Inner::Mp3 { enc, .. } => enc.delay(),
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Inner::Ac3 { enc, .. } => enc.priming_samples(),
#[cfg(feature = "opus-encode")]
Inner::Opus { enc, .. } => u32::from(enc.pre_skip()),
#[allow(unreachable_patterns)]
_ => 0,
}
}
/// Frames of input taken so far.
pub fn frames(&self) -> u64 {
self.frames
}
/// Decoded samples after the last input frame, which a container trims (the end of an MP4
/// edit, Matroska's DiscardPadding): the packets' durations add up to
/// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after
/// [`finish`](Self::finish).
///
/// The sum holds once there is input. With none, [`finish`](Self::finish) returns no packets,
/// so the durations add up to 0 and this is 0, while `priming` is still the codec's delay: a
/// muxer writes an empty track and has no priming to skip.
pub fn padding(&self) -> u64 {
self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames))
}
/// Encodes the first `frames` frames of `block`, one slice per channel in WAV order
/// (`&[Vec<f32>]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale
/// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped.
///
/// Internal codec calls process at most 4096 frames at a time, but this method collects their
/// packets in one returned vector whose memory use grows with `frames`. For streaming with
/// bounded memory, pass bounded input blocks and consume each returned batch before encoding
/// the next block, as [`FileEncoder`](crate::FileEncoder) does for coded formats.
///
/// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is
/// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is
/// an error too. When encoding itself fails, the packets of the block are lost, and every
/// later call fails rather than return a stream with a gap.
pub fn encode<C: AsRef<[f32]>>(&mut self, block: &[C], frames: usize) -> Result<Vec<EncodedPacket>> {
self.usable()?;
let channels = usize::from(self.channels());
if block.len() != channels {
return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len())));
}
if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() {
return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}")));
}
let mut out = Vec::new();
for at in (0..frames).step_by(CHUNK) {
let end = frames.min(at + CHUNK);
let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect();
if let Err(e) = self.push(&planes, &mut out) {
self.failed = true;
return Err(e);
}
self.frames = self.frames.saturating_add((end - at) as u64);
}
Ok(out)
}
/// Encodes what the encoder still holds, padded with silence to whole packets and as far as
/// a decoder needs to return every input frame after the priming, and returns the last
/// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description
/// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable.
pub fn finish(&mut self) -> Result<Vec<EncodedPacket>> {
self.usable()?;
self.finished = true;
let mut out = Vec::new();
let done = self.drain(&mut out);
if done.is_err() {
self.failed = true;
}
done.map(|()| out)
}
fn usable(&self) -> Result<()> {
if self.failed {
Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into()))
} else if self.finished {
Err(AudioError::Encode("the packet encoder is finished".into()))
} else {
Ok(())
}
}
/// Appends a packet of `duration` decoded samples at the current position.
fn emit(pts: &mut u64, out: &mut Vec<EncodedPacket>, data: Vec<u8>, duration: u32) {
out.push(EncodedPacket { data, pts: *pts, duration });
*pts = pts.saturating_add(u64::from(duration));
}
/// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames)
/// and appends the packets completed.
fn push(&mut self, planes: &[&[f32]], out: &mut Vec<EncodedPacket>) -> Result<()> {
let pts = &mut self.pts;
match &mut self.inner {
#[cfg(feature = "aac-encode")]
Inner::Aac(enc) => {
for data in enc.encode(planes) {
Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32);
}
}
#[cfg(feature = "alac-encode")]
Inner::Alac { enc, quantizers, pending } => {
let frames = planes.first().map_or(0, |p| p.len());
let mut at = 0;
while at < frames {
let filled = pending.first().map_or(0, Vec::len);
let end = frames.min(at + CHUNK.saturating_sub(filled).max(1));
for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) {
dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s)));
}
at = end;
if pending.first().is_some_and(|p| p.len() >= CHUNK) {
alac_packet(enc, pending, pts, out)?;
}
}
}
#[cfg(feature = "mp3-encode")]
Inner::Mp3 { enc, bytes } => {
bytes.extend(enc.encode(planes));
mp3_frames(enc, bytes, pts, out)?;
}
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Inner::Ac3 { enc, planes: clean } => {
for (dst, src) in clean.iter_mut().zip(planes) {
dst.clear();
dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }));
}
let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect();
for p in enc.push(&refs)? {
Self::emit(pts, out, p.data, p.samples);
}
}
#[cfg(feature = "opus-encode")]
Inner::Opus { enc, pending, coded } => {
let frames = planes.first().map_or(0, |p| p.len());
for i in 0..frames {
pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })));
if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() {
opus_packet(enc, pending, coded, pts, out)?;
}
}
}
}
Ok(())
}
/// Encodes what the codec still holds and appends the last packets.
fn drain(&mut self, out: &mut Vec<EncodedPacket>) -> Result<()> {
let pts = &mut self.pts;
match &mut self.inner {
#[cfg(feature = "aac-encode")]
Inner::Aac(enc) => {
for data in enc.flush() {
Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32);
}
}
#[cfg(feature = "alac-encode")]
Inner::Alac { enc, pending, .. } => {
if pending.first().is_some_and(|p| !p.is_empty()) {
alac_packet(enc, pending, pts, out)?;
}
}
#[cfg(feature = "mp3-encode")]
Inner::Mp3 { enc, bytes } => {
bytes.extend(enc.flush());
mp3_frames(enc, bytes, pts, out)?;
if !bytes.is_empty() {
return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len())));
}
}
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Inner::Ac3 { enc, .. } => {
for p in enc.finish()?.packets {
Self::emit(pts, out, p.data, p.samples);
}
}
#[cfg(feature = "opus-encode")]
Inner::Opus { enc, pending, coded } => {
// Every input frame decodes after the pre-skip: as many packets as that takes.
let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64;
let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size };
let width = usize::from(enc.channels());
while *coded < needed {
pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0);
opus_packet(enc, pending, coded, pts, out)?;
}
}
}
Ok(())
}
}
/// Encodes the pending samples as one ALAC packet and empties them.
#[cfg(feature = "alac-encode")]
fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec<i32>], pts: &mut u64, out: &mut Vec<EncodedPacket>) -> Result<()> {
let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect();
let frames = refs.first().map_or(0, |p| p.len()) as u32;
let data = enc.encode(&refs)?;
pending.iter_mut().for_each(Vec::clear);
PacketEncoder::emit(pts, out, data, frames);
Ok(())
}
/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them.
#[cfg(feature = "opus-encode")]
fn opus_packet(
enc: &mut crate::opus::encoder::Encoder,
pending: &mut Vec<f32>,
coded: &mut u64,
pts: &mut u64,
out: &mut Vec<EncodedPacket>,
) -> Result<()> {
let data = enc.encode_float(pending)?;
pending.clear();
let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32;
*coded += u64::from(size);
PacketEncoder::emit(pts, out, data, size);
Ok(())
}
/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames
/// back to back, so each one's length follows from its header's padding bit.
#[cfg(feature = "mp3-encode")]
fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec<u8>, pts: &mut u64, out: &mut Vec<EncodedPacket>) -> Result<()> {
let samples = enc.frame_samples();
let config = enc.config();
// Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot.
let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize;
let mut at = 0;
while let Some(header) = bytes.get(at..at + 4) {
if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 {
return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into()));
}
let len = base + usize::from((header[2] >> 1) & 1);
let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break };
PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32);
at += len;
}
bytes.drain(..at);
Ok(())
}
#[cfg(test)]
mod tests;
@@ -1,6 +1,6 @@
use super::*;
use crate::Speaker;
use crate::{CodecId, Speaker};
fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option<Vec<usize>> {
channel_map(mask, order, &ChannelLayout::from_mask(layout))
@@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() {
assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES));
assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES));
}
/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format.
#[test]
fn unbuilt_codecs_are_unsupported() {
let built = [
(CodecId::Aac, cfg!(feature = "aac-encode")),
(CodecId::Alac, cfg!(feature = "alac-encode")),
(CodecId::Mp3, cfg!(feature = "mp3-encode")),
(CodecId::Ac3, cfg!(feature = "ac3-encode")),
(CodecId::Eac3, cfg!(feature = "eac3-encode")),
(CodecId::Opus, cfg!(feature = "opus-encode")),
];
let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16);
for (codec, built) in built {
let made = PacketEncoder::new(codec, &opts, 48_000, 2);
if built {
assert!(made.is_ok(), "{codec:?}: {made:?}");
} else {
assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}");
}
}
}
+60 -351
View File
@@ -1,7 +1,7 @@
//! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through
//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's
//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the
//! encoder's priming and the exact length in the edit list.
//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a
//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for
//! M4A records the encoder's priming and the exact length in the edit list.
// Each codec is its own feature, and so are the two sinks: with only some of them built, the
// other halves of the shared code are unused.
@@ -11,271 +11,10 @@
)]
use super::failed_write_error;
use super::pcm::validate_layout;
use crate::layout::channel_map;
use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result};
use crate::packet::{EncodedPacket, PacketEncoder};
use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result};
use std::io::{Cursor, Seek, Write};
/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written
/// stay small however long a block is. Also the frames of an ALAC packet.
const CHUNK: usize = 4096;
/// Bits per second per channel when no rate is asked for: AAC.
const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per
/// full-bandwidth channel).
const DEFAULT_KBPS_PER_CHANNEL: u32 = 96;
/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`.
fn labels(mask: u32) -> String {
ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::<Vec<_>>().join(" ")
}
/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]),
/// or why the audio does not fit.
fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<Vec<usize>> {
let Some(&mask) = format.layout_masks(layout.channels()).first() else {
return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels())));
};
channel_map(mask, order, layout).ok_or_else(|| {
AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout)))
})
}
/// The speakers of the caller's layout, for an error message.
fn given(layout: &ChannelLayout) -> String {
layout.mask().map_or_else(|| "without speaker assignment".into(), labels)
}
/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels
/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc.
#[cfg(feature = "aac-encode")]
fn aac_order(channels: usize) -> Option<&'static [usize]> {
if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) }
}
/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample
/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes
/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s).
#[cfg(feature = "aac-encode")]
fn aac_floor_per_channel(sample_rate: u32) -> u32 {
(sample_rate / 4).max(6000)
}
/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a
/// quality of 0–1 spans the encoder's VBR range.
#[cfg(feature = "aac-encode")]
fn aac_mode(rate: Option<RateControl>, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode {
use crate::aac::BitrateMode;
let (lo, hi) = crate::aac::cbr_range(sample_rate, channels);
let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo));
// An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone.
let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps };
match rate {
None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))),
Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)),
// NaN stays NaN, which the encoder refuses.
Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)),
}
}
/// The bit rate in kbit/s for a codec with constant bit rates only.
fn constant_kbps(name: &str, rate: Option<RateControl>, default: u32) -> Result<u32> {
match rate {
None => Ok(default),
Some(RateControl::Bitrate(bps)) => Ok(bps / 1000),
Some(RateControl::Quality(_)) => {
Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality")))
}
}
}
/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding
/// mode whose speakers the layout names, at the nearest bit rate the stream can carry.
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
fn ac3_config(
codec: crate::ac3::encoder::Codec,
sample_rate: u32,
layout: &ChannelLayout,
rate: Option<RateControl>,
) -> Result<(crate::ac3::encoder::Config, Vec<usize>)> {
use crate::ac3::encoder::{Codec, CodingMode, Config};
use CodingMode::*;
let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" };
let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71];
let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| {
// 7.1 is an E-AC-3 programme with an LFE; the encoder has no other.
if mode == Surround71 && (codec != Codec::Eac3 || !lfe) {
return None;
}
let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe };
let map = channel_map(config.channel_layout().mask()?, None, layout)?;
Some((config, map))
});
let Some((mut config, map)) = found else {
return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout))));
};
let full = config.mode.channels() as u32;
let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?;
// What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of
// the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold.
let least = if config.mode == Surround71 { 384 } else { 32 * full };
config.bitrate_kbps = match codec {
Codec::Ac3 => {
let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least);
crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor)
}
Codec::Eac3 => {
let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 };
want.clamp(least, most.max(least))
}
};
Ok((config, map))
}
/// One encoded packet and the frames it decodes to.
struct Packet {
data: Vec<u8>,
frames: u32,
}
/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order.
enum Codec {
#[cfg(feature = "aac-encode")]
Aac(Box<crate::aac::Encoder>),
#[cfg(feature = "alac-encode")]
Alac {
enc: Box<crate::alac::Encoder>,
quantizers: Vec<super::pcm::Quantizer>,
/// Quantized samples of the packet being filled, per channel.
pending: Vec<Vec<i32>>,
},
#[cfg(feature = "mp3-encode")]
Mp3(Box<crate::mp3::Encoder>),
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Ac3 {
enc: Box<crate::ac3::encoder::Encoder>,
/// The block with every sample finite and within ±1, as the encoder requires.
planes: Vec<Vec<f32>>,
},
}
impl Codec {
/// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames)
/// and appends the packets completed.
fn push(&mut self, planes: &[&[f32]], out: &mut Vec<Packet>) -> Result<()> {
match self {
#[cfg(feature = "aac-encode")]
Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })),
#[cfg(feature = "alac-encode")]
Codec::Alac { enc, quantizers, pending } => {
let frames = planes.first().map_or(0, |p| p.len());
let mut at = 0;
while at < frames {
let filled = pending.first().map_or(0, Vec::len);
let end = frames.min(at + CHUNK.saturating_sub(filled).max(1));
for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) {
dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s)));
}
at = end;
if pending.first().is_some_and(|p| p.len() >= CHUNK) {
alac_packet(enc, pending, out)?;
}
}
}
#[cfg(feature = "mp3-encode")]
Codec::Mp3(enc) => {
let data = enc.encode(planes);
if !data.is_empty() {
out.push(Packet { data, frames: 0 });
}
}
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Codec::Ac3 { enc, planes: clean } => {
for (dst, src) in clean.iter_mut().zip(planes) {
dst.clear();
dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }));
}
let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect();
out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples }));
}
}
Ok(())
}
/// Encodes what the encoder still holds and appends the last packets.
fn finish(&mut self, out: &mut Vec<Packet>) -> Result<()> {
match self {
#[cfg(feature = "aac-encode")]
Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })),
#[cfg(feature = "alac-encode")]
Codec::Alac { enc, pending, .. } => {
if pending.first().is_some_and(|p| !p.is_empty()) {
alac_packet(enc, pending, out)?;
}
}
#[cfg(feature = "mp3-encode")]
Codec::Mp3(enc) => {
let data = enc.flush();
if !data.is_empty() {
out.push(Packet { data, frames: 0 });
}
}
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })),
}
Ok(())
}
/// Decoded frames before the first frame of the audio.
fn priming(&self) -> u32 {
match self {
#[cfg(feature = "aac-encode")]
Codec::Aac(enc) => enc.priming_samples(),
#[allow(unreachable_patterns)]
_ => 0,
}
}
/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames`
/// frames in all): the configuration a decoder needs, with the average bit rate.
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option<craft_media::isobmff::SampleEntry> {
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry};
match self {
#[cfg(feature = "aac-encode")]
Codec::Aac(enc) => {
let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate);
if let CodecConfig::Aac(config) = &mut entry.codec
&& frames > 0
{
let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames);
config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX);
}
Some(entry)
}
#[cfg(feature = "alac-encode")]
Codec::Alac { enc, .. } => {
let bits = u16::from(enc.encoder_config().bit_depth);
Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits))
}
#[allow(unreachable_patterns)]
_ => None,
}
}
}
/// Encodes the pending samples as one ALAC packet and empties them.
#[cfg(feature = "alac-encode")]
fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec<i32>], out: &mut Vec<Packet>) -> Result<()> {
let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect();
let frames = refs.first().map_or(0, |p| p.len()) as u32;
let data = enc.encode(&refs)?;
pending.iter_mut().for_each(Vec::clear);
out.push(Packet { data, frames });
Ok(())
}
/// A muxer's error as this crate's: a failed write stays an I/O error.
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
fn mux_error(e: craft_media::isobmff::Error) -> AudioError {
@@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError {
}
}
/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in
/// all): the configuration a decoder needs, with the average bit rate.
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option<craft_media::isobmff::SampleEntry> {
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry};
let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels()));
match enc.codec() {
CodecId::Aac => {
let mut entry = SampleEntry::aac(enc.extradata(), channels, rate);
if let CodecConfig::Aac(config) = &mut entry.codec
&& frames > 0
{
let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames);
config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX);
}
Some(entry)
}
CodecId::Alac => {
let bits = u16::from(enc.bit_depth().unwrap_or(16));
Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits))
}
_ => None,
}
}
/// An M4A file being written: one audio track whose samples are the packets.
///
/// The last packet is held back until the length is known: its duration is cut to the audio's
@@ -298,9 +62,8 @@ struct M4a<W: Write + Seek> {
track: Option<usize>,
entry: craft_media::isobmff::SampleEntry,
sample_rate: u32,
channels: u32,
priming: u32,
held: Option<Packet>,
held: Option<EncodedPacket>,
/// Frames and bytes of the packets written, the held one not counted.
frames: u64,
bytes: u64,
@@ -308,13 +71,14 @@ struct M4a<W: Write + Seek> {
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
impl<W: Write + Seek> M4a<W> {
fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result<Self> {
fn new(out: W, enc: &PacketEncoder) -> Result<Self> {
use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions};
let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?;
let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?;
let sample_rate = enc.sample_rate();
let mut options = WriterOptions::new(Brand::Mp4);
options.movie_timescale = sample_rate;
let mux = Mp4Writer::new(out, options).map_err(mux_error)?;
Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 })
Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 })
}
fn track(&mut self, has_audio: bool) -> Result<usize> {
@@ -333,7 +97,7 @@ impl<W: Write + Seek> M4a<W> {
Ok(track)
}
fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> {
fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> {
let track = self.track(true)?;
let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true };
self.mux.write_sample(track, sample).map_err(mux_error)?;
@@ -342,22 +106,22 @@ impl<W: Write + Seek> M4a<W> {
Ok(())
}
fn write(&mut self, packet: Packet) -> Result<()> {
fn write(&mut self, packet: EncodedPacket) -> Result<()> {
if let Some(held) = self.held.replace(packet) {
self.sample(&held, held.frames)?;
self.sample(&held, held.duration)?;
}
Ok(())
}
/// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`.
fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result<W> {
/// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`.
fn finish(mut self, enc: &PacketEncoder) -> Result<W> {
if let Some(held) = self.held.take() {
let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames);
self.sample(&held, rest.min(u64::from(held.frames)) as u32)?;
let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames);
self.sample(&held, rest.min(u64::from(held.duration)) as u32)?;
}
let track = self.track(false)?;
// The configuration is complete only now: the bit rate, and ALAC's largest packet.
if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) {
if let Some(entry) = sample_entry(enc, self.bytes, self.frames) {
self.mux.set_sample_entry(track, entry).map_err(mux_error)?;
}
self.mux.finish().map_err(mux_error)
@@ -374,15 +138,8 @@ enum Sink<W: Write + Seek> {
/// A file of one of the coded formats written block by block.
pub(crate) struct Writer<W: Write + Seek> {
codec: Codec,
enc: PacketEncoder,
sink: Sink<W>,
/// For each encoder channel, the caller's channel that feeds it.
map: Vec<usize>,
/// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for
/// AAC at a constant quality.
bitrate: Option<u32>,
frames: u64,
packets: Vec<Packet>,
/// Set when a write has failed: the encoder and the sink no longer agree, so the writer
/// refuses every later call.
failed: bool,
@@ -390,68 +147,23 @@ pub(crate) struct Writer<W: Write + Seek> {
impl<W: Write + Seek> Writer<W> {
pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result<Self> {
validate_layout(channels, sample_rate)?;
let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16));
let (codec, map, bitrate) = match opts.format {
#[cfg(feature = "aac-encode")]
EncodeFormat::Aac => {
let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?;
let mode = aac_mode(opts.rate_control, sample_rate, channels);
let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) };
let bitrate = match mode {
crate::aac::BitrateMode::Cbr(bps) => Some(bps),
crate::aac::BitrateMode::Vbr(_) => None,
};
(Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate)
}
#[cfg(feature = "alac-encode")]
EncodeFormat::Alac => {
let count = u8::try_from(channels).unwrap_or(u8::MAX);
let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?;
let bits = match opts.bit_depth {
crate::BitDepth::Int16 => 16,
crate::BitDepth::Int24 => 24,
crate::BitDepth::Int32 => 32,
crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())),
};
let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?;
let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels);
(Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None)
}
#[cfg(feature = "mp3-encode")]
EncodeFormat::Mp3 => {
let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?;
let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?;
// A sample rate MP3 has not is the encoder's to refuse.
let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want);
let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?;
(Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000)))
}
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
EncodeFormat::Ac3 | EncodeFormat::Eac3 => {
let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 };
let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?;
let enc = crate::ac3::encoder::Encoder::new(config)?;
(Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000)))
}
#[allow(unreachable_patterns)]
f => return Err(AudioError::Unsupported(format!("writing {f:?}"))),
};
let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?;
let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?;
let sink = match opts.format {
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)),
EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)),
_ => Sink::Raw(out),
};
Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false })
Ok(Writer { enc, sink, failed: false })
}
pub(crate) fn bitrate(&self) -> Option<u32> {
self.bitrate
self.enc.bitrate()
}
/// Hands the packets waiting to the sink.
fn drain(&mut self) -> Result<()> {
for packet in self.packets.drain(..) {
/// Hands `packets` to the sink.
fn drain(&mut self, packets: Vec<EncodedPacket>) -> Result<()> {
for packet in packets {
match &mut self.sink {
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
Sink::M4a(m4a) => m4a.write(packet)?,
@@ -466,16 +178,16 @@ impl<W: Write + Seek> Writer<W> {
if self.failed {
return Err(failed_write_error());
}
for at in (0..frames).step_by(CHUNK) {
let end = frames.min(at + CHUNK);
let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect();
let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain());
// A block at a time, so the packets waiting for the sink stay few however long it is.
for at in (0..frames).step_by(crate::packet::CHUNK) {
let end = frames.min(at + crate::packet::CHUNK);
let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect();
let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets));
if let Err(e) = written {
self.failed = true;
return Err(e);
}
}
self.frames = self.frames.saturating_add(frames as u64);
Ok(())
}
@@ -483,11 +195,11 @@ impl<W: Write + Seek> Writer<W> {
if self.failed {
return Err(failed_write_error());
}
self.codec.finish(&mut self.packets)?;
self.drain()?;
let last = self.enc.finish()?;
self.drain(last)?;
match self.sink {
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames),
Sink::M4a(m4a) => m4a.finish(&self.enc),
Sink::Raw(mut out) => {
out.flush()?;
Ok(out)
@@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result<Vec<u8>>
w.write(&buf.channels, buf.frames())?;
Ok(w.finish()?.into_inner())
}
#[cfg(test)]
mod tests;
+1 -1
View File
@@ -8,7 +8,7 @@ mod aiff;
mod coded;
#[cfg(feature = "flac-encode")]
pub(crate) mod flac;
mod pcm;
pub(crate) mod pcm;
#[cfg(feature = "vorbis-encode")]
mod vorbis;
#[cfg(feature = "vorbis-encode")]
+1
View File
@@ -18,6 +18,7 @@ mod mp3_encoder_oracle;
mod mpa_oracle;
mod opus;
mod opusenc;
mod packet_encoder;
mod routing_oracle;
mod track_decoder;
#[cfg(feature = "vorbis-encode")]
+244
View File
@@ -0,0 +1,244 @@
//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the
//! encoder gives, at the length that was encoded and with each channel on its speaker.
use std::io::Cursor;
use craft_audio::{
AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder,
};
/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE.
fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec<Vec<f32>> {
(0..channels)
.map(|c| {
let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32;
(0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect()
})
.collect()
}
/// Normalised correlation of two signals over the samples both have.
fn correlation(a: &[f32], b: &[f32]) -> f64 {
let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64);
for (&x, &y) in a.iter().zip(b) {
let (x, y) = (f64::from(x), f64::from(y));
ab += x * y;
aa += x * x;
bb += y * y;
}
ab / (aa * bb).sqrt().max(1e-30)
}
/// Encodes `input` in uneven blocks and returns the packets.
fn encode(enc: &mut PacketEncoder, input: &[Vec<f32>]) -> Vec<EncodedPacket> {
let frames = input[0].len();
let mut packets = Vec::new();
let mut at = 0;
for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() {
let n = n.min(frames - at);
let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect();
packets.extend(enc.encode(&block, n).unwrap());
at += n;
if at == frames {
break;
}
}
packets.extend(enc.finish().unwrap());
packets
}
/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and
/// returns the decoded audio from the first input frame on, cut to the input's length, and the
/// layout the decoder reports.
fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec<f32>]) -> (PacketEncoder, Vec<Vec<f32>>, ChannelLayout) {
let frames = input[0].len();
let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap();
let packets = encode(&mut enc, input);
assert_eq!(enc.frames(), frames as u64);
// The packets follow one another, and add up to the priming, the audio and the padding.
let mut pts = 0;
for p in &packets {
assert_eq!(p.pts, pts, "{codec:?}");
pts += u64::from(p.duration);
}
assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}");
let last = packets.last().map_or(0, |p| u64::from(p.duration));
assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding());
let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect();
let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap();
assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}");
let mut out = vec![Vec::new(); usize::from(dec.channels())];
for p in &packets {
let block = dec.decode(&p.data).unwrap();
assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to");
for (o, c) in out.iter_mut().zip(block.channels) {
o.extend(c);
}
}
let skip = enc.priming() as usize;
let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect();
(enc, out, dec.layout())
}
/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded.
fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec<f32>]) -> (PacketEncoder, Vec<Vec<f32>>) {
let (enc, out, layout) = decode_back(codec, opts, sample_rate, input);
assert_eq!(layout, enc.layout(), "{codec:?}");
(enc, out)
}
/// Each decoded channel is its input channel, in place: it matches that channel and no other. The
/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude.
fn assert_in_place(codec: CodecId, input: &[Vec<f32>], output: &[Vec<f32>], least: f64) {
for (c, got) in output.iter().enumerate() {
let scores: Vec<f64> = input.iter().map(|want| correlation(want, got).abs()).collect();
let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least };
assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}");
for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) {
assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}");
}
}
}
#[test]
fn aac_round_trips_in_place() {
let input = tones(48_000, 6, 30_001);
let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000);
let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input);
assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000)));
assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6");
assert_in_place(CodecId::Aac, &input, &out, 0.95);
}
/// 16-bit ALAC is lossless: the input comes back bit for bit.
#[test]
fn alac_round_trips_exactly() {
let input = tones(44_100, 6, 10_000);
let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1);
let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input);
assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1));
assert_eq!(out, input);
}
#[test]
fn mp3_round_trips_in_place() {
for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] {
let input = tones(rate, 2, 20_000);
let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000);
let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap();
let packets = encode(&mut enc, &input);
assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz");
let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input);
assert_eq!((enc.priming(), enc.extradata()), (1057, vec![]));
assert_in_place(CodecId::Mp3, &input, &out, 0.95);
}
}
#[test]
fn ac3_round_trips_in_place() {
let input = tones(48_000, 6, 20_000);
let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input);
assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000)));
assert_in_place(CodecId::Ac3, &input, &out, 0.9);
}
#[test]
fn eac3_round_trips_in_place() {
let input = tones(48_000, 6, 20_000);
let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input);
assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE));
assert_in_place(CodecId::Eac3, &input, &out, 0.9);
}
/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the
/// README), at the same length.
#[test]
fn eac3_7_1_decodes_as_its_5_1_substream() {
let input = tones(48_000, 8, 20_000);
let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1);
let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input);
assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE));
assert!(out.iter().all(|c| c.len() == 20_000));
}
#[test]
fn opus_round_trips_in_place() {
for channels in [1, 2] {
let input = tones(48_000, channels, 20_000);
let opts = EncodeOptions::default().with_bitrate(128_000);
let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input);
let head = enc.extradata();
assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming()));
assert_in_place(CodecId::Opus, &input, &out, 0.9);
}
}
/// The raw streams `FileEncoder` writes are the packets in a row.
#[test]
fn file_encoder_writes_the_packets() {
for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] {
let input = tones(48_000, usize::from(layout.channels()), 12_345);
let opts = EncodeOptions::new(format).with_layout(layout);
let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap();
file.write(&input, 12_345).unwrap();
let file = file.finish().unwrap().into_inner();
let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap();
let packets: Vec<u8> = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect();
assert_eq!(file, packets, "{format:?}");
}
}
/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format.
#[test]
fn unsupported_settings_are_refused() {
let unsupported =
|codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_)));
let opts = EncodeOptions::default();
assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2));
assert!(unsupported(CodecId::Flac, &opts, 48_000, 2));
assert!(unsupported(CodecId::Opus, &opts, 44_100, 2));
assert!(unsupported(CodecId::Opus, &opts, 48_000, 3));
assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2));
for (codec, format, rate, channels) in [
(CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2),
(CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0),
(CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6),
(CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8),
(CodecId::Aac, EncodeFormat::Aac, 44_000, 2),
] {
let opts = EncodeOptions::new(format);
let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels));
assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}");
assert!(packets.is_err());
}
assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2));
assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2));
// A layout for another channel count is the caller's mistake.
assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_))));
}
/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was.
#[test]
fn misuse_is_an_error() {
let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap();
let short = [vec![0.0f32; 10], vec![0.0; 5]];
assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_))));
assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_))));
assert_eq!(enc.frames(), 0);
assert!(enc.encode(&short, 5).unwrap().is_empty());
assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets");
assert!(matches!(enc.finish(), Err(AudioError::Encode(_))));
assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_))));
// An encoder given nothing returns nothing: no packets, no frames and no padding. `priming`
// is the codec's delay either way, so it equals that of an encoder that was given input.
for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] {
let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap();
assert!(enc.finish().unwrap().is_empty(), "{codec:?}");
assert_eq!((enc.frames(), enc.padding()), (0, 0), "{codec:?}");
let mut fed = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap();
fed.encode(&short, 5).unwrap();
fed.finish().unwrap();
assert_eq!(enc.priming(), fed.priming(), "{codec:?}");
}
}