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
// bitstream.rs — MSB-first bit writer and bit reader.

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

use crate::crc::{crc8_update, crc16_update};

const OUTBUF_SIZE: usize = 65536;
const INBUF_SIZE:  usize = 65536;

// ---------------------------------------------------------------------------
// BitWriter
// ---------------------------------------------------------------------------

pub struct BitWriter<W: Write> {
    handle:       W,
    /// Partial-byte accumulator; bits are packed MSB-first into the low bits.
    /// Only the low `bits_used` bits are valid.
    buffer:       u8,
    bits_used:    u8,
    pub crc8:     u8,
    pub crc16:    u16,
    outbuf:       Box<[u8; OUTBUF_SIZE]>,
    outbuf_len:   usize,
    bytes_written: u64,
}

impl<W: Write> BitWriter<W> {
    pub fn new(handle: W) -> Self {
        Self {
            handle,
            buffer:        0,
            bits_used:     0,
            crc8:          0,
            crc16:         0,
            outbuf:        Box::new([0u8; OUTBUF_SIZE]),
            outbuf_len:    0,
            bytes_written: 0,
        }
    }

    fn flush_outbuf(&mut self) -> io::Result<()> {
        if self.outbuf_len == 0 {
            return Ok(());
        }
        self.handle.write_all(&self.outbuf[..self.outbuf_len])?;
        self.outbuf_len = 0;
        Ok(())
    }

    fn emit_byte(&mut self, b: u8) -> io::Result<()> {
        self.crc8  = crc8_update(self.crc8, b);
        self.crc16 = crc16_update(self.crc16, b);
        self.outbuf[self.outbuf_len] = b;
        self.outbuf_len += 1;
        self.bytes_written += 1;
        if self.outbuf_len == OUTBUF_SIZE {
            self.flush_outbuf()?;
        }
        Ok(())
    }

    /// Writes `count` bits of `value`, MSB-first. `count` must be ≤ 64.
    pub fn write_bits(&mut self, value: u64, count: u8) -> io::Result<usize> {
        if count == 0 {
            return Ok(0);
        }
        let mut bytes_written = 0usize;
        let mut remaining = count;
        let clean = if count == 64 { value } else { value & ((1u64 << count) - 1) };

        while remaining > 0 {
            let space = 8 - self.bits_used;
            if remaining >= space {
                let shift = remaining - space;
                let bits = ((clean >> shift) & ((1u64 << space) - 1)) as u8;
                let byte = (self.buffer << (space % 8)) | bits;
                self.emit_byte(byte)?;
                bytes_written += 1;
                remaining -= space;
                self.bits_used = 0;
                self.buffer = 0;
            } else {
                self.buffer = (self.buffer << remaining)
                    | (clean as u8 & ((1u8 << remaining) - 1));
                self.bits_used += remaining;
                remaining = 0;
            }
        }
        Ok(bytes_written)
    }

    /// Writes `count` zero bits. Optimised for unary Rice coding.
    pub fn write_zeros(&mut self, count: u32) -> io::Result<usize> {
        if count == 0 {
            return Ok(0);
        }
        let mut total_written = 0usize;
        let mut remaining = count;

        // Fill any partial byte first.
        if self.bits_used > 0 {
            let fill = (8 - self.bits_used) as u32;
            if remaining < fill {
                self.buffer <<= remaining as u8;
                self.bits_used += remaining as u8;
                return Ok(0);
            }
            self.buffer <<= fill as u8;
            self.emit_byte(self.buffer)?;
            total_written += 1;
            self.buffer = 0;
            self.bits_used = 0;
            remaining -= fill;
        }

        // Emit whole zero bytes.
        let zero_bytes = remaining / 8;
        for _ in 0..zero_bytes {
            self.emit_byte(0)?;
            total_written += 1;
        }
        remaining %= 8;

        // Queue leftover bits.
        if remaining > 0 {
            self.buffer = 0;
            self.bits_used = remaining as u8;
        }

        Ok(total_written)
    }

    /// Writes raw bytes, flushing any pending partial byte first.
    pub fn write_bytes(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.is_empty() {
            return Ok(0);
        }
        if self.bits_used > 0 {
            let final_byte = self.buffer << (8 - self.bits_used);
            self.emit_byte(final_byte)?;
            self.buffer = 0;
            self.bits_used = 0;
        }
        for &b in bytes {
            self.emit_byte(b)?;
        }
        self.flush_outbuf()?;
        Ok(bytes.len())
    }

    /// Writes raw bytes directly to the output buffer without updating CRC accumulators.
    /// Use this when stitching pre-encoded frame data where CRC was already finalized.
    pub fn write_bytes_raw(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.is_empty() {
            return Ok(0);
        }
        // Must be byte-aligned — caller is responsible for ensuring this.
        debug_assert_eq!(self.bits_used, 0, "write_bytes_raw called with pending bits");
        self.bytes_written += bytes.len() as u64;

        let mut pos = 0;
        while pos < bytes.len() {
            let space = OUTBUF_SIZE - self.outbuf_len;
            let chunk = (bytes.len() - pos).min(space);
            self.outbuf[self.outbuf_len..self.outbuf_len + chunk]
                .copy_from_slice(&bytes[pos..pos + chunk]);
            self.outbuf_len += chunk;
            pos += chunk;
            if self.outbuf_len == OUTBUF_SIZE {
                self.handle.write_all(&self.outbuf[..self.outbuf_len])?;
                self.outbuf_len = 0;
            }
        }
        Ok(bytes.len())
    }

    /// Pads to next byte boundary with zero bits (padding excluded from CRCs).
    /// Flushes the output buffer.
    pub fn flush(&mut self) -> io::Result<usize> {
        let mut n = 0;
        if self.bits_used > 0 {
            let final_byte = self.buffer << (8 - self.bits_used);
            // Write directly to outbuf without updating CRCs (per FLAC spec).
            self.outbuf[self.outbuf_len] = final_byte;
            self.outbuf_len += 1;
            n += 1;
            self.buffer = 0;
            self.bits_used = 0;
        }
        self.flush_outbuf()?;
        Ok(n)
    }

    /// Frame header flush: the final partial byte IS included in CRC-8.
    pub fn flush_header(&mut self) -> io::Result<()> {
        if self.bits_used > 0 {
            self.buffer <<= 8 - self.bits_used;
            let b = self.buffer;
            self.emit_byte(b)?;
            self.buffer = 0;
            self.bits_used = 0;
        }
        self.flush_outbuf()
    }

    /// Finalizes a frame: flushes the last partial byte into CRC-16,
    /// flushes the output buffer, and returns the CRC-16.
    pub fn finalize_frame(&mut self) -> io::Result<u16> {
        if self.bits_used > 0 {
            self.buffer <<= 8 - self.bits_used;
            let b = self.buffer;
            self.emit_byte(b)?;
            self.buffer = 0;
            self.bits_used = 0;
        }
        self.flush_outbuf()?;
        Ok(self.crc16)
    }

    pub fn reset_crc8(&mut self)  { self.crc8  = 0; }
    pub fn reset_crc16(&mut self) { self.crc16 = 0; }
    pub fn bits_pending(&self) -> u8  { self.bits_used }
    pub fn bytes_written(&self) -> u64 { self.bytes_written }
}

// ---------------------------------------------------------------------------
// BitReader
// ---------------------------------------------------------------------------

pub struct BitReader<R: Read> {
    handle:     R,
    /// Staging word: bits held MSB-first in the high `bits_avail` bits.
    bits:       u64,
    bits_avail: u8,
    inbuf:      Box<[u8; INBUF_SIZE]>,
    inbuf_pos:  usize,
    inbuf_len:  usize,
    pub crc8:   u8,
    pub crc16:  u16,
}

impl<R: Read> BitReader<R> {
    pub fn new(handle: R) -> Self {
        Self {
            handle,
            bits:       0,
            bits_avail: 0,
            inbuf:      Box::new([0u8; INBUF_SIZE]),
            inbuf_pos:  0,
            inbuf_len:  0,
            crc8:       0,
            crc16:      0,
        }
    }

    pub fn reset_crc8(&mut self)  { self.crc8  = 0; }
    pub fn reset_crc16(&mut self) { self.crc16 = 0; }
    pub fn bits_avail(&self) -> u8 { self.bits_avail }

    fn refill_byte(&mut self) -> io::Result<bool> {
        if self.inbuf_pos >= self.inbuf_len {
            let n = self.handle.read(&mut self.inbuf[..])?;
            if n == 0 {
                return Ok(false); // EOF
            }
            self.inbuf_pos = 0;
            self.inbuf_len = n;
        }
        let b = self.inbuf[self.inbuf_pos];
        self.inbuf_pos += 1;
        self.crc8  = crc8_update(self.crc8, b);
        self.crc16 = crc16_update(self.crc16, b);
        self.bits |= (b as u64) << (56 - self.bits_avail);
        self.bits_avail += 8;
        Ok(true)
    }

    /// Reads exactly `count` bits (1–57), MSB-first. Returns `None` on EOF.
    pub fn read_bits(&mut self, count: u8) -> io::Result<Option<u64>> {
        debug_assert!(count > 0 && count <= 57, "read_bits: count must be 1–57");
        while self.bits_avail < count {
            if !self.refill_byte()? {
                return Ok(None);
            }
        }
        let val = self.bits >> (64 - count);
        self.bits <<= count;
        self.bits_avail -= count;
        Ok(Some(val))
    }

    /// Reads `count` bits without updating CRC accumulators.
    /// Used when reading checksum fields.
    pub fn read_bits_nocrc(&mut self, count: u8) -> io::Result<Option<u64>> {
        debug_assert!(count > 0 && count <= 57, "read_bits_nocrc: count must be 1–57");
        while self.bits_avail < count {
            let crc8_save  = self.crc8;
            let crc16_save = self.crc16;
            if !self.refill_byte()? {
                return Ok(None);
            }
            self.crc8  = crc8_save;
            self.crc16 = crc16_save;
        }
        let val = self.bits >> (64 - count);
        self.bits <<= count;
        self.bits_avail -= count;
        Ok(Some(val))
    }

    /// Reads a unary-coded non-negative integer (counts leading zeros
    /// up to the terminating 1). Returns the zero count (Rice quotient).
    pub fn read_unary(&mut self) -> io::Result<Option<u32>> {
        let mut q = 0u32;
        loop {
            while self.bits_avail == 0 {
                if !self.refill_byte()? {
                    return Ok(None);
                }
            }
            let leading = leading_zeros_in_staging(self.bits, self.bits_avail);
            if leading < self.bits_avail {
                q += leading as u32;
                self.bits <<= leading + 1;
                self.bits_avail -= leading + 1;
                return Ok(Some(q));
            }
            q += self.bits_avail as u32;
            self.bits = 0;
            self.bits_avail = 0;
        }
    }

    /// Discards bits until the reader is byte-aligned.
    pub fn align(&mut self) {
        let leftover = self.bits_avail % 8;
        if leftover != 0 {
            self.bits <<= leftover;
            self.bits_avail -= leftover;
        }
    }
}

/// Counts leading zero bits in the top `avail` bits of a u64 staging word.
fn leading_zeros_in_staging(bits: u64, avail: u8) -> u8 {
    let mut n = 0u8;
    let mut mask = 1u64 << 63;
    while n < avail {
        if bits & mask != 0 {
            break;
        }
        n += 1;
        mask >>= 1;
    }
    n
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_bit_writer_basic() {
        let mut buf = Vec::new();
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0b1011, 4).unwrap();
        w.write_bits(0b0001, 4).unwrap();
        w.write_bits(0b1, 1).unwrap();
        w.flush().unwrap();
        assert_eq!(buf[0], 0xb1);
        assert_eq!(buf[1], 0x80);
    }

    #[test]
    fn test_bit_reader_roundtrip() {
        let mut buf = Vec::new();
        {
            let mut w = BitWriter::new(&mut buf);
            w.write_bits(0b1011, 4).unwrap();
            w.write_bits(0b01,   2).unwrap();
            w.write_bits(0b1,    1).unwrap();
            w.write_bits(0b0,    1).unwrap();
            w.flush().unwrap();
        }
        let mut r = BitReader::new(Cursor::new(&buf));
        assert_eq!(r.read_bits(4).unwrap(), Some(0b1011));
        assert_eq!(r.read_bits(2).unwrap(), Some(0b01));
        assert_eq!(r.read_bits(1).unwrap(), Some(0b1));
        assert_eq!(r.read_bits(1).unwrap(), Some(0b0));
    }

    #[test]
    fn test_read_unary() {
        let mut buf = Vec::new();
        {
            let mut w = BitWriter::new(&mut buf);
            w.write_bits(1u64, 1).unwrap();   // q=0
            w.write_zeros(3).unwrap();         // q=3: '000'
            w.write_bits(1u64, 1).unwrap();    //       '1'
            w.flush().unwrap();
        }
        let mut r = BitReader::new(Cursor::new(&buf));
        assert_eq!(r.read_unary().unwrap(), Some(0));
        assert_eq!(r.read_unary().unwrap(), Some(3));
    }
}