Module: Omnizip::Algorithms::BZip2::Bz2

Defined in:
lib/omnizip/algorithms/bzip2/bz2.rb

Overview

Standard bzip2 wire format (port of the omnizip-rs omnizip-bzip2/src/bz2 module).

Output is decodable by bzip2 -d; input from the bzip2 CLI decodes here. Pipeline: RLE1 -> BWT -> seeded MTF -> RLE2 (RUNA/RUNB) -> canonical Huffman, MSB-first bit packing, with the bzip2 CRC-32 variant on every block and a combined stream CRC.

Defined Under Namespace

Classes: BitReader, BitWriter

Constant Summary collapse

BLOCK_MAGIC =
0x3141_5926_5359
EOS_MAGIC =
0x1772_4538_5090
ITERATIONS =
4
GROUP_SIZE =
50
MAX_GROUPS =
6
MAX_CODE_LENGTH =
23
RUNA =
0
RUNB =
1
CRC_TABLE =
Array.new(256) do |i|
  crc = i << 24
  8.times do
    crc = if crc.nobits?(0x8000_0000)
            (crc << 1) & 0xFFFF_FFFF
          else
            ((crc << 1) ^ 0x04C1_1DB7) & 0xFFFF_FFFF
          end
  end
  crc
end

Class Method Summary collapse

Class Method Details

.build_sequence(data) ⇒ Object

The active bytes in ascending order (the seeded-MTF table).



204
205
206
207
208
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 204

def build_sequence(data)
  seen = Array.new(256, false)
  data.each_byte { |b| seen[b] = true }
  (0...256).select { |b| seen[b] }
end

.build_symbol_map(data) ⇒ Object

bzip2 symbol usage map: 16-bit group word, then one 16-bit byte map per used group (bit 15 - index, MSB-first order). rubocop:disable-next Metrics/AbcSize



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 257

def build_symbol_map(data)
  used = Array.new(256, false)
  data.each_byte { |b| used[b] = true }

  groups_used = 0
  detail = []
  16.times do |g|
    group_bits = 0
    any = false
    16.times do |j|
      next unless used[(g * 16) + j]

      group_bits |= 1 << (15 - j)
      any = true
    end
    next unless any

    groups_used |= 1 << (15 - g)
    detail << group_bits
  end
  [groups_used, detail]
end

.build_table(lengths) ⇒ Object

Canonical code table: entries sorted for bit-by-bit match.



582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 582

def build_table(lengths)
  alphabet = lengths.length
  order = (0...alphabet).sort_by { |i| [lengths[i], i] }
  entries = []
  code = 0
  length = 0
  order.each do |i|
    while length < lengths[i]
      code <<= 1
      length += 1
    end
    next unless lengths[i].positive?

    entries << [i, code, lengths[i]]
    code += 1
  end
  entries
end

.canonical_codes(lengths) ⇒ Object

Canonical codes assigned in (length, symbol) order. rubocop:disable-next Metrics/AbcSize



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 358

def canonical_codes(lengths)
  max_len = lengths.max || 0
  codes = Array.new(lengths.length) { [0, 0] }
  return codes if max_len.zero?

  bl_count = Array.new(max_len + 1, 0)
  lengths.each { |l| bl_count[l] += 1 if l.positive? }

  next_code = Array.new(max_len + 1, 0)
  code = 0
  (1..max_len).each do |bits|
    code = (code + bl_count[bits - 1]) << 1
    next_code[bits] = code
  end
  lengths.each_with_index do |len, sym|
    next unless len.positive?

    codes[sym] = [next_code[len], len]
    next_code[len] += 1
  end
  codes
end

.code_lengths(freqs) ⇒ Object

Canonical Huffman code lengths (every symbol gets a code; zero frequencies become 1) with rescaling to keep lengths within bzip2's 23-bit limit. rubocop:disable Metrics/MethodLength rubocop:disable-next Metrics/AbcSize



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 285

def code_lengths(freqs)
  n = freqs.length
  active = freqs.each_index.map { |i| [(freqs[i].zero? ? 1 : freqs[i]), i] }
  return Array.new(n, 0) if active.empty?

  loop do
    lengths = huffman_lengths(active, n)
    max_len = lengths.max || 0
    return lengths if max_len <= MAX_CODE_LENGTH

    scaled = false
    active.map! do |(w, i)|
      if w > 1
        scaled = true
        [(w + 1) / 2, i]
      else
        [w, i]
      end
    end
    # Can't reduce further: clamp.
    return lengths.map { |l| [l, MAX_CODE_LENGTH].min } unless scaled
  end
end

.compress(input, level = 9) ⇒ Object

Compress input into a standard .bz2 stream. level (1-9) selects the block size in 100 KB steps.



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
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 72

def compress(input, level = 9)
  raise Omnizip::CompressionError, "bzip2 level must be 1..9" unless (1..9).cover?(level)

  block_size = level * 100_000
  writer = BitWriter.new
  writer.write_bits("B".ord, 8)
  writer.write_bits("Z".ord, 8)
  writer.write_bits("h".ord, 8)
  writer.write_bits("0".ord + level, 8)

  if input.empty?
    writer.write48(EOS_MAGIC)
    writer.write_bits(0, 32)
    return writer.finish
  end

  combined = 0
  offset = 0
  while offset < input.bytesize
    chunk = input.byteslice(offset, block_size)
    offset += block_size
    block_crc = crc32(chunk)
    combined = rotate_left32(combined, 1) ^ block_crc
    encode_block(chunk, block_crc, writer)
  end
  writer.write48(EOS_MAGIC)
  writer.write_bits(combined, 32)
  writer.finish
end

.crc32(data) ⇒ Object

bzip2 CRC-32: non-reflected polynomial 0x04C11DB7, init 0xFFFFFFFF, final complement — NOT the zlib variant.



48
49
50
51
52
53
54
55
56
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 48

def crc32(data)
  table = CRC_TABLE
  crc = 0xFFFF_FFFF
  data.each_byte do |b|
    crc = ((crc << 8) & 0xFFFF_FFFF) ^
      table[((crc >> 24) ^ b) & 0xFF]
  end
  crc ^ 0xFFFF_FFFF
end

.decode_symbol(table, r) ⇒ Object



601
602
603
604
605
606
607
608
609
610
611
612
613
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 601

def decode_symbol(table, r)
  code = 0
  len = 0
  loop do
    code = (code << 1) | r.read_bit
    len += 1
    raise Omnizip::DecompressionError, "huffman code too long" if len > 24

    table.each do |(sym, c, l)|
      return sym if l == len && c == code
    end
  end
end

.decompress(input) ⇒ Object

rubocop:disable Metrics/MethodLength rubocop:disable-next Metrics/AbcSize Decompress a complete .bz2 stream (single member). Verifies every block CRC and the combined stream CRC.



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 414

def decompress(input)
  if input.bytesize < 4 || input.byteslice(0, 3) != "BZh" ||
      !input.getbyte(3).between?("0".ord, "9".ord)
    raise Omnizip::DecompressionError, "not a bzip2 stream (bad header)"
  end

  r = BitReader.new(input, 4)
  out = String.new(encoding: Encoding::BINARY)
  combined = 0
  # rubocop:disable-next Metrics/BlockLength
  loop do
    magic = r.read48
    if magic == EOS_MAGIC
      stored = r.read_bits(32)
      if stored != combined
        raise Omnizip::DecompressionError,
              format("combined CRC mismatch: stored %08X, " \
                     "computed %08X", stored, combined)
      end
      return out
    end
    unless magic == BLOCK_MAGIC
      raise Omnizip::DecompressionError,
            format("bad block magic %012X", magic)
    end

    block_crc = r.read_bits(32)
    if r.read_bit == 1
      raise Omnizip::DecompressionError,
            "randomised blocks are not supported"
    end
    orig_ptr = r.read_bits(24)

    groups = r.read_bits(16)
    if groups.zero?
      raise Omnizip::DecompressionError, "empty symbol map"
    end

    sequence = []
    16.times do |g|
      next unless groups.anybits?(1 << (15 - g))

      map = r.read_bits(16)
      16.times do |b|
        sequence << ((g * 16) + b) if map.anybits?(1 << (15 - b))
      end
    end
    n_in_use = sequence.length

    n_groups = r.read_bits(3)
    unless (2..MAX_GROUPS).cover?(n_groups)
      raise Omnizip::DecompressionError, "invalid nGroups #{n_groups}"
    end

    n_selectors = r.read_bits(15)
    if n_selectors.zero?
      raise Omnizip::DecompressionError, "zero selectors"
    end

    selector_mtf = []
    n_selectors.times do
      j = 0
      while r.read_bit == 1
        j += 1
        if j > MAX_GROUPS
          raise Omnizip::DecompressionError,
                "selector unary run too long"
        end
      end
      selector_mtf << j
    end
    order = (0...n_groups).to_a
    selectors = selector_mtf.map do |j|
      table = order.delete_at(j)
      order.unshift(table)
      table
    end

    alphabet = n_in_use + 2
    tables = Array.new(n_groups) do
      lengths = Array.new(alphabet, 0)
      cur = r.read_bits(5)
      alphabet.times do |slot|
        loop do
          break if r.read_bit.zero?

          cur += r.read_bit == 1 ? -1 : 1
        end
        lengths[slot] = cur
      end
      build_table(lengths)
    end

    eob = n_in_use + 1
    symbols = []
    catch(:eob) do
      selectors.each do |sel|
        table = tables[sel]
        GROUP_SIZE.times do
          sym = decode_symbol(table, r)
          throw :eob if sym == eob

          symbols << sym
        end
      end
    end

    mtf = symbols_to_mtf(symbols, n_in_use)
    bwt = mtf_decode_seeded(mtf, sequence)
    block = Bwt.new.decode(bwt, orig_ptr)
    data = Rle.new.decode(block)
    computed = crc32(data)
    if computed != block_crc
      raise Omnizip::DecompressionError,
            format("block CRC mismatch: stored %08X, " \
                   "computed %08X", block_crc, computed)
    end
    combined = rotate_left32(combined, 1) ^ block_crc
    out << data
  end
end

.encode_block(block, block_crc, writer) ⇒ Object

rubocop:disable Metrics/MethodLength rubocop:disable-next Metrics/AbcSize rubocop:disable Metrics/MethodLength rubocop:disable-next Metrics/AbcSize



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
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 106

def encode_block(block, block_crc, writer)
  rle1 = Rle.new.encode(block)
  bwt_data, primary_index = Bwt.new.encode(rle1)
  sequence = build_sequence(bwt_data)
  n_in_use = sequence.length
  mtf = mtf_encode_seeded(bwt_data, sequence)
  symbols = mtf_to_symbols(mtf, n_in_use)
  alphabet_size = n_in_use + 2

  writer.write48(BLOCK_MAGIC)
  writer.write_bits(block_crc, 32)
  writer.write_bit(false) # never randomised
  writer.write_bits(primary_index & 0xFF_FFFF, 24)

  groups_used, group_maps = build_symbol_map(bwt_data)
  writer.write_bits(groups_used, 16)
  group_maps.each { |g| writer.write_bits(g, 16) }

  # Upstream bzip2 table selection: the group count grows
  # with symbol count (2 below 200, 3 below 600, then toward
  # 6), then ITERATIONS rounds of chunk-to-table assignment by
  # cheapest total code length and table recomputation.
  chunks = symbols.each_slice(GROUP_SIZE).to_a
  chunk_freqs = chunks.map do |chunk|
    freq = Array.new(alphabet_size, 0)
    chunk.each { |s| freq[s] += 1 }
    freq
  end
  n_groups = if symbols.length < 200
               2
             else
               symbols.length < 600 ? 3 : 6
             end
  # The format requires 2..6 groups even for a single chunk.

  # Seed the tables with upstream bzip2's position ramp
  # (len[t][v] = v / (t+1) + 1): starting every table from
  # the global frequencies collapses the first assignment
  # round onto table 0 and the iteration never differentiates.
  lengths_per_table = Array.new(n_groups) do |t|
    Array.new(alphabet_size) { |v| [(v / (t + 1)) + 1, 20].min }
  end
  selectors = Array.new(chunks.length, 0)

  ITERATIONS.times do
    selectors = chunks.each_index.map do |ci|
      cf = chunk_freqs[ci]
      (0...n_groups).min_by do |ti|
        lengths = lengths_per_table[ti]
        cost = 0
        cf.each_with_index do |f, sym|
          cost += f * lengths[sym] if f.positive?
        end
        cost
      end
    end

    table_freqs = Array.new(n_groups) { Array.new(alphabet_size, 0) }
    selectors.each_with_index do |ti, ci|
      cf = chunk_freqs[ci]
      alphabet_size.times { |a| table_freqs[ti][a] += cf[a] }
    end
    lengths_per_table = Array.new(n_groups) { |i| code_lengths(table_freqs[i]) }
  end

  # MTF the selectors over the final table order.
  order = (0...n_groups).to_a
  mtf_selectors = selectors.map do |t|
    idx = order.index(t)
    order.delete_at(idx)
    order.unshift(t)
    idx
  end

  n_selectors = [chunks.length, 1].max
  writer.write_bits(n_groups, 3)
  writer.write_bits(n_selectors, 15)
  # MTF value N -> N '1's then '0'.
  mtf_selectors.each do |v|
    v.times { writer.write_bit(true) }
    writer.write_bit(false)
  end

  tables = lengths_per_table.map { |l| canonical_codes(l) }
  lengths_per_table.each { |l| write_huffman_table(writer, l) }

  chunks.each_with_index do |chunk, i|
    table = tables[selectors[i]]
    chunk.each do |sym|
      code, len = table[sym]
      writer.write_bits(code, len)
    end
  end
end

.huffman_lengths(active, alphabet_size) ⇒ Object

Standard Huffman via smallest-pair merging with parent pointers; depth = code length per active symbol. rubocop:disable-next Metrics/AbcSize



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
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 312

def huffman_lengths(active, alphabet_size)
  nodes = active.map { |(w, _i)| { freq: w, parent: -1 } }
  ids = active.map { |_w, i| i }
  next_id = alphabet_size

  loop do
    roots = []
    nodes.each_index { |k| roots << k if nodes[k][:parent] == -1 }
    break if roots.length <= 1

    a = -1
    b = -1
    roots.each do |k|
      if a == -1 || nodes[k][:freq] < nodes[a][:freq] ||
          (nodes[k][:freq] == nodes[a][:freq] && ids[k] < ids[a])
        b = a
        a = k
      elsif b == -1 || nodes[k][:freq] < nodes[b][:freq] ||
          (nodes[k][:freq] == nodes[b][:freq] && ids[k] < ids[b])
        b = k
      end
    end

    nodes[a][:parent] = nodes.length
    nodes[b][:parent] = nodes.length
    nodes << { freq: nodes[a][:freq] + nodes[b][:freq], parent: -1 }
    ids << next_id
    next_id += 1
  end

  out = Array.new(alphabet_size, 0)
  active.each_index do |k|
    sym = ids[k]
    len = 0
    cur = k
    while nodes[cur][:parent] != -1
      cur = nodes[cur][:parent]
      len += 1
    end
    out[sym] = [len, 1].max
  end
  out
end

.mtf_decode_seeded(data, sequence) ⇒ Object

Seed-aware MTF inverse over the active-byte sequence. Returns a binary String (the BWT stage consumes bytes).



566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 566

def mtf_decode_seeded(data, sequence)
  list = sequence.dup
  out = Array.new(data.length)
  data.each_with_index do |v, i|
    if v >= list.length
      out[i] = 0
    else
      b = list.delete_at(v)
      list.unshift(b)
      out[i] = b
    end
  end
  out.pack("C*")
end

.mtf_encode_seeded(data, sequence) ⇒ Object

rubocop:disable Metrics/MethodLength



211
212
213
214
215
216
217
218
219
220
221
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 211

def mtf_encode_seeded(data, sequence)
  table = sequence.dup
  out = []
  data.each_byte do |byte|
    pos = table.index(byte)
    out << pos
    table.delete_at(pos)
    table.unshift(byte)
  end
  out
end

.mtf_to_symbols(mtf_values, n_in_use) ⇒ Object

RUNA/RUNB (bijective base-2) zero-run encoding plus the value/EOB symbols; EOB = n_in_use + 1. rubocop:disable-next Metrics/AbcSize



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
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 226

def mtf_to_symbols(mtf_values, n_in_use)
  eob = n_in_use + 1
  out = []
  i = 0
  while i < mtf_values.length
    v = mtf_values[i]
    if v.zero?
      run = 0
      while i < mtf_values.length && mtf_values[i].zero?
        run += 1
        i += 1
      end
      n = run
      while n.positive?
        n -= 1
        out << (n.nobits?(1) ? RUNA : RUNB)
        n >>= 1
      end
    else
      out << (v + 1)
      i += 1
    end
  end
  out << eob
  out
end

.rotate_left32(v, n) ⇒ Object

rubocop:enable Metrics/MethodLength



406
407
408
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 406

def rotate_left32(v, n)
  ((v << n) | (v >> (32 - n))) & 0xFFFF_FFFF
end

.symbols_to_mtf(symbols, n_in_use) ⇒ Object

RUNA/RUNB symbol stream back to MTF values. rubocop:disable-next Metrics/AbcSize



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 539

def symbols_to_mtf(symbols, n_in_use)
  eob = n_in_use + 1
  mtf = []
  i = 0
  while i < symbols.length
    sym = symbols[i]
    if [RUNA, RUNB].include?(sym)
      run = 0
      bit = 1
      while i < symbols.length && [RUNA, RUNB].include?(symbols[i])
        run += symbols[i] == RUNB ? bit << 1 : bit
        bit <<= 1
        i += 1
      end
      [run, 1 << 24].min.times { mtf << 0 }
    elsif sym == eob
      break
    else
      mtf << (sym - 1)
      i += 1
    end
  end
  mtf
end

.write_huffman_table(writer, lengths) ⇒ Object

Delta-coded code-length table: 5-bit start length, then '10' (+1) / '11' (-1) adjustments and a '0' terminator per symbol.



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/omnizip/algorithms/bzip2/bz2.rb', line 384

def write_huffman_table(writer, lengths)
  writer.write_bits(lengths[0], 5)
  current = lengths[0]
  lengths.each do |target|
    diff = target - current
    while diff != 0
      writer.write_bit(true)
      if diff.positive?
        writer.write_bit(false)
        diff -= 1
        current += 1
      else
        writer.write_bit(true)
        diff += 1
        current -= 1
      end
    end
    writer.write_bit(false)
  end
end