rezin-flac 0.2.0

A high-performance parallel FLAC audio codec
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// subframe.rs — FLAC subframe encoding and decoding.

use std::io::{self, Read, Write};

use rezin_lpc::fixed::{predict_fixed, restore_fixed};
use rezin_lpc::quantize::{predict_lpc, restore_lpc};

use crate::bitstream::{BitReader, BitWriter};
use crate::entropy::{optimize_rice, read_rice, write_rice, zig_zag};

const MAX_BLOCK: usize = 4096;

// ---------------------------------------------------------------------------
// Encoding
// ---------------------------------------------------------------------------

/// Writes a subframe. If `q_lpc` is empty, selects the best fixed predictor.
/// Otherwise uses the supplied LPC coefficients.
pub fn write_subframe_lpc<W: Write>(
    w:       &mut BitWriter<W>,
    samples: &[i32],
    q_lpc:   &[i32],
    shift:   u8,
    bps:     u8,
) -> io::Result<usize> {
    let n = samples.len();

    if q_lpc.is_empty() {
        // No LPC coefficients — find the best fixed predictor order.
        let max_order = n.min(4) as u8;
        let mut best_order  = 0u8;
        let mut best_sum    = f64::INFINITY;
        let mut best_res    = vec![0i32; n];
        let mut fixed_res   = vec![0i32; n];

        for order in 0..=max_order {
            predict_fixed(samples, order, &mut fixed_res);
            let sum: u64 = fixed_res[order as usize..].iter()
                .map(|&v| if v >= 0 { v as u64 } else { -(v as i64) as u64 })
                .sum();
            if (sum as f64) < best_sum {
                best_sum   = sum as f64;
                best_order = order;
                best_res.copy_from_slice(&fixed_res);
            }
        }
        return write_subframe_fixed(w, samples, &best_res, best_order, bps);
    }

    // LPC subframe.
    let p = q_lpc.len();
    let mut lpc_res = vec![0i32; n];
    predict_lpc(samples, q_lpc, shift, &mut lpc_res);

    let mut total = 0usize;
    let order = p as u8;
    let subframe_type = (0b00100000u64 | (order - 1) as u64) << 1;
    total += w.write_bits(subframe_type, 8)?;

    // Warmup samples
    for i in 0..p {
        total += w.write_bits(samples[i] as i64 as u64, bps)?;
    }

    let coeff_precision: u8 = 15;
    total += w.write_bits((coeff_precision - 1) as u64, 4)?;
    total += w.write_bits(shift as u64, 5)?;
    for i in 0..p {
        total += w.write_bits(
            (q_lpc[i] as u64) & ((1u64 << coeff_precision) - 1),
            coeff_precision,
        )?;
    }

    total += write_residuals(w, &lpc_res[p..], order)?;
    Ok(total)
}

fn write_subframe_fixed<W: Write>(
    w:         &mut BitWriter<W>,
    samples:   &[i32],
    residuals: &[i32],
    order:     u8,
    bps:       u8,
) -> io::Result<usize> {
    let mut total = 0usize;
    let subframe_type = ((0b001000u64 | order as u64) << 1) as u64;
    total += w.write_bits(subframe_type, 8)?;

    for i in 0..order as usize {
        total += w.write_bits(samples[i] as i64 as u64, bps)?;
    }

    total += write_residuals(w, &residuals[order as usize..], order)?;
    Ok(total)
}

pub fn write_subframe_constant<W: Write>(
    w:     &mut BitWriter<W>,
    value: i32,
    bps:   u8,
) -> io::Result<usize> {
    let mut total = 0usize;
    total += w.write_bits(0x00, 8)?; // type 0b000000, wasted=0
    total += w.write_bits(value as i64 as u64, bps)?;
    Ok(total)
}

fn best_partition_order(residuals: &[i32], predictor_order: u8) -> u8 {
    let n = residuals.len();
    let block_size = n + predictor_order as usize;
    let mut best_order = 0u8;
    let mut best_bits  = u64::MAX;

    for order in 0u8..=4 {
        let num_partitions = 1u32 << order;
        if block_size as u32 % num_partitions != 0 { continue; }
        let part_size = block_size as u32 / num_partitions;
        if part_size <= predictor_order as u32 { continue; }

        let mut use_rice2 = false;
        let mut pos = 0usize;
        for p in 0..num_partitions {
            let count = if p == 0 {
                (part_size - predictor_order as u32) as usize
            } else {
                part_size as usize
            };
            let partition = &residuals[pos..pos + count];
            let mut rice_k = optimize_rice(partition);
            let max_zz = partition.iter().map(|&v| zig_zag(v)).max().unwrap_or(0);
            while max_zz >> rice_k > 30 && rice_k < 30 { rice_k += 1; }
            if rice_k > 14 { use_rice2 = true; }
            pos += count;
        }

        let k_bits: u64 = if use_rice2 { 5 } else { 4 };
        let mut estimated_bits: u64 = 0;
        pos = 0;
        for p in 0..num_partitions {
            let count = if p == 0 {
                (part_size - predictor_order as u32) as usize
            } else {
                part_size as usize
            };
            let partition = &residuals[pos..pos + count];
            let mut rice_k = optimize_rice(partition);
            let max_zz = partition.iter().map(|&v| zig_zag(v)).max().unwrap_or(0);
            while max_zz >> rice_k > 30 && rice_k < 30 { rice_k += 1; }

            estimated_bits += k_bits;
            for &v in partition {
                let zz = zig_zag(v);
                estimated_bits += (zz >> rice_k) as u64 + 1 + rice_k as u64;
            }
            pos += count;
        }
        if estimated_bits < best_bits {
            best_bits  = estimated_bits;
            best_order = order;
        }
    }

    best_order
}

fn write_residuals<W: Write>(
    w:               &mut BitWriter<W>,
    residuals:       &[i32],
    predictor_order: u8,
) -> io::Result<usize> {
    let mut total = 0usize;
    let partition_order = best_partition_order(residuals, predictor_order);
    let block_size      = residuals.len() + predictor_order as usize;
    let num_partitions  = 1u32 << partition_order;
    let part_size       = block_size as u32 / num_partitions;

    // First pass: determine if any partition needs Rice2 (k > 14).
    let mut use_rice2 = false;
    let mut pos = 0usize;
    for p in 0..num_partitions {
        let count = if p == 0 {
            (part_size - predictor_order as u32) as usize
        } else {
            part_size as usize
        };
        let end = pos + count;
        let mut rice_k = optimize_rice(&residuals[pos..end]);
        let max_zz = residuals[pos..end].iter().map(|&v| zig_zag(v)).max().unwrap_or(0);
        while max_zz >> rice_k > 30 && rice_k < 30 { rice_k += 1; }
        if rice_k > 14 { use_rice2 = true; }
        pos += count;
    }

    total += w.write_bits(if use_rice2 { 1 } else { 0 }, 2)?;
    total += w.write_bits(partition_order as u64, 4)?;

    // Second pass: write parameters and samples.
    pos = 0;
    for p in 0..num_partitions {
        let count = if p == 0 {
            (part_size - predictor_order as u32) as usize
        } else {
            part_size as usize
        };
        let end = pos + count;
        let mut rice_k = optimize_rice(&residuals[pos..end]);
        let max_zz = residuals[pos..end].iter().map(|&v| zig_zag(v)).max().unwrap_or(0);
        while max_zz >> rice_k > 30 && rice_k < 30 { rice_k += 1; }

        total += w.write_bits(rice_k as u64, if use_rice2 { 5 } else { 4 })?;
        for i in pos..end {
            total += write_rice(w, residuals[i], rice_k)?;
        }
        pos += count;
    }

    Ok(total)
}

// ---------------------------------------------------------------------------
// Decoding
// ---------------------------------------------------------------------------

/// Reads and decodes a single FLAC subframe into `out`.
/// `bps` is the effective bits-per-sample (may be bps+1 for side channel).
pub fn read_subframe<R: Read>(
    r:   &mut BitReader<R>,
    out: &mut [i32],
    bps: u8,
) -> io::Result<()> {
    let _n = out.len();

    let hdr = match r.read_bits(8)? {
        Some(v) => v,
        None    => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF in subframe header")),
    };

    // Wasted bits flag
    let mut wasted = 0u8;
    if hdr & 1 == 1 {
        wasted = match r.read_unary()? {
            Some(v) => (v + 1) as u8,
            None    => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF in wasted bits")),
        };
    }
    let effective_bps = bps - wasted;
    let subframe_type = ((hdr >> 1) & 0x3F) as u8;

    if subframe_type == 0b000000 {
        read_subframe_constant(r, out, effective_bps, wasted)?;
    } else if subframe_type == 0b000010 {
        read_subframe_verbatim(r, out, effective_bps, wasted)?;
    } else if subframe_type & 0b111000 == 0b001000 {
        let order = subframe_type & 0b111;
        read_subframe_fixed(r, out, effective_bps, order, wasted)?;
    } else if subframe_type & 0b100000 == 0b100000 {
        let order = (subframe_type & 0b011111) + 1;
        read_subframe_lpc(r, out, effective_bps, order, wasted)?;
    } else {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "unknown subframe type"));
    }

    Ok(())
}

fn read_subframe_constant<R: Read>(
    r:      &mut BitReader<R>,
    out:    &mut [i32],
    bps:    u8,
    wasted: u8,
) -> io::Result<()> {
    let raw = match r.read_bits(bps)? {
        Some(v) => v,
        None    => return Err(eof()),
    };
    let value = (sign_extend(raw, bps) as u32).wrapping_shl(wasted as u32) as i32;
    out.fill(value);
    Ok(())
}

fn read_subframe_verbatim<R: Read>(
    r:      &mut BitReader<R>,
    out:    &mut [i32],
    bps:    u8,
    wasted: u8,
) -> io::Result<()> {
    for s in out.iter_mut() {
        let raw = match r.read_bits(bps)? {
            Some(v) => v,
            None    => return Err(eof()),
        };
        *s = (sign_extend(raw, bps) as u32).wrapping_shl(wasted as u32) as i32;
    }
    Ok(())
}

fn read_subframe_fixed<R: Read>(
    r:      &mut BitReader<R>,
    out:    &mut [i32],
    bps:    u8,
    order:  u8,
    wasted: u8,
) -> io::Result<()> {
    let n = out.len();
    for i in 0..order as usize {
        let raw = match r.read_bits(bps)? {
            Some(v) => v,
            None    => return Err(eof()),
        };
        out[i] = (sign_extend(raw, bps) as u32).wrapping_shl(wasted as u32) as i32;
    }

    read_residuals(r, &mut out[order as usize..], order)?;

    // Reconstruct in-place using a temporary buffer.
    let mut tmp = vec![0i32; n];
    restore_fixed(out, order, &mut tmp);
    out.copy_from_slice(&tmp);

    if wasted > 0 {
        for s in out[order as usize..].iter_mut() {
            *s = (*s as u32).wrapping_shl(wasted as u32) as i32;
        }
    }
    Ok(())
}

fn read_subframe_lpc<R: Read>(
    r:      &mut BitReader<R>,
    out:    &mut [i32],
    bps:    u8,
    order:  u8,
    wasted: u8,
) -> io::Result<()> {
    let n = out.len();
    for i in 0..order as usize {
        let raw = match r.read_bits(bps)? {
            Some(v) => v,
            None    => return Err(eof()),
        };
        out[i] = (sign_extend(raw, bps) as u32).wrapping_shl(wasted as u32) as i32;
    }

    let prec_raw = match r.read_bits(4)? {
        Some(v) => v,
        None    => return Err(eof()),
    };
    let precision = (prec_raw + 1) as u8;

    let shift_raw = match r.read_bits(5)? {
        Some(v) => v,
        None    => return Err(eof()),
    };
    let shift = shift_raw as u8;

    let mut q_lpc = [0i32; 12];
    for i in 0..order as usize {
        let raw = match r.read_bits(precision)? {
            Some(v) => v,
            None    => return Err(eof()),
        };
        q_lpc[i] = sign_extend(raw, precision);
    }

    read_residuals(r, &mut out[order as usize..], order)?;

    let mut tmp = vec![0i32; n];
    restore_lpc(out, &q_lpc[..order as usize], shift, &mut tmp);
    out.copy_from_slice(&tmp);

    if wasted > 0 {
        for s in out[order as usize..].iter_mut() {
            *s = (*s as u32).wrapping_shl(wasted as u32) as i32;
        }
    }
    Ok(())
}

fn read_residuals<R: Read>(
    r:               &mut BitReader<R>,
    out:             &mut [i32],
    predictor_order: u8,
) -> io::Result<()> {
    let method = match r.read_bits(2)? {
        Some(v) => v,
        None    => return Err(eof()),
    };
    let param_bits: u8 = if method == 0 { 4 } else { 5 };

    let partition_order = match r.read_bits(4)? {
        Some(v) => v as u8,
        None    => return Err(eof()),
    };

    let block_size      = out.len() + predictor_order as usize;
    let num_partitions  = 1u32 << partition_order;
    let part_size       = block_size as u32 / num_partitions;
    let mut pos         = 0usize;

    for p in 0..num_partitions {
        let count = if p == 0 {
            (part_size - predictor_order as u32) as usize
        } else {
            part_size as usize
        };
        let rice_k = match r.read_bits(param_bits)? {
            Some(v) => v as u8,
            None    => return Err(eof()),
        };
        for i in 0..count {
            out[pos + i] = match read_rice(r, rice_k)? {
                Some(v) => v,
                None    => return Err(eof()),
            };
        }
        pos += count;
    }
    Ok(())
}

fn sign_extend(val: u64, bits: u8) -> i32 {
    if bits == 0 { return 0; }
    let sign_bit = 1u64 << (bits - 1);
    if val & sign_bit != 0 {
        let mask = !((sign_bit << 1).wrapping_sub(1));
        (val | mask) as i64 as i32
    } else {
        val as i32
    }
}

#[inline]
fn eof() -> io::Error {
    io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected EOF in subframe")
}