forge
Explore
Log in

Don't you dare go Hollow

Word-buffered granule bit emission, cost-only rate loop

Browse files at this commit

d97b1acc1fa91c4a04a56f33132ad0e8e8b32e4bAhmet Kaan GümüşParent: d5d7c0a
  • perf
    • word-buffered granule bit emission, cost-only rate loop
Show full message
perf(mp3): word-buffered granule bit emission, cost-only rate loop

The profile was 45% inside BitWriter's per-bit loop and most of another
22% in code_spectrum's Vec<bool> round-trip: every rate-loop round wrote
the granule's bits out and re-expanded them one bool per bit for the
frame writer. BitBuf buffers the same MSB-first bitstream through a u64
accumulator; the rate loop now judges candidate gains by Huffman cost
alone and the kept configuration is materialised exactly once. All eight
bench fixtures encode byte-identically; the crate suite is green.
encode: stereo CBR 8.2x -> 18.2x realtime, VBR 4.0x -> 10.6x.
crates/ec-mp3/src/encode.rsmodified+132 -85
@@ -19,7 +19,7 @@
19 19
20 use crate::filterbank::{Analysis, alias_expand};20 use crate::filterbank::{Analysis, alias_expand};
21 use crate::header::{ChannelMode, FrameHeader, Version};21 use crate::header::{ChannelMode, FrameHeader, Version};
22-use crate::huffman::{self, Table};22+use crate::huffman::{self, BitBuf, Table};
23 use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, short_widths, windows};23 use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, short_widths, windows};
24 use ec_core::bitio::BitWriter;24 use ec_core::bitio::BitWriter;
25 use ec_core::error::{Error, Result};25 use ec_core::error::{Error, Result};
@@ -94,7 +94,7 @@ const DEMAND_SPLIT: f64 = 0.7;
94 /// One granule's worth of coded spectrum plus the side info describing it.94 /// One granule's worth of coded spectrum plus the side info describing it.
95 #[derive(Clone, Debug)]95 #[derive(Clone, Debug)]
96 struct CodedGranule {96 struct CodedGranule {
97- bits: Vec<bool>,97+ bits: BitBuf,
98 part2_3_length: u32,98 part2_3_length: u32,
99 big_values: u32,99 big_values: u32,
100 global_gain: u32,100 global_gain: u32,
@@ -932,13 +932,10 @@ impl Mp3Encode {
932 debug_assert_eq!(side_bytes.len(), side_info_len);932 debug_assert_eq!(side_bytes.len(), side_info_len);
933 933
934 // Append the granule data to the stream at `used`, byte aligned.934 // Append the granule data to the stream at `used`, byte aligned.
935- let mut main = BitWriter::new();935+ let mut main = BitBuf::new();
936 for granule in &coded {936 for granule in &coded {
937- for bit in &granule.bits {937+ main.append(&granule.bits);
938- main.write_bit(*bit);
939 }938 }
940- }
941- main.align_to_byte();
942 let main_bytes = main.into_bytes();939 let main_bytes = main.into_bytes();
943 // Stream positions the reservoir cap skipped over are stuffing, not940 // Stream positions the reservoir cap skipped over are stuffing, not
944 // data, so they are zeros rather than a shorter stream.941 // data, so they are zeros rather than a shorter stream.
@@ -1103,7 +1100,7 @@ fn quantise_granule(
1103 if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) {1100 if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) {
1104 return (1101 return (
1105 CodedGranule {1102 CodedGranule {
1106- bits: Vec::new(),1103+ bits: BitBuf::new(),
1107 part2_3_length: 0,1104 part2_3_length: 0,
1108 big_values: 0,1105 big_values: 0,
1109 global_gain: 0,1106 global_gain: 0,
@@ -1211,29 +1208,35 @@ fn census(exit: (&str, usize)) {
1211 }1208 }
1212 }1209 }
1213 1210
1214-/// Bitstream order for a short block's spectrum.1211+/// Puts a spectrum into bitstream order in `out`.
1215 ///1212 ///
1216 /// A short granule is coded band by band, window by window, line by line,1213 /// A short granule is coded band by band, window by window, line by line,
1217 /// while the spectrum the transform produces interleaves the three windows on1214 /// while the spectrum the transform produces interleaves the three windows on
1218 /// every line — the decoder's reorder step. The encoder has to undo it before1215 /// every line — the decoder's reorder step. The encoder has to undo it before
1219 /// Huffman coding; writing spectral order instead costs exactly the same1216 /// Huffman coding; writing spectral order instead costs exactly the same
1220 /// number of bits, lands exactly on `part2_3_length`, and hands the decoder a1217 /// number of bits, lands exactly on `part2_3_length`, and hands the decoder a
1221-/// permuted granule, which comes back as noise.1218+/// permuted granule, which comes back as noise. A long block is already in
1222-fn short_reorder(sample_rate: u32, spectral: &[i32]) -> Vec<i32> {1219+/// order and is copied as is.
1220+fn recode_into(spectral: &[i32; 576], block_type: u8, sample_rate: u32, out: &mut [i32; 576]) {
1221+ if block_type != 2 {
1222+ *out = *spectral;
1223+ return;
1224+ }
1223 let widths = short_widths(sample_rate);1225 let widths = short_widths(sample_rate);
1224 let starts = short_starts(sample_rate);1226 let starts = short_starts(sample_rate);
1225- let mut out = Vec::with_capacity(576);1227+ let mut position = 0usize;
1226 for sfb in 0..13 {1228 for sfb in 0..13 {
1227 let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb]));1229 let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb]));
1228 for window in 0..3 {1230 for window in 0..3 {
1229 for line in 0..width {1231 for line in 0..width {
1230- let position = (start + line) * 3 + window;1232+ out[position] = spectral[(start + line) * 3 + window];
1231- out.push(spectral.get(position).copied().unwrap_or(0));1233+ position += 1;
1232 }1234 }
1233 }1235 }
1234 }1236 }
1235- out.resize(576, 0);1237+ for slot in out.iter_mut().skip(position) {
1236- out1238+ *slot = 0;
1239+ }
1237 }1240 }
1238 1241
1239 /// The largest scalefactor a band can actually carry.1242 /// The largest scalefactor a band can actually carry.
@@ -1273,6 +1276,13 @@ fn band_thresholds(threshold: &[f32], block_type: u8, sample_rate: u32) -> Vec<f
1273 1276
1274 /// Quantises with a fixed scalefactor set, running the rate loop on1277 /// Quantises with a fixed scalefactor set, running the rate loop on
1275 /// `global_gain`, and reports the noise each band ends up with.1278 /// `global_gain`, and reports the noise each band ends up with.
1279+///
1280+/// The rate loop judges every candidate gain by Huffman cost alone
1281+/// ([`plan_spectrum`]); the granule's bits are materialised exactly once,
1282+/// for the configuration the loop keeps ([`write_spectrum`]). Writing the
1283+/// bits per round — and re-expanding them into a `Vec<bool>` to hand them
1284+/// to the frame writer — was the largest single cost in the encoder's
1285+/// profile, and said nothing the cost pass had not already said.
1276 fn code_with(1286 fn code_with(
1277 xr: &[f32],1287 xr: &[f32],
1278 block_type: u8,1288 block_type: u8,
@@ -1298,21 +1308,19 @@ fn code_with(
1298 2101308 210
1299 };1309 };
1300 let mut gain = start.clamp(0, 255);1310 let mut gain = start.clamp(0, 255);
1301- let mut ix = vec![0i32; 576];1311+ let mut ix = [0i32; 576];
1302- let mut coded;1312+ let mut coding = [0i32; 576];
1313+ let mut trial: [i32; 576];
1303 // The rate loop runs both ways: down while there are bits to spare, up1314 // The rate loop runs both ways: down while there are bits to spare, up
1304 // while the granule is too big for them. A line that saturates the coding1315 // while the granule is too big for them. A line that saturates the coding
1305 // range is not "cheap", it is clipped, so that check comes first.1316 // range is not "cheap", it is clipped, so that check comes first.
1306 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);1317 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);
1307- let for_coding = |ix: &[i32]| -> Vec<i32> {1318+ let mut plan_of = |ix: &[i32; 576]| -> SpectrumPlan {
1308- if block_type == 2 {1319+ recode_into(ix, block_type, sample_rate, &mut coding);
1309- short_reorder(sample_rate, ix)1320+ plan_spectrum(&coding, block_type, sample_rate)
1310- } else {
1311- ix.to_vec()
1312- }
1313 };1321 };
1314 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);1322 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1315- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1323+ let mut coded = plan_of(&ix);
1316 if peak <= 1e-20 {1324 if peak <= 1e-20 {
1317 // Below the smallest representable level: every line quantises to1325 // Below the smallest representable level: every line quantises to
1318 // zero at any gain (the quantiser's scale multiplies zero either1326 // zero at any gain (the quantiser's scale multiplies zero either
@@ -1325,26 +1333,26 @@ fn code_with(
1325 gain = 0;1333 gain = 0;
1326 } else {1334 } else {
1327 loop {1335 loop {
1328- if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {1336+ if (saturated(&ix) || coded.cost > target_bits) && gain < 255 {
1329 gain += 1;1337 gain += 1;
1330 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);1338 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1331- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1339+ coded = plan_of(&ix);
1332 continue;1340 continue;
1333 }1341 }
1334- if saturated(&ix) || coded.0 > target_bits || gain == 0 {1342+ if saturated(&ix) || coded.cost > target_bits || gain == 0 {
1335 break;1343 break;
1336 }1344 }
1337 // Try one step quieter; keep it only if it still fits and stays1345 // Try one step quieter; keep it only if it still fits and stays
1338 // inside the coding range.1346 // inside the coding range.
1339- let mut trial = ix.clone();1347+ trial = ix;
1340 quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);1348 quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);
1341- let trial_coded = code_spectrum(&for_coding(&trial), block_type, sample_rate);1349+ let trial_plan = plan_of(&trial);
1342- if trial_coded.0 > target_bits || saturated(&trial) {1350+ if trial_plan.cost > target_bits || saturated(&trial) {
1343 break;1351 break;
1344 }1352 }
1345 gain -= 1;1353 gain -= 1;
1346 ix = trial;1354 ix = trial;
1347- coded = trial_coded;1355+ coded = trial_plan;
1348 }1356 }
1349 }1357 }
1350 // Last resort: if even the quietest legal gain will not fit the bits we1358 // Last resort: if even the quietest legal gain will not fit the bits we
@@ -1352,14 +1360,13 @@ fn code_with(
1352 // overruns its budget would corrupt the reservoir for every frame after1360 // overruns its budget would corrupt the reservoir for every frame after
1353 // it, which is far worse than a low-passed one.1361 // it, which is far worse than a low-passed one.
1354 let mut limit = 576usize;1362 let mut limit = 576usize;
1355- while coded.0 > target_bits && limit > 4 {1363+ while coded.cost > target_bits && limit > 4 {
1356 limit = limit * 3 / 4;1364 limit = limit * 3 / 4;
1357 for slot in ix.iter_mut().skip(limit) {1365 for slot in ix.iter_mut().skip(limit) {
1358 *slot = 0;1366 *slot = 0;
1359 }1367 }
1360- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1368+ coded = plan_of(&ix);
1361 }1369 }
1362- let (_, big_values, tables, region0, region1, count1_select, bits) = coded;
1363 let mut noise = [0.0f32; SFB_LONG];1370 let mut noise = [0.0f32; SFB_LONG];
1364 let power = power43();1371 let power = power43();
1365 let residual = |i: usize, band: usize| -> f32 {1372 let residual = |i: usize, band: usize| -> f32 {
@@ -1384,41 +1391,38 @@ fn code_with(
1384 noise[band] = sum;1391 noise[band] = sum;
1385 }1392 }
1386 }1393 }
1387- let mut out = BitWriter::new();1394+ // Materialise the granule: scalefactors, then the spectrum the plan
1395+ // chose, in bitstream order.
1396+ recode_into(&ix, block_type, sample_rate, &mut coding);
1397+ let mut bits = BitBuf::new();
1388 if block_type == 2 {1398 if block_type == 2 {
1389 // The decoder reads short scalefactors band-major, three windows at a1399 // The decoder reads short scalefactors band-major, three windows at a
1390 // time; ours are one per band, so each is written three times.1400 // time; ours are one per band, so each is written three times.
1391 for (band, value) in scalefac.iter().enumerate().take(12) {1401 for (band, value) in scalefac.iter().enumerate().take(12) {
1392 let slen = if band < 6 { slen1 } else { slen2 };1402 let slen = if band < 6 { slen1 } else { slen2 };
1393 for _window in 0..3 {1403 for _window in 0..3 {
1394- out.write_bits(u32::from(*value), slen);1404+ bits.push_bits(u64::from(*value), slen);
1395 }1405 }
1396 }1406 }
1397 } else {1407 } else {
1398 for (band, value) in scalefac.iter().enumerate() {1408 for (band, value) in scalefac.iter().enumerate() {
1399 let slen = if band < 11 { slen1 } else { slen2 };1409 let slen = if band < 11 { slen1 } else { slen2 };
1400- out.write_bits(u32::from(*value), slen);1410+ bits.push_bits(u64::from(*value), slen);
1401- }
1402 }1411 }
1403- let scalefac_bits = out.bit_len() as u32;
1404- let mut bits_out: Vec<bool> = Vec::with_capacity((scalefac_bits + bits.len() as u32) as usize);
1405- let bytes = out.into_bytes();
1406- for i in 0..scalefac_bits as usize {
1407- bits_out.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
1408 }1412 }
1409- bits_out.extend_from_slice(&bits);1413+ write_spectrum(&coded, &coding, &mut bits);
1410 let granule = CodedGranule {1414 let granule = CodedGranule {
1411- part2_3_length: bits_out.len() as u32,1415+ part2_3_length: bits.bit_len(),
1412- bits: bits_out,1416+ bits,
1413- big_values,1417+ big_values: coded.big_values,
1414 global_gain: gain as u32,1418 global_gain: gain as u32,
1415 scalefac_compress: compress,1419 scalefac_compress: compress,
1416 block_type,1420 block_type,
1417- table_select: tables,1421+ table_select: coded.tables,
1418- region0_count: region0,1422+ region0_count: coded.region0,
1419- region1_count: region1,1423+ region1_count: coded.region1,
1420 scalefac_scale: false,1424 scalefac_scale: false,
1421- count1table_select: count1_select,1425+ count1table_select: coded.count1_select,
1422 };1426 };
1423 (granule, noise)1427 (granule, noise)
1424 }1428 }
@@ -1481,14 +1485,29 @@ fn short_band(index: usize, sample_rate: u32) -> usize {
1481 .unwrap_or(0)1485 .unwrap_or(0)
1482 }1486 }
1483 1487
1484-/// Chooses the region split, the tables and the count1 boundary, and writes the1488+/// The coding a spectrum gets: region split, tables, count1 boundary, and
1485-/// spectrum. Returns the bit cost first so the rate loop can stop early.1489+/// the bit cost the rate loop judges candidate gains by.
1486-#[allow(clippy::type_complexity)]1490+#[derive(Clone, Copy, Debug)]
1487-fn code_spectrum(1491+struct SpectrumPlan {
1488- ix: &[i32],1492+ cost: u32,
1493+ big_values: u32,
1494+ tables: [u8; 3],
1495+ region0: u32,
1496+ region1: u32,
1497+ count1_select: bool,
1498+ bounds: [usize; 3],
1499+ big_end: usize,
1500+ count1_end: usize,
1501+}
1502+
1503+/// Trailing zeros, the count1 boundary, and the region split for a coded
1504+/// spectrum, in bitstream order. The planner and the writer read these off
1505+/// one structure so both see the same boundaries.
1506+fn regions(
1507+ ix: &[i32; 576],
1489 block_type: u8,1508 block_type: u8,
1490 sample_rate: u32,1509 sample_rate: u32,
1491-) -> (u32, u32, [u8; 3], u32, u32, bool, Vec<bool>) {1510+) -> (u32, u32, [usize; 3], usize, usize) {
1492 // Trailing zeros are not coded at all; before them, a run of values in1511 // Trailing zeros are not coded at all; before them, a run of values in
1493 // -1..=1 is coded four at a time.1512 // -1..=1 is coded four at a time.
1494 let mut rzero = 576;1513 let mut rzero = 576;
@@ -1539,9 +1558,16 @@ fn code_spectrum(
1539 (r0 as u32, r1 as u32, [a, b.max(a), big_end])1558 (r0 as u32, r1 as u32, [a, b.max(a), big_end])
1540 }1559 }
1541 };1560 };
1561+ (region0, region1, bounds, big_end, count1_end)
1562+}
1542 1563
1564+/// Chooses the region split, the tables and the count1 boundary, and prices
1565+/// the spectrum. The rate loop calls this for every candidate gain; only the
1566+/// configuration it keeps is ever written ([`write_spectrum`]).
1567+fn plan_spectrum(ix: &[i32; 576], block_type: u8, sample_rate: u32) -> SpectrumPlan {
1568+ let (region0, region1, bounds, big_end, count1_end) = regions(ix, block_type, sample_rate);
1543 let mut tables = [0u8; 3];1569 let mut tables = [0u8; 3];
1544- let mut writer = BitWriter::new();1570+ let mut cost = 0u32;
1545 let mut from = 0usize;1571 let mut from = 0usize;
1546 for (region, to) in bounds.iter().enumerate() {1572 for (region, to) in bounds.iter().enumerate() {
1547 let to = (*to).min(big_end);1573 let to = (*to).min(big_end);
@@ -1551,43 +1577,64 @@ fn code_spectrum(
1551 let table = huffman::big_table(usize::from(select)).expect("table exists");1577 let table = huffman::big_table(usize::from(select)).expect("table exists");
1552 let mut i = from;1578 let mut i = from;
1553 while i + 1 < to {1579 while i + 1 < to {
1554- huffman::write_pair(&mut writer, table, ix[i], ix[i + 1]);1580+ cost += huffman::pair_bits(table, ix[i].unsigned_abs(), ix[i + 1].unsigned_abs())
1581+ .expect("the chosen table codes every pair in its region");
1555 i += 2;1582 i += 2;
1556 }1583 }
1557 }1584 }
1558 from = to;1585 from = to;
1559 }1586 }
1560 // count1: try both tables, keep the cheaper.1587 // count1: try both tables, keep the cheaper.
1561- let quads: Vec<[i32; 4]> = (big_end..count1_end)1588+ let quads_cost = |select: bool| -> u32 {
1562- .step_by(4)1589+ let mut sum = 0;
1563- .filter(|i| i + 4 <= 576)1590+ let mut i = big_end;
1564- .map(|i| [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]])1591+ while i + 4 <= count1_end {
1565- .collect();1592+ sum += huffman::quad_bits(select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]);
1566- let cost = |select: bool| -> u32 {1593+ i += 4;
1567- quads1594+ }
1568- .iter()1595+ sum
1569- .map(|quad| huffman::quad_bits(select, *quad))
1570- .sum()
1571 };1596 };
1572- let count1_select = cost(true) < cost(false);1597+ let count1_select = quads_cost(true) < quads_cost(false);
1573- for quad in &quads {1598+ cost += quads_cost(count1_select);
1574- huffman::write_quad(&mut writer, count1_select, *quad);1599+ SpectrumPlan {
1575- }1600+ cost,
1576- let bit_len = writer.bit_len() as usize;1601+ big_values: (big_end / 2) as u32,
1577- let bytes = writer.into_bytes();
1578- let mut bits = Vec::with_capacity(bit_len);
1579- for i in 0..bit_len {
1580- bits.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
1581- }
1582- (
1583- bits.len() as u32,
1584- (big_end / 2) as u32,
1585 tables,1602 tables,
1586 region0,1603 region0,
1587 region1,1604 region1,
1588 count1_select,1605 count1_select,
1589- bits,1606+ bounds,
1590- )1607+ big_end,
1608+ count1_end,
1609+ }
1610+}
1611+
1612+/// Writes the coded spectrum the plan names into `out`, pairs and quadruples
1613+/// in bitstream order. `ix` is the spectrum in bitstream order, the same
1614+/// array the plan was computed from.
1615+fn write_spectrum(plan: &SpectrumPlan, ix: &[i32; 576], out: &mut BitBuf) {
1616+ let mut from = 0usize;
1617+ for (region, to) in plan.bounds.iter().enumerate() {
1618+ let to = (*to).min(plan.big_end);
1619+ if to > from {
1620+ let table = huffman::big_table(usize::from(plan.tables[region])).expect("table exists");
1621+ let mut i = from;
1622+ while i + 1 < to {
1623+ huffman::write_pair(out, table, ix[i], ix[i + 1]);
1624+ i += 2;
1625+ }
1626+ }
1627+ from = to;
1628+ }
1629+ let mut i = plan.big_end;
1630+ while i + 4 <= plan.count1_end {
1631+ huffman::write_quad(
1632+ out,
1633+ plan.count1_select,
1634+ [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]],
1635+ );
1636+ i += 4;
1637+ }
1591 }1638 }
1592 1639
1593 /// Tables that can code a region whose largest magnitude is `max`, cheapest1640 /// Tables that can code a region whose largest magnitude is `max`, cheapest
crates/ec-mp3/src/huffman.rsmodified+97 -10
@@ -2,7 +2,7 @@
2 //! process, and the encoder's cost/write side.2 //! process, and the encoder's cost/write side.
3 3
4 use crate::huffman_tables::*;4 use crate::huffman_tables::*;
5-use ec_core::bitio::{BitReader, BitWriter};5+use ec_core::bitio::BitReader;
6 use ec_core::error::{Error, Result};6 use ec_core::error::{Error, Result};
7 use std::sync::OnceLock;7 use std::sync::OnceLock;
8 8
@@ -175,6 +175,93 @@ pub(crate) fn decode_quad(
175 Ok(())175 Ok(())
176 }176 }
177 177
178+/// A byte-backed bit accumulator for the granule coder: the same MSB-first
179+/// convention as [`ec_core::bitio::BitWriter`], but buffering through a `u64`
180+/// accumulator and appending whole bit runs, so a granule's Huffman codes and
181+/// its splice into the main-data stream stop costing one call per bit.
182+///
183+/// The encoder's profile was ~45% inside `BitWriter::write_bit`'s per-bit
184+/// branch-store cycle (plus the `Vec<bool>` materialisation every rate-loop
185+/// round paid to hand granule bits up to the frame writer); this is the same
186+/// bitstream, emitted a word at a time.
187+#[derive(Clone, Debug, Default)]
188+pub(crate) struct BitBuf {
189+ /// Completed bytes.
190+ bytes: Vec<u8>,
191+ /// Pending bits, top-aligned in the accumulator (`used < 8`).
192+ acc: u64,
193+ used: u32,
194+}
195+
196+impl BitBuf {
197+ /// An empty buffer.
198+ pub(crate) fn new() -> BitBuf {
199+ BitBuf::default()
200+ }
201+
202+ /// Bits written so far.
203+ pub(crate) fn bit_len(&self) -> u32 {
204+ (self.bytes.len() as u32) * 8 + self.used
205+ }
206+
207+ /// Appends the low `n` bits of `value` (`n <= 64`), most significant first.
208+ pub(crate) fn push_bits(&mut self, value: u64, n: u32) {
209+ debug_assert!(n <= 64, "push_bits: n = {n} > 64");
210+ let mask = if n >= 64 { u64::MAX } else { (1u64 << n) - 1 };
211+ self.acc |= (value & mask) << (64 - self.used - n);
212+ self.used += n;
213+ while self.used >= 8 {
214+ self.bytes.push((self.acc >> 56) as u8);
215+ self.acc <<= 8;
216+ self.used -= 8;
217+ }
218+ }
219+
220+ /// Appends one bit.
221+ pub(crate) fn push_bit(&mut self, bit: bool) {
222+ if bit {
223+ self.acc |= 1u64 << (63 - self.used);
224+ }
225+ self.used += 1;
226+ if self.used == 8 {
227+ self.bytes.push((self.acc >> 56) as u8);
228+ self.acc = 0;
229+ self.used = 0;
230+ }
231+ }
232+
233+ /// Appends the first `nbits` of `src`, most significant first — the bulk
234+ /// path a granule's bits take into the frame's main-data stream.
235+ pub(crate) fn push_bits_from(&mut self, src: &[u8], nbits: u32) {
236+ let mut bit = 0;
237+ while bit < nbits {
238+ let take = (nbits - bit).min(8);
239+ let byte = src[(bit / 8) as usize];
240+ let off = bit % 8;
241+ let value = u64::from(byte >> (8 - off - take)) & ((1u64 << take) - 1);
242+ self.push_bits(value, take);
243+ bit += take;
244+ }
245+ }
246+
247+ /// Appends every bit of `other`.
248+ pub(crate) fn append(&mut self, other: &BitBuf) {
249+ self.push_bits_from(&other.bytes, (other.bytes.len() as u32) * 8);
250+ if other.used > 0 {
251+ self.push_bits(other.acc >> (64 - other.used), other.used);
252+ }
253+ }
254+
255+ /// Zero-pads to the byte boundary and hands back the bytes, the partial
256+ /// byte's unused low bits zero — exactly what `BitWriter` produces.
257+ pub(crate) fn into_bytes(mut self) -> Vec<u8> {
258+ if self.used > 0 {
259+ self.bytes.push((self.acc >> 56) as u8);
260+ }
261+ self.bytes
262+ }
263+}
264+
178 /// Bits one pair costs in `table`, or `None` when the pair is out of range.265 /// Bits one pair costs in `table`, or `None` when the pair is out of range.
179 pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> {266 pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> {
180 let max = u32::from(table.dim) - 1;267 let max = u32::from(table.dim) - 1;
@@ -203,19 +290,19 @@ pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> {
203 }290 }
204 291
205 /// Writes one pair; the caller has already checked it fits the table.292 /// Writes one pair; the caller has already checked it fits the table.
206-pub(crate) fn write_pair(writer: &mut BitWriter, table: Table, x: i32, y: i32) {293+pub(crate) fn write_pair(writer: &mut BitBuf, table: Table, x: i32, y: i32) {
207 let max = u32::from(table.dim) - 1;294 let max = u32::from(table.dim) - 1;
208 let escape = table.linbits > 0;295 let escape = table.linbits > 0;
209 let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs());296 let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs());
210 let (ix, iy) = (ax.min(max), ay.min(max));297 let (ix, iy) = (ax.min(max), ay.min(max));
211 let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize];298 let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize];
212- writer.write_bits(u32::from(code), u32::from(len));299+ writer.push_bits(u64::from(code), u32::from(len));
213 for (value, abs) in [(x, ax), (y, ay)] {300 for (value, abs) in [(x, ax), (y, ay)] {
214 if abs >= max && escape {301 if abs >= max && escape {
215- writer.write_bits(abs - max, u32::from(table.linbits));302+ writer.push_bits(u64::from(abs - max), u32::from(table.linbits));
216 }303 }
217 if abs != 0 {304 if abs != 0 {
218- writer.write_bit(value < 0);305+ writer.push_bit(value < 0);
219 }306 }
220 }307 }
221 }308 }
@@ -230,15 +317,15 @@ pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 {
230 }317 }
231 318
232 /// Writes one count1 quadruple.319 /// Writes one count1 quadruple.
233-pub(crate) fn write_quad(writer: &mut BitWriter, select: bool, quad: [i32; 4]) {320+pub(crate) fn write_quad(writer: &mut BitBuf, select: bool, quad: [i32; 4]) {
234 let index = quad321 let index = quad
235 .iter()322 .iter()
236 .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));323 .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));
237 let (len, code) = count1_table(select)[index];324 let (len, code) = count1_table(select)[index];
238- writer.write_bits(u32::from(code), u32::from(len));325+ writer.push_bits(u64::from(code), u32::from(len));
239 for value in quad {326 for value in quad {
240 if value != 0 {327 if value != 0 {
241- writer.write_bit(value < 0);328+ writer.push_bit(value < 0);
242 }329 }
243 }330 }
244 }331 }
@@ -299,7 +386,7 @@ mod tests {
299 continue;386 continue;
300 }387 }
301 let max = u32::from(table.dim) - 1;388 let max = u32::from(table.dim) - 1;
302- let mut writer = BitWriter::new();389+ let mut writer = BitBuf::new();
303 let mut wanted = Vec::new();390 let mut wanted = Vec::new();
304 for x in 0..=max {391 for x in 0..=max {
305 for y in 0..=max {392 for y in 0..=max {
@@ -321,7 +408,7 @@ mod tests {
321 #[test]408 #[test]
322 fn quads_round_trip() {409 fn quads_round_trip() {
323 for select in [false, true] {410 for select in [false, true] {
324- let mut writer = BitWriter::new();411+ let mut writer = BitBuf::new();
325 let mut wanted = Vec::new();412 let mut wanted = Vec::new();
326 for index in 0..16 {413 for index in 0..16 {
327 let quad = [414 let quad = [