Word-buffered granule bit emission, cost-only rate loop
Browse files at this commitd97b1acc1fa91c4a04a56f33132ad0e8e8b32e4bParent: d5d7c0a- perf
- word-buffered granule bit emission, cost-only rate loop
2 changed files +229 -95
- crates/ec-mp3/src/encode.rs +132 -85
- crates/ec-mp3/src/huffman.rs +97 -10
crates/ec-mp3/src/encode.rsmodified+132 -85
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | |
| 20 | 20 | use crate::filterbank::{Analysis, alias_expand}; |
| 21 | 21 | use crate::header::{ChannelMode, FrameHeader, Version}; |
| 22 | -use crate::huffman::{self, Table}; | |
| 22 | +use crate::huffman::{self, BitBuf, Table}; | |
| 23 | 23 | use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, short_widths, windows}; |
| 24 | 24 | use ec_core::bitio::BitWriter; |
| 25 | 25 | use ec_core::error::{Error, Result}; |
| @@ -94,7 +94,7 @@ const DEMAND_SPLIT: f64 = 0.7; | ||
| 94 | 94 | /// One granule's worth of coded spectrum plus the side info describing it. |
| 95 | 95 | #[derive(Clone, Debug)] |
| 96 | 96 | struct CodedGranule { |
| 97 | - bits: Vec<bool>, | |
| 97 | + bits: BitBuf, | |
| 98 | 98 | part2_3_length: u32, |
| 99 | 99 | big_values: u32, |
| 100 | 100 | global_gain: u32, |
| @@ -932,13 +932,10 @@ impl Mp3Encode { | ||
| 932 | 932 | debug_assert_eq!(side_bytes.len(), side_info_len); |
| 933 | 933 | |
| 934 | 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 | 936 | for granule in &coded { |
| 937 | - for bit in &granule.bits { | |
| 938 | - main.write_bit(*bit); | |
| 939 | - } | |
| 937 | + main.append(&granule.bits); | |
| 940 | 938 | } |
| 941 | - main.align_to_byte(); | |
| 942 | 939 | let main_bytes = main.into_bytes(); |
| 943 | 940 | // Stream positions the reservoir cap skipped over are stuffing, not |
| 944 | 941 | // data, so they are zeros rather than a shorter stream. |
| @@ -1103,7 +1100,7 @@ fn quantise_granule( | ||
| 1103 | 1100 | if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) { |
| 1104 | 1101 | return ( |
| 1105 | 1102 | CodedGranule { |
| 1106 | - bits: Vec::new(), | |
| 1103 | + bits: BitBuf::new(), | |
| 1107 | 1104 | part2_3_length: 0, |
| 1108 | 1105 | big_values: 0, |
| 1109 | 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 | 1213 | /// A short granule is coded band by band, window by window, line by line, |
| 1217 | 1214 | /// while the spectrum the transform produces interleaves the three windows on |
| 1218 | 1215 | /// every line — the decoder's reorder step. The encoder has to undo it before |
| 1219 | 1216 | /// Huffman coding; writing spectral order instead costs exactly the same |
| 1220 | 1217 | /// number of bits, lands exactly on `part2_3_length`, and hands the decoder a |
| 1221 | -/// permuted granule, which comes back as noise. | |
| 1222 | -fn short_reorder(sample_rate: u32, spectral: &[i32]) -> Vec<i32> { | |
| 1218 | +/// permuted granule, which comes back as noise. A long block is already in | |
| 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 | 1225 | let widths = short_widths(sample_rate); |
| 1224 | 1226 | let starts = short_starts(sample_rate); |
| 1225 | - let mut out = Vec::with_capacity(576); | |
| 1227 | + let mut position = 0usize; | |
| 1226 | 1228 | for sfb in 0..13 { |
| 1227 | 1229 | let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb])); |
| 1228 | 1230 | for window in 0..3 { |
| 1229 | 1231 | for line in 0..width { |
| 1230 | - let position = (start + line) * 3 + window; | |
| 1231 | - out.push(spectral.get(position).copied().unwrap_or(0)); | |
| 1232 | + out[position] = spectral[(start + line) * 3 + window]; | |
| 1233 | + position += 1; | |
| 1232 | 1234 | } |
| 1233 | 1235 | } |
| 1234 | 1236 | } |
| 1235 | - out.resize(576, 0); | |
| 1236 | - out | |
| 1237 | + for slot in out.iter_mut().skip(position) { | |
| 1238 | + *slot = 0; | |
| 1239 | + } | |
| 1237 | 1240 | } |
| 1238 | 1241 | |
| 1239 | 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 | 1277 | /// Quantises with a fixed scalefactor set, running the rate loop on |
| 1275 | 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 | 1286 | fn code_with( |
| 1277 | 1287 | xr: &[f32], |
| 1278 | 1288 | block_type: u8, |
| @@ -1298,21 +1308,19 @@ fn code_with( | ||
| 1298 | 1308 | 210 |
| 1299 | 1309 | }; |
| 1300 | 1310 | let mut gain = start.clamp(0, 255); |
| 1301 | - let mut ix = vec![0i32; 576]; | |
| 1302 | - let mut coded; | |
| 1311 | + let mut ix = [0i32; 576]; | |
| 1312 | + let mut coding = [0i32; 576]; | |
| 1313 | + let mut trial: [i32; 576]; | |
| 1303 | 1314 | // The rate loop runs both ways: down while there are bits to spare, up |
| 1304 | 1315 | // while the granule is too big for them. A line that saturates the coding |
| 1305 | 1316 | // range is not "cheap", it is clipped, so that check comes first. |
| 1306 | 1317 | let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191); |
| 1307 | - let for_coding = |ix: &[i32]| -> Vec<i32> { | |
| 1308 | - if block_type == 2 { | |
| 1309 | - short_reorder(sample_rate, ix) | |
| 1310 | - } else { | |
| 1311 | - ix.to_vec() | |
| 1312 | - } | |
| 1318 | + let mut plan_of = |ix: &[i32; 576]| -> SpectrumPlan { | |
| 1319 | + recode_into(ix, block_type, sample_rate, &mut coding); | |
| 1320 | + plan_spectrum(&coding, block_type, sample_rate) | |
| 1313 | 1321 | }; |
| 1314 | 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 | 1324 | if peak <= 1e-20 { |
| 1317 | 1325 | // Below the smallest representable level: every line quantises to |
| 1318 | 1326 | // zero at any gain (the quantiser's scale multiplies zero either |
| @@ -1325,26 +1333,26 @@ fn code_with( | ||
| 1325 | 1333 | gain = 0; |
| 1326 | 1334 | } else { |
| 1327 | 1335 | loop { |
| 1328 | - if (saturated(&ix) || coded.0 > target_bits) && gain < 255 { | |
| 1336 | + if (saturated(&ix) || coded.cost > target_bits) && gain < 255 { | |
| 1329 | 1337 | gain += 1; |
| 1330 | 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 | 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 | 1343 | break; |
| 1336 | 1344 | } |
| 1337 | 1345 | // Try one step quieter; keep it only if it still fits and stays |
| 1338 | 1346 | // inside the coding range. |
| 1339 | - let mut trial = ix.clone(); | |
| 1347 | + trial = ix; | |
| 1340 | 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); | |
| 1342 | - if trial_coded.0 > target_bits || saturated(&trial) { | |
| 1349 | + let trial_plan = plan_of(&trial); | |
| 1350 | + if trial_plan.cost > target_bits || saturated(&trial) { | |
| 1343 | 1351 | break; |
| 1344 | 1352 | } |
| 1345 | 1353 | gain -= 1; |
| 1346 | 1354 | ix = trial; |
| 1347 | - coded = trial_coded; | |
| 1355 | + coded = trial_plan; | |
| 1348 | 1356 | } |
| 1349 | 1357 | } |
| 1350 | 1358 | // Last resort: if even the quietest legal gain will not fit the bits we |
| @@ -1352,14 +1360,13 @@ fn code_with( | ||
| 1352 | 1360 | // overruns its budget would corrupt the reservoir for every frame after |
| 1353 | 1361 | // it, which is far worse than a low-passed one. |
| 1354 | 1362 | let mut limit = 576usize; |
| 1355 | - while coded.0 > target_bits && limit > 4 { | |
| 1363 | + while coded.cost > target_bits && limit > 4 { | |
| 1356 | 1364 | limit = limit * 3 / 4; |
| 1357 | 1365 | for slot in ix.iter_mut().skip(limit) { |
| 1358 | 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 | 1370 | let mut noise = [0.0f32; SFB_LONG]; |
| 1364 | 1371 | let power = power43(); |
| 1365 | 1372 | let residual = |i: usize, band: usize| -> f32 { |
| @@ -1384,41 +1391,38 @@ fn code_with( | ||
| 1384 | 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 | 1398 | if block_type == 2 { |
| 1389 | 1399 | // The decoder reads short scalefactors band-major, three windows at a |
| 1390 | 1400 | // time; ours are one per band, so each is written three times. |
| 1391 | 1401 | for (band, value) in scalefac.iter().enumerate().take(12) { |
| 1392 | 1402 | let slen = if band < 6 { slen1 } else { slen2 }; |
| 1393 | 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 | 1407 | } else { |
| 1398 | 1408 | for (band, value) in scalefac.iter().enumerate() { |
| 1399 | 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 | 1411 | } |
| 1402 | 1412 | } |
| 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 | - } | |
| 1409 | - bits_out.extend_from_slice(&bits); | |
| 1413 | + write_spectrum(&coded, &coding, &mut bits); | |
| 1410 | 1414 | let granule = CodedGranule { |
| 1411 | - part2_3_length: bits_out.len() as u32, | |
| 1412 | - bits: bits_out, | |
| 1413 | - big_values, | |
| 1415 | + part2_3_length: bits.bit_len(), | |
| 1416 | + bits, | |
| 1417 | + big_values: coded.big_values, | |
| 1414 | 1418 | global_gain: gain as u32, |
| 1415 | 1419 | scalefac_compress: compress, |
| 1416 | 1420 | block_type, |
| 1417 | - table_select: tables, | |
| 1418 | - region0_count: region0, | |
| 1419 | - region1_count: region1, | |
| 1421 | + table_select: coded.tables, | |
| 1422 | + region0_count: coded.region0, | |
| 1423 | + region1_count: coded.region1, | |
| 1420 | 1424 | scalefac_scale: false, |
| 1421 | - count1table_select: count1_select, | |
| 1425 | + count1table_select: coded.count1_select, | |
| 1422 | 1426 | }; |
| 1423 | 1427 | (granule, noise) |
| 1424 | 1428 | } |
| @@ -1481,14 +1485,29 @@ fn short_band(index: usize, sample_rate: u32) -> usize { | ||
| 1481 | 1485 | .unwrap_or(0) |
| 1482 | 1486 | } |
| 1483 | 1487 | |
| 1484 | -/// Chooses the region split, the tables and the count1 boundary, and writes the | |
| 1485 | -/// spectrum. Returns the bit cost first so the rate loop can stop early. | |
| 1486 | -#[allow(clippy::type_complexity)] | |
| 1487 | -fn code_spectrum( | |
| 1488 | - ix: &[i32], | |
| 1488 | +/// The coding a spectrum gets: region split, tables, count1 boundary, and | |
| 1489 | +/// the bit cost the rate loop judges candidate gains by. | |
| 1490 | +#[derive(Clone, Copy, Debug)] | |
| 1491 | +struct SpectrumPlan { | |
| 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 | 1508 | block_type: u8, |
| 1490 | 1509 | sample_rate: u32, |
| 1491 | -) -> (u32, u32, [u8; 3], u32, u32, bool, Vec<bool>) { | |
| 1510 | +) -> (u32, u32, [usize; 3], usize, usize) { | |
| 1492 | 1511 | // Trailing zeros are not coded at all; before them, a run of values in |
| 1493 | 1512 | // -1..=1 is coded four at a time. |
| 1494 | 1513 | let mut rzero = 576; |
| @@ -1539,9 +1558,16 @@ fn code_spectrum( | ||
| 1539 | 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 | 1569 | let mut tables = [0u8; 3]; |
| 1544 | - let mut writer = BitWriter::new(); | |
| 1570 | + let mut cost = 0u32; | |
| 1545 | 1571 | let mut from = 0usize; |
| 1546 | 1572 | for (region, to) in bounds.iter().enumerate() { |
| 1547 | 1573 | let to = (*to).min(big_end); |
| @@ -1551,43 +1577,64 @@ fn code_spectrum( | ||
| 1551 | 1577 | let table = huffman::big_table(usize::from(select)).expect("table exists"); |
| 1552 | 1578 | let mut i = from; |
| 1553 | 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 | 1582 | i += 2; |
| 1556 | 1583 | } |
| 1557 | 1584 | } |
| 1558 | 1585 | from = to; |
| 1559 | 1586 | } |
| 1560 | 1587 | // count1: try both tables, keep the cheaper. |
| 1561 | - let quads: Vec<[i32; 4]> = (big_end..count1_end) | |
| 1562 | - .step_by(4) | |
| 1563 | - .filter(|i| i + 4 <= 576) | |
| 1564 | - .map(|i| [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]) | |
| 1565 | - .collect(); | |
| 1566 | - let cost = |select: bool| -> u32 { | |
| 1567 | - quads | |
| 1568 | - .iter() | |
| 1569 | - .map(|quad| huffman::quad_bits(select, *quad)) | |
| 1570 | - .sum() | |
| 1588 | + let quads_cost = |select: bool| -> u32 { | |
| 1589 | + let mut sum = 0; | |
| 1590 | + let mut i = big_end; | |
| 1591 | + while i + 4 <= count1_end { | |
| 1592 | + sum += huffman::quad_bits(select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]); | |
| 1593 | + i += 4; | |
| 1594 | + } | |
| 1595 | + sum | |
| 1571 | 1596 | }; |
| 1572 | - let count1_select = cost(true) < cost(false); | |
| 1573 | - for quad in &quads { | |
| 1574 | - huffman::write_quad(&mut writer, count1_select, *quad); | |
| 1575 | - } | |
| 1576 | - let bit_len = writer.bit_len() as usize; | |
| 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, | |
| 1597 | + let count1_select = quads_cost(true) < quads_cost(false); | |
| 1598 | + cost += quads_cost(count1_select); | |
| 1599 | + SpectrumPlan { | |
| 1600 | + cost, | |
| 1601 | + big_values: (big_end / 2) as u32, | |
| 1585 | 1602 | tables, |
| 1586 | 1603 | region0, |
| 1587 | 1604 | region1, |
| 1588 | 1605 | count1_select, |
| 1589 | - bits, | |
| 1590 | - ) | |
| 1606 | + bounds, | |
| 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 | 1640 | /// 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 | 2 | //! process, and the encoder's cost/write side. |
| 3 | 3 | |
| 4 | 4 | use crate::huffman_tables::*; |
| 5 | -use ec_core::bitio::{BitReader, BitWriter}; | |
| 5 | +use ec_core::bitio::BitReader; | |
| 6 | 6 | use ec_core::error::{Error, Result}; |
| 7 | 7 | use std::sync::OnceLock; |
| 8 | 8 | |
| @@ -175,6 +175,93 @@ pub(crate) fn decode_quad( | ||
| 175 | 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 | 265 | /// Bits one pair costs in `table`, or `None` when the pair is out of range. |
| 179 | 266 | pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> { |
| 180 | 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 | 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 | 294 | let max = u32::from(table.dim) - 1; |
| 208 | 295 | let escape = table.linbits > 0; |
| 209 | 296 | let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs()); |
| 210 | 297 | let (ix, iy) = (ax.min(max), ay.min(max)); |
| 211 | 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 | 300 | for (value, abs) in [(x, ax), (y, ay)] { |
| 214 | 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 | 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 | 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 | 321 | let index = quad |
| 235 | 322 | .iter() |
| 236 | 323 | .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); |
| 237 | 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 | 326 | for value in quad { |
| 240 | 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 | 386 | continue; |
| 300 | 387 | } |
| 301 | 388 | let max = u32::from(table.dim) - 1; |
| 302 | - let mut writer = BitWriter::new(); | |
| 389 | + let mut writer = BitBuf::new(); | |
| 303 | 390 | let mut wanted = Vec::new(); |
| 304 | 391 | for x in 0..=max { |
| 305 | 392 | for y in 0..=max { |
| @@ -321,7 +408,7 @@ mod tests { | ||
| 321 | 408 | #[test] |
| 322 | 409 | fn quads_round_trip() { |
| 323 | 410 | for select in [false, true] { |
| 324 | - let mut writer = BitWriter::new(); | |
| 411 | + let mut writer = BitBuf::new(); | |
| 325 | 412 | let mut wanted = Vec::new(); |
| 326 | 413 | for index in 0..16 { |
| 327 | 414 | let quad = [ |