Skip to main content

threers_codec/mp3/
encoder.rs

1//! MPEG-1 Layer III encoding: planar `f32` PCM to an `.mp3` file at 32,
2//! 44.1 or 48 kHz, mono or stereo, at a constant bitrate.
3//!
4//! The chain, per granule (576 samples) and channel:
5//!
6//! 1. The 32-band polyphase analysis filterbank (ISO 11172-3 annex C), whose
7//!    prototype is the decoder's synthesis window scaled by 1/32.
8//! 2. An 18-point MDCT per subband with the sine window, after the sign flip
9//!    that undoes the filterbank's frequency inversion, and the alias-reduction
10//!    butterflies between neighbouring subbands.
11//! 3. A low-pass that follows the bitrate.
12//! 4. For stereo, a per-frame choice of left/right or mid/side.
13//! 5. Power-law quantization (`|x|^(3/4)`, rounding offset 0.4054) with one
14//!    global step per granule and channel, found by bisection so that the
15//!    granule fits its share of the frame.
16//! 6. Huffman coding with the best of the 32 big-value tables for each of
17//!    three regions (the region split is searched too), and the better of
18//!    the two count-1 tables.
19//!
20//! What it leaves out: block switching (short blocks, so sharp attacks
21//! pre-echo), scalefactors (the quantization noise is flat across the
22//! spectrum), the bit reservoir (every frame is self-contained), intensity
23//! stereo, a psychoacoustic model, and MPEG-2 sample rates. The output
24//! decodes with any MP3 decoder. [`encode_mp3`] puts a Xing/LAME `Info` frame
25//! first, which carries the encoder delay and padding, so gapless players
26//! trim the file to exactly the input's length.
27//!
28//! ```
29//! use threers_codec::mp3::encoder::{encode_mp3, Mp3Config};
30//! let tone: Vec<f32> = (0..44_100).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
31//! let mp3 = encode_mp3(&[tone], &Mp3Config::new(44_100, 1, 64)).unwrap();
32//! assert!(mp3.len() > 1_000);
33//! ```
34
35use std::sync::OnceLock;
36
37use super::tables::{BAND_INFO, HT, HTC, INTWINBASE};
38use crate::bitstream::BitWriter;
39
40/// Samples per frame and channel.
41pub const FRAME: usize = 1152;
42const GRANULE: usize = 576;
43
44/// Samples a decoder's output is late by, counting its own 529: where the
45/// input's first sample lands when the stream is decoded without the `Info`
46/// frame's help. The filterbank takes 481 and the transform's overlap 576.
47pub const DELAY: usize = 1057;
48
49/// MPEG-1 Layer III bitrates, kbit/s, by header index 1 to 14.
50pub const BITRATES: [u32; 14] = [
51    32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
52];
53
54/// The MPEG-1 sample rates, in header order.
55pub const SAMPLE_RATES: [u32; 3] = [44_100, 48_000, 32_000];
56
57/// What to encode.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct Mp3Config {
60    pub sample_rate: u32,
61    /// 1 or 2.
62    pub channels: usize,
63    /// Constant bitrate in kbit/s: one of [`BITRATES`].
64    pub kbps: u32,
65}
66
67impl Mp3Config {
68    pub fn new(sample_rate: u32, channels: usize, kbps: u32) -> Self {
69        Self {
70            sample_rate,
71            channels,
72            kbps,
73        }
74    }
75}
76
77/// Why encoding was refused.
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub enum Mp3Error {
80    /// Only 32, 44.1 and 48 kHz (MPEG-1) are supported.
81    SampleRate(u32),
82    Channels(usize),
83    /// Not one of [`BITRATES`].
84    Bitrate(u32),
85    Input(String),
86}
87
88impl std::fmt::Display for Mp3Error {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        match self {
91            Self::SampleRate(r) => write!(f, "{r} Hz: MPEG-1 Layer III is 32, 44100 or 48000 Hz"),
92            Self::Channels(c) => write!(f, "{c} channels: only mono and stereo are supported"),
93            Self::Bitrate(b) => write!(f, "{b} kbit/s is not an MPEG-1 Layer III bitrate"),
94            Self::Input(why) => write!(f, "bad input: {why}"),
95        }
96    }
97}
98
99impl std::error::Error for Mp3Error {}
100
101// ------------------------------------------------------------- huffman
102
103/// A big-value table: code lengths and codes for each pair of 0..=15, and
104/// how large a value it can carry.
105struct PairTable {
106    len: [[u8; 16]; 16],
107    code: [[u16; 16]; 16],
108    linbits: u32,
109    /// The largest value the table can code (with its linbits).
110    max: i32,
111}
112
113/// A count-1 table: code lengths and codes by the quad's four-bit pattern.
114struct QuadTable {
115    len: [u8; 16],
116    code: [u8; 16],
117}
118
119struct Tables {
120    pairs: Vec<Option<PairTable>>,
121    quads: [QuadTable; 2],
122    /// The analysis window C[i] = D[i] / 32.
123    window: [f64; 512],
124    /// cos((2k+1)(i-16)pi/64).
125    matrix: Vec<[f64; 64]>,
126    /// The 36-point MDCT: window and cosines.
127    mdct_window: [f64; 36],
128    mdct_cos: Vec<[f64; 36]>,
129}
130
131/// Walks a radix-16 table (the decoder's `huff_pair` layout), recording each
132/// leaf's code. A non-negative entry is `length << 8 | x << 4 | y` for the
133/// bits left in this nibble; a negative one points to a sub-table.
134fn walk_pairs(
135    tab: &[i16],
136    base: usize,
137    prefix: u32,
138    prefix_len: u32,
139    len: &mut [[u8; 16]; 16],
140    code: &mut [[u16; 16]; 16],
141) {
142    for idx in 0..16usize {
143        let e = tab[base + idx];
144        if e < 0 {
145            walk_pairs(
146                tab,
147                base + (-e) as usize,
148                (prefix << 4) | idx as u32,
149                prefix_len + 4,
150                len,
151                code,
152            );
153        } else {
154            let l = (e >> 8) as u32;
155            // A leaf of length l fills 2^(4-l) entries; take its first.
156            if l == 0 || idx & ((1 << (4 - l)) - 1) != 0 {
157                continue;
158            }
159            let (x, y) = (((e >> 4) & 15) as usize, (e & 15) as usize);
160            len[x][y] = (prefix_len + l) as u8;
161            code[x][y] = ((prefix << l) | (idx as u32 >> (4 - l))) as u16;
162        }
163    }
164}
165
166/// Walks a bit-serial count-1 table.
167fn walk_quads(tab: &[i16], at: usize, prefix: u32, depth: u32, out: &mut QuadTable) {
168    let a = tab[at];
169    if a >= 0 {
170        out.len[a as usize] = depth as u8;
171        out.code[a as usize] = prefix as u8;
172    } else {
173        walk_quads(tab, at + 1, prefix << 1, depth + 1, out);
174        walk_quads(
175            tab,
176            at + 1 + (-a) as usize,
177            (prefix << 1) | 1,
178            depth + 1,
179            out,
180        );
181    }
182}
183
184fn tables() -> &'static Tables {
185    static T: OnceLock<Tables> = OnceLock::new();
186    T.get_or_init(|| {
187        let mut pairs = Vec::with_capacity(32);
188        for (n, (linbits, tab)) in HT.iter().enumerate() {
189            // Tables 4 and 14 do not exist.
190            if n == 4 || n == 14 {
191                pairs.push(None);
192                continue;
193            }
194            let (mut len, mut code) = ([[0u8; 16]; 16], [[0u16; 16]; 16]);
195            walk_pairs(tab, 0, 0, 0, &mut len, &mut code);
196            if n == 0 {
197                // Table 0 carries only zeros, in no bits.
198                pairs.push(Some(PairTable {
199                    len,
200                    code,
201                    linbits: 0,
202                    max: 0,
203                }));
204                continue;
205            }
206            let tree_max = (0..16)
207                .filter(|&x| (0..16).any(|y| len[x][y] > 0 || len[y][x] > 0))
208                .max()
209                .unwrap_or(0) as i32;
210            let max = if *linbits > 0 {
211                15 + (1 << linbits) - 1
212            } else {
213                tree_max
214            };
215            pairs.push(Some(PairTable {
216                len,
217                code,
218                linbits: *linbits,
219                max,
220            }));
221        }
222        let mut quads = [
223            QuadTable {
224                len: [0; 16],
225                code: [0; 16],
226            },
227            QuadTable {
228                len: [0; 16],
229                code: [0; 16],
230            },
231        ];
232        for (q, (_, tab)) in quads.iter_mut().zip(HTC.iter()) {
233            walk_quads(tab, 0, 0, 0, q);
234        }
235        // D[i] = +/- base[i] / 65536 with the sign changing every 64 entries;
236        // the base is symmetric about 256. C = D / 32.
237        let mut window = [0.0; 512];
238        for (i, w) in window.iter_mut().enumerate() {
239            let base = INTWINBASE[if i <= 256 { i } else { 512 - i }] as f64 / 65_536.0;
240            let sign = if (i / 64) % 2 == 0 { 1.0 } else { -1.0 };
241            *w = sign * base / 32.0;
242        }
243        let matrix = (0..32)
244            .map(|k| {
245                let mut row = [0.0; 64];
246                for (i, r) in row.iter_mut().enumerate() {
247                    *r = ((2 * k + 1) as f64 * (i as f64 - 16.0) * std::f64::consts::PI / 64.0)
248                        .cos();
249                }
250                row
251            })
252            .collect();
253        let mut mdct_window = [0.0; 36];
254        for (i, w) in mdct_window.iter_mut().enumerate() {
255            *w = (std::f64::consts::PI / 36.0 * (i as f64 + 0.5)).sin();
256        }
257        let mdct_cos = (0..18)
258            .map(|k| {
259                let mut row = [0.0; 36];
260                for (i, r) in row.iter_mut().enumerate() {
261                    *r = (std::f64::consts::PI / 72.0
262                        * (2 * i + 1 + 18) as f64
263                        * (2 * k + 1) as f64)
264                        .cos();
265                }
266                row
267            })
268            .collect();
269        Tables {
270            pairs,
271            quads,
272            window,
273            matrix,
274            mdct_window,
275            mdct_cos,
276        }
277    })
278}
279
280/// Bits for one pair of magnitudes in a table; `None` if it cannot code them.
281fn pair_bits(t: &PairTable, x: i32, y: i32) -> Option<u32> {
282    if x > t.max || y > t.max {
283        return None;
284    }
285    let (cx, cy) = if t.linbits > 0 {
286        (x.min(15), y.min(15))
287    } else {
288        (x, y)
289    };
290    let mut bits = u32::from(t.len[cx as usize][cy as usize]);
291    if t.linbits > 0 {
292        if x >= 15 {
293            bits += t.linbits;
294        }
295        if y >= 15 {
296            bits += t.linbits;
297        }
298    }
299    Some(bits + u32::from(x != 0) + u32::from(y != 0))
300}
301
302// -------------------------------------------------------- granule coding
303
304/// A granule of one channel, quantized and ready to write.
305#[derive(Clone)]
306struct Granule {
307    global_gain: u32,
308    /// Signed.
309    ix: [i32; GRANULE],
310    big_values: usize,
311    count1_quads: usize,
312    count1_table: usize,
313    region0_count: usize,
314    region1_count: usize,
315    tables: [usize; 3],
316    bits: u32,
317}
318
319impl Granule {
320    fn silent() -> Self {
321        Self {
322            global_gain: 0,
323            ix: [0; GRANULE],
324            big_values: 0,
325            count1_quads: 0,
326            count1_table: 0,
327            region0_count: 0,
328            region1_count: 0,
329            tables: [0; 3],
330            bits: 0,
331        }
332    }
333}
334
335/// The sfb edge at `index`, clamped: past the last band is the end.
336fn edge(long: &[u16; 23], index: usize) -> usize {
337    long.get(index).map_or(GRANULE, |&e| usize::from(e))
338}
339
340/// Chooses the coding of magnitudes `ix` (signs ignored here): where the
341/// big values end, the count-1 table, the regions and a table per region.
342fn code_granule(ix: &[i32; GRANULE], long: &[u16; 23]) -> Option<Granule> {
343    let t = tables();
344    let mut end = GRANULE;
345    while end >= 2 && ix[end - 1] == 0 && ix[end - 2] == 0 {
346        end -= 2;
347    }
348    // Count-1 quads from the top while every value is 0 or 1.
349    let mut big = end;
350    while big >= 4 && ix[big - 4..big].iter().all(|&v| v <= 1) {
351        big -= 4;
352    }
353    let quads = (end - big) / 4;
354    let (mut best_count1, mut count1_table) = (u32::MAX, 0);
355    for (n, q) in t.quads.iter().enumerate() {
356        let mut bits = 0;
357        for c in ix[big..end].chunks(4) {
358            let m = (c[0] << 3 | c[1] << 2 | c[2] << 1 | c[3]) as usize;
359            bits += u32::from(q.len[m]) + c.iter().filter(|&&v| v != 0).count() as u32;
360        }
361        if bits < best_count1 {
362            best_count1 = bits;
363            count1_table = n;
364        }
365    }
366    let pairs = big / 2;
367    if ix[..big].iter().any(|&v| v > 15 + (1 << 13) - 1) {
368        return None;
369    }
370
371    // Per table, running totals of the bits for the pairs, and of the pairs it
372    // cannot code, so any region's best table is a subtraction.
373    let usable: Vec<usize> = (0..32).filter(|&n| t.pairs[n].is_some()).collect();
374    let mut cost = vec![vec![0u32; pairs + 1]; 32];
375    let mut bad = vec![vec![0u32; pairs + 1]; 32];
376    for &n in &usable {
377        let table = t.pairs[n].as_ref().expect("usable");
378        for p in 0..pairs {
379            let (x, y) = (ix[2 * p], ix[2 * p + 1]);
380            let (c, b) = pair_bits(table, x, y).map_or((0, 1), |bits| (bits, 0));
381            cost[n][p + 1] = cost[n][p] + c;
382            bad[n][p + 1] = bad[n][p] + b;
383        }
384    }
385    let best_table = |from: usize, to: usize| -> (u32, usize) {
386        if from >= to {
387            return (0, 0);
388        }
389        usable
390            .iter()
391            .filter(|&&n| bad[n][to] == bad[n][from])
392            .map(|&n| (cost[n][to] - cost[n][from], n))
393            .min()
394            .unwrap_or((u32::MAX / 4, 0))
395    };
396
397    let mut best: Option<(u32, usize, usize, [usize; 3])> = None;
398    for r0 in 0..16usize {
399        for r1 in 0..8usize {
400            // Regions in pairs; they cannot pass the end of the big values.
401            let a = (edge(long, r0 + 1) / 2).min(pairs);
402            let b = (edge(long, r0 + r1 + 2) / 2).min(pairs).max(a);
403            let ((c0, t0), (c1, t1), (c2, t2)) =
404                (best_table(0, a), best_table(a, b), best_table(b, pairs));
405            let total = c0.saturating_add(c1).saturating_add(c2);
406            if best.is_none_or(|(bits, ..)| total < bits) {
407                best = Some((total, r0, r1, [t0, t1, t2]));
408            }
409        }
410    }
411    let (big_bits, region0_count, region1_count, tables_chosen) = best?;
412    let bits = big_bits.saturating_add(best_count1);
413    Some(Granule {
414        global_gain: 0,
415        ix: *ix,
416        big_values: pairs,
417        count1_quads: quads,
418        count1_table,
419        region0_count,
420        region1_count,
421        tables: tables_chosen,
422        bits,
423    })
424}
425
426fn write_granule(w: &mut BitWriter, g: &Granule, long: &[u16; 23]) {
427    let t = tables();
428    let a = (edge(long, g.region0_count + 1) / 2).min(g.big_values);
429    let b = (edge(long, g.region0_count + g.region1_count + 2) / 2)
430        .min(g.big_values)
431        .max(a);
432    for (region, (from, to)) in [(0, a), (a, b), (b, g.big_values)].into_iter().enumerate() {
433        let table = t.pairs[g.tables[region]]
434            .as_ref()
435            .expect("a chosen table exists");
436        for p in from..to {
437            let (x, y) = (g.ix[2 * p], g.ix[2 * p + 1]);
438            let (ax, ay) = (x.abs(), y.abs());
439            if g.tables[region] == 0 {
440                continue; // table 0: zeros, no bits
441            }
442            let (cx, cy) = if table.linbits > 0 {
443                (ax.min(15), ay.min(15))
444            } else {
445                (ax, ay)
446            };
447            w.write_bits(
448                u32::from(table.code[cx as usize][cy as usize]),
449                u32::from(table.len[cx as usize][cy as usize]),
450            );
451            if table.linbits > 0 && ax >= 15 {
452                w.write_bits((ax - 15) as u32, table.linbits);
453            }
454            if ax != 0 {
455                w.write_bits(u32::from(x < 0), 1);
456            }
457            if table.linbits > 0 && ay >= 15 {
458                w.write_bits((ay - 15) as u32, table.linbits);
459            }
460            if ay != 0 {
461                w.write_bits(u32::from(y < 0), 1);
462            }
463        }
464    }
465    let q = &t.quads[g.count1_table];
466    let start = 2 * g.big_values;
467    for c in g.ix[start..start + 4 * g.count1_quads].chunks(4) {
468        let m = (c[0].abs() << 3 | c[1].abs() << 2 | c[2].abs() << 1 | c[3].abs()) as usize;
469        w.write_bits(u32::from(q.code[m]), u32::from(q.len[m]));
470        for &v in c {
471            if v != 0 {
472                w.write_bits(u32::from(v < 0), 1);
473            }
474        }
475    }
476}
477
478// ---------------------------------------------------------------- encoder
479
480/// Per-channel filterbank state.
481struct Channel {
482    /// The last 512 input samples, newest first.
483    x: [f64; 512],
484    /// The previous granule's subband samples, `[subband][slot]`.
485    previous: [[f64; 18]; 32],
486}
487
488/// Encodes a stream frame by frame.
489pub struct Mp3Encoder {
490    cfg: Mp3Config,
491    sr_index: usize,
492    bitrate_index: usize,
493    long: [u16; 23],
494    side_bytes: usize,
495    channels: Vec<Channel>,
496    pending: Vec<Vec<f32>>,
497    /// Bands from this sample on are never coded.
498    cutoff: usize,
499    /// Fraction of a byte carried between frames, for padding.
500    padding_acc: u32,
501    frames: u64,
502    pushed: u64,
503    bytes: u64,
504}
505
506/// Input PCM (full scale 1.0) to the spectrum the quantizer works on.
507const SCALE: f64 = 0.1122;
508
509impl Mp3Encoder {
510    pub fn new(cfg: Mp3Config) -> Result<Self, Mp3Error> {
511        let sr_index = SAMPLE_RATES
512            .iter()
513            .position(|&r| r == cfg.sample_rate)
514            .ok_or(Mp3Error::SampleRate(cfg.sample_rate))?;
515        if !(1..=2).contains(&cfg.channels) {
516            return Err(Mp3Error::Channels(cfg.channels));
517        }
518        let bitrate_index = BITRATES
519            .iter()
520            .position(|&b| b == cfg.kbps)
521            .ok_or(Mp3Error::Bitrate(cfg.kbps))?
522            + 1;
523        let per_channel = f64::from(cfg.kbps) * 1000.0 / cfg.channels as f64;
524        let cutoff_hz = (per_channel * 0.25).clamp(4_000.0, f64::from(cfg.sample_rate) / 2.0);
525        let cutoff = ((cutoff_hz / (f64::from(cfg.sample_rate) / 2.0)) * GRANULE as f64) as usize;
526        let _ = tables();
527        Ok(Self {
528            cfg,
529            sr_index,
530            bitrate_index,
531            long: BAND_INFO[sr_index].long_idx,
532            side_bytes: if cfg.channels == 1 { 17 } else { 32 },
533            channels: (0..cfg.channels)
534                .map(|_| Channel {
535                    x: [0.0; 512],
536                    previous: [[0.0; 18]; 32],
537                })
538                .collect(),
539            pending: vec![Vec::new(); cfg.channels],
540            cutoff: cutoff.min(GRANULE),
541            padding_acc: 0,
542            frames: 0,
543            pushed: 0,
544            bytes: 0,
545        })
546    }
547
548    pub fn config(&self) -> &Mp3Config {
549        &self.cfg
550    }
551
552    /// Frames written so far.
553    pub fn frames(&self) -> u64 {
554        self.frames
555    }
556
557    /// Adds samples (one slice per channel, equal lengths) and returns the
558    /// bytes of every frame that is now complete.
559    pub fn push(&mut self, planar: &[&[f32]]) -> Result<Vec<u8>, Mp3Error> {
560        if planar.len() != self.cfg.channels {
561            return Err(Mp3Error::Input(format!(
562                "{} channels given, {} expected",
563                planar.len(),
564                self.cfg.channels
565            )));
566        }
567        if planar.iter().any(|c| c.len() != planar[0].len()) {
568            return Err(Mp3Error::Input("the channels differ in length".into()));
569        }
570        for (p, c) in self.pending.iter_mut().zip(planar) {
571            p.extend_from_slice(c);
572        }
573        self.pushed += planar[0].len() as u64;
574        let mut out = Vec::new();
575        while self.pending[0].len() >= FRAME {
576            let frame: Vec<Vec<f32>> = self
577                .pending
578                .iter_mut()
579                .map(|p| p.drain(..FRAME).collect())
580                .collect();
581            out.extend(self.encode_frame(&frame));
582        }
583        Ok(out)
584    }
585
586    /// Ends the stream: pads with silence so the last samples and the delay
587    /// behind them come out.
588    pub fn finish(&mut self) -> Vec<u8> {
589        let total = self.pushed as usize + DELAY;
590        let frames_needed = total.div_ceil(FRAME) as u64;
591        let mut out = Vec::new();
592        while self.frames < frames_needed || !self.pending[0].is_empty() {
593            let frame: Vec<Vec<f32>> = self
594                .pending
595                .iter_mut()
596                .map(|p| {
597                    let take = p.len().min(FRAME);
598                    let mut f: Vec<f32> = p.drain(..take).collect();
599                    f.resize(FRAME, 0.0);
600                    f
601                })
602                .collect();
603            out.extend(self.encode_frame(&frame));
604        }
605        out
606    }
607
608    /// The `Info` frame that goes first in the file, once everything has been
609    /// encoded: it carries the length, the encoder delay and the padding.
610    pub fn info_frame(&self) -> Vec<u8> {
611        build_info_frame(self, self.frames, self.bytes, self.pushed)
612    }
613
614    /// Filters 576 samples of one channel to subbands, transforms them, and
615    /// reduces the aliasing: 576 coefficients, subband-major.
616    fn analyze(&mut self, ch: usize, samples: &[f64]) -> [f64; GRANULE] {
617        let t = tables();
618        let state = &mut self.channels[ch];
619        // 18 slots of 32 subband samples.
620        let mut slots = [[0.0f64; 32]; 18];
621        for (slot, out) in slots.iter_mut().enumerate() {
622            state.x.copy_within(0..480, 32);
623            for j in 0..32 {
624                state.x[31 - j] = samples[slot * 32 + j];
625            }
626            let mut y = [0.0f64; 64];
627            for (i, yi) in y.iter_mut().enumerate() {
628                *yi = (0..8)
629                    .map(|j| t.window[i + 64 * j] * state.x[i + 64 * j])
630                    .sum();
631            }
632            for (k, o) in out.iter_mut().enumerate() {
633                *o = t.matrix[k].iter().zip(&y).map(|(m, v)| m * v).sum();
634            }
635        }
636        let mut xr = [0.0f64; GRANULE];
637        for sb in 0..32 {
638            // The 36 inputs: the last granule's slots, then this one's, with
639            // every odd slot of an odd subband negated to undo the filterbank's
640            // frequency inversion.
641            let mut z = [0.0f64; 36];
642            for slot in 0..18 {
643                let flip = if sb % 2 == 1 && slot % 2 == 1 {
644                    -1.0
645                } else {
646                    1.0
647                };
648                z[slot] = state.previous[sb][slot];
649                z[18 + slot] = slots[slot][sb] * flip;
650            }
651            state.previous[sb].copy_from_slice(&z[18..36]);
652            for k in 0..18 {
653                xr[sb * 18 + k] = (0..36)
654                    .map(|i| t.mdct_window[i] * z[i] * t.mdct_cos[k][i])
655                    .sum();
656            }
657        }
658        // Alias reduction between neighbouring subbands.
659        const C: [f64; 8] = [
660            -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037,
661        ];
662        for sb in 1..32 {
663            for (i, c) in C.iter().enumerate() {
664                let (cs, ca) = (1.0 / (1.0 + c * c).sqrt(), c / (1.0 + c * c).sqrt());
665                let (bu, bd) = (xr[sb * 18 - 1 - i], xr[sb * 18 + i]);
666                xr[sb * 18 - 1 - i] = bu * cs + bd * ca;
667                xr[sb * 18 + i] = bd * cs - bu * ca;
668            }
669        }
670        xr
671    }
672
673    fn encode_frame(&mut self, frame: &[Vec<f32>]) -> Vec<u8> {
674        let nch = self.cfg.channels;
675        // Spectra for both granules and channels.
676        let mut xr = vec![vec![[0.0f64; GRANULE]; nch]; 2];
677        for gr in 0..2 {
678            for ch in 0..nch {
679                let s: Vec<f64> = frame[ch][gr * GRANULE..(gr + 1) * GRANULE]
680                    .iter()
681                    .map(|&v| f64::from(v) * SCALE)
682                    .collect();
683                let mut spec = self.analyze(ch, &s);
684                for v in &mut spec[self.cutoff..] {
685                    *v = 0.0;
686                }
687                xr[gr][ch] = spec;
688            }
689        }
690
691        // Mid/side for the frame, if it needs fewer bits.
692        let mut ms = false;
693        if nch == 2 {
694            let (mut lr, mut mid_side) = (0.0, 0.0);
695            for gr in 0..2 {
696                for k in 0..self.cutoff {
697                    let (l, r) = (xr[gr][0][k], xr[gr][1][k]);
698                    lr += l.abs().powf(0.75) + r.abs().powf(0.75);
699                    mid_side += ((l + r) * std::f64::consts::FRAC_1_SQRT_2).abs().powf(0.75)
700                        + ((l - r) * std::f64::consts::FRAC_1_SQRT_2).abs().powf(0.75);
701                }
702            }
703            ms = mid_side < lr * 0.9;
704            if ms {
705                for gr_spec in &mut xr {
706                    for k in 0..GRANULE {
707                        let (l, r) = (gr_spec[0][k], gr_spec[1][k]);
708                        gr_spec[0][k] = (l + r) * std::f64::consts::FRAC_1_SQRT_2;
709                        gr_spec[1][k] = (l - r) * std::f64::consts::FRAC_1_SQRT_2;
710                    }
711                }
712            }
713        }
714
715        // Frame size, with padding.
716        let exact = 144_000 * self.cfg.kbps;
717        let rate = self.cfg.sample_rate;
718        self.padding_acc += exact % rate;
719        let padding = u32::from(self.padding_acc >= rate);
720        if padding == 1 {
721            self.padding_acc -= rate;
722        }
723        let size = (exact / rate + padding) as usize;
724        let capacity = ((size - 4 - self.side_bytes) * 8) as u32;
725
726        // Each granule-channel takes an equal share of what is left.
727        let mut granules: Vec<Granule> = Vec::with_capacity(2 * nch);
728        let mut left = capacity;
729        let mut remaining = (2 * nch) as u32;
730        for gr in 0..2 {
731            for ch in 0..nch {
732                let share = (left / remaining).min(4095);
733                let g = self.fit(&xr[gr][ch], share);
734                left -= g.bits.min(left);
735                remaining -= 1;
736                granules.push(g);
737            }
738        }
739
740        // Write: header, side info, main data.
741        let mut w = BitWriter::with_capacity(size);
742        w.write_bits(0x7FF, 11); // sync
743        w.write_bits(0b11, 2); // MPEG-1
744        w.write_bits(0b01, 2); // Layer III
745        w.write_bits(1, 1); // no CRC
746        w.write_bits(self.bitrate_index as u32, 4);
747        w.write_bits(self.sr_index as u32, 2);
748        w.write_bits(padding, 1);
749        w.write_bits(0, 1); // private
750        w.write_bits(if nch == 1 { 3 } else { 1 }, 2); // mono / joint stereo
751        w.write_bits(if ms { 2 } else { 0 }, 2);
752        w.write_bits(0, 1); // copyright
753        w.write_bits(1, 1); // original
754        w.write_bits(0, 2); // emphasis
755        w.write_bits(0, 9); // main_data_begin: no reservoir
756        w.write_bits(0, if nch == 1 { 5 } else { 3 });
757        for _ in 0..nch {
758            w.write_bits(0, 4); // scfsi
759        }
760        for g in &granules {
761            w.write_bits(g.bits, 12);
762            w.write_bits(g.big_values as u32, 9);
763            w.write_bits(g.global_gain, 8);
764            w.write_bits(0, 4); // scalefac_compress: no scalefactors
765            w.write_bits(0, 1); // window switching off
766            for t in g.tables {
767                w.write_bits(t as u32, 5);
768            }
769            w.write_bits(g.region0_count as u32, 4);
770            w.write_bits(g.region1_count as u32, 3);
771            w.write_bits(0, 1); // preflag
772            w.write_bits(0, 1); // scalefac_scale
773            w.write_bits(g.count1_table as u32, 1);
774        }
775        for g in &granules {
776            write_granule(&mut w, g, &self.long);
777        }
778        // Stuffing: zeros to the end of the frame.
779        let mut bytes = {
780            while !w.bit_len().is_multiple_of(8) {
781                w.write_bits(0, 1);
782            }
783            w.finish()
784        };
785        bytes.resize(size, 0);
786        self.frames += 1;
787        self.bytes += bytes.len() as u64;
788        bytes
789    }
790
791    /// Quantizes one granule at the finest step that fits `budget` bits.
792    fn fit(&self, spec: &[f64; GRANULE], budget: u32) -> Granule {
793        let pow34: Vec<f64> = spec.iter().map(|x| x.abs().powf(0.75)).collect();
794        let try_gain = |gg: u32| -> Option<Granule> {
795            let inv = (-0.75 * (f64::from(gg) - 210.0) / 4.0).exp2();
796            let mut ix = [0i32; GRANULE];
797            for k in 0..GRANULE {
798                let v = (pow34[k] * inv + 0.4054).floor();
799                if v > 8206.0 {
800                    return None;
801                }
802                ix[k] = v as i32;
803            }
804            let mut g = code_granule(&ix, &self.long)?;
805            for (k, v) in g.ix.iter_mut().enumerate() {
806                if spec[k] < 0.0 {
807                    *v = -*v;
808                }
809            }
810            g.global_gain = gg;
811            Some(g)
812        };
813        let (mut lo, mut hi) = (0u32, 255u32);
814        let mut best: Option<Granule> = None;
815        while lo <= hi {
816            let mid = (lo + hi) / 2;
817            match try_gain(mid) {
818                Some(g) if g.bits <= budget => {
819                    best = Some(g);
820                    if mid == 0 {
821                        break;
822                    }
823                    hi = mid - 1;
824                }
825                _ => lo = mid + 1,
826            }
827        }
828        best.unwrap_or_else(Granule::silent)
829    }
830}
831
832// ----------------------------------------------------------- info frame
833
834fn crc16(data: &[u8]) -> u16 {
835    // CRC-16, polynomial 0x8005 reflected (what LAME computes over its tag).
836    let mut crc = 0u16;
837    for &b in data {
838        crc ^= u16::from(b);
839        for _ in 0..8 {
840            crc = if crc & 1 != 0 {
841                (crc >> 1) ^ 0xA001
842            } else {
843                crc >> 1
844            };
845        }
846    }
847    crc
848}
849
850/// A valid silent frame carrying the Xing `Info` tag and a LAME-style
851/// extension, which is where players read the encoder delay and padding.
852///
853/// Players decide whether the extension is there by its first four bytes, so
854/// they say `LAME`; the next five name the encoder.
855fn build_info_frame(enc: &Mp3Encoder, frames: u64, bytes: u64, samples: u64) -> Vec<u8> {
856    let cfg = enc.cfg;
857    let size = (144_000 * cfg.kbps / cfg.sample_rate) as usize;
858    let mut f = vec![0u8; size];
859    f[0] = 0xFF;
860    f[1] = 0xFB;
861    f[2] = ((enc.bitrate_index as u8) << 4) | ((enc.sr_index as u8) << 2);
862    f[3] = (if cfg.channels == 1 { 3 } else { 1 }) << 6;
863    let at = 4 + enc.side_bytes;
864    let file_bytes = (bytes + size as u64) as u32;
865    f[at..at + 4].copy_from_slice(b"Info");
866    f[at + 4..at + 8].copy_from_slice(&3u32.to_be_bytes()); // frames and bytes present
867    f[at + 8..at + 12].copy_from_slice(&(frames as u32).to_be_bytes());
868    f[at + 12..at + 16].copy_from_slice(&file_bytes.to_be_bytes());
869    // The extension follows the fields the flags announce.
870    let l = at + 16;
871    f[l..l + 9].copy_from_slice(b"LAMEthrs ");
872    f[l + 9] = 0x01; // tag revision 0, constant bitrate
873    f[l + 10] = ((f64::from(cfg.kbps) * 1000.0 / cfg.channels as f64 * 0.25)
874        .clamp(4_000.0, 20_000.0)
875        / 100.0) as u8; // low-pass, 100 Hz units
876    f[l + 20] = cfg.kbps.min(255) as u8;
877    // Delay and padding, 12 bits each: the delay a decoder removes besides
878    // its own 529 samples, and the silence at the end.
879    let delay = DELAY - 529;
880    let padding = (frames * FRAME as u64).saturating_sub(delay as u64 + samples) as u32;
881    f[l + 21] = (delay >> 4) as u8;
882    f[l + 22] = (((delay & 15) << 4) as u8) | ((padding >> 8) as u8 & 15);
883    f[l + 23] = padding as u8;
884    f[l + 28..l + 32].copy_from_slice(&file_bytes.to_be_bytes()); // music length
885    let crc = crc16(&f[..l + 34]);
886    f[l + 34..l + 36].copy_from_slice(&crc.to_be_bytes());
887    f
888}
889
890/// Encodes whole channels to an `.mp3` file, `Info` frame first.
891pub fn encode_mp3(planar: &[Vec<f32>], cfg: &Mp3Config) -> Result<Vec<u8>, Mp3Error> {
892    let mut enc = Mp3Encoder::new(*cfg)?;
893    let views: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect();
894    let mut body = enc.push(&views)?;
895    body.extend(enc.finish());
896    let mut out = enc.info_frame();
897    out.extend(body);
898    Ok(out)
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904
905    #[test]
906    fn every_table_is_a_prefix_code_that_covers_its_values() {
907        let t = tables();
908        for (n, table) in t.pairs.iter().enumerate() {
909            let Some(table) = table else { continue };
910            if n == 0 {
911                continue;
912            }
913            // Kraft: the code lengths sum to at most 1, and nothing is a
914            // prefix of anything else.
915            let mut codes = Vec::new();
916            for x in 0..16 {
917                for y in 0..16 {
918                    if table.len[x][y] > 0 {
919                        codes.push((u32::from(table.code[x][y]), u32::from(table.len[x][y])));
920                    }
921                }
922            }
923            let kraft: f64 = codes.iter().map(|&(_, l)| 0.5f64.powi(l as i32)).sum();
924            assert!(kraft <= 1.0 + 1e-9, "table {n}: Kraft sum {kraft}");
925            for (i, &(a, la)) in codes.iter().enumerate() {
926                for &(b, lb) in &codes[i + 1..] {
927                    let l = la.min(lb);
928                    assert_ne!(
929                        a >> (la - l),
930                        b >> (lb - l),
931                        "table {n}: one code starts another"
932                    );
933                }
934            }
935            let xmax = if table.linbits > 0 {
936                15
937            } else {
938                table.max as usize
939            };
940            for x in 0..=xmax {
941                for y in 0..=xmax {
942                    assert!(table.len[x][y] > 0, "table {n} lacks ({x},{y})");
943                }
944            }
945        }
946        for (n, q) in t.quads.iter().enumerate() {
947            assert!(
948                q.len.iter().all(|&l| l > 0),
949                "count-1 table {n} covers all 16 quads"
950            );
951            let kraft: f64 = q.len.iter().map(|&l| 0.5f64.powi(i32::from(l))).sum();
952            assert!((kraft - 1.0).abs() < 1e-9, "count-1 table {n}: {kraft}");
953        }
954        // Table 1's well-known codes.
955        let t1 = t.pairs[1].as_ref().unwrap();
956        assert_eq!((t1.len[0][0], t1.code[0][0]), (1, 1));
957        assert_eq!((t1.len[1][1], t1.code[1][1]), (3, 0));
958    }
959
960    #[test]
961    fn the_window_is_the_prototype_filter() {
962        let w = &tables().window;
963        assert!((w[256] - 75_038.0 / 65_536.0 / 32.0).abs() < 1e-12);
964        // Symmetric in magnitude about 256, with the sign alternating by 64.
965        for i in 1..256 {
966            assert!((w[i].abs() - w[512 - i].abs()).abs() < 1e-12, "{i}");
967        }
968        assert!(w[10] < 0.0 && w[100] < 0.0 || w[100] > 0.0, "signs are set");
969    }
970
971    #[test]
972    fn bad_settings_are_refused() {
973        assert_eq!(
974            Mp3Encoder::new(Mp3Config::new(22_050, 2, 128)).err(),
975            Some(Mp3Error::SampleRate(22_050))
976        );
977        assert_eq!(
978            Mp3Encoder::new(Mp3Config::new(44_100, 3, 128)).err(),
979            Some(Mp3Error::Channels(3))
980        );
981        assert_eq!(
982            Mp3Encoder::new(Mp3Config::new(44_100, 2, 100)).err(),
983            Some(Mp3Error::Bitrate(100))
984        );
985        let mut enc = Mp3Encoder::new(Mp3Config::new(44_100, 2, 128)).unwrap();
986        assert!(matches!(
987            enc.push(&[&[0.0; 4][..]]),
988            Err(Mp3Error::Input(_))
989        ));
990    }
991}