Debian Codegraph @

src/internal/ppmd7.rs

raw symbols SCIP
1 mod decoder;
2 mod encoder;
3 mod range_coding;
4
5 use std::{
6 alloc::{alloc_zeroed, dealloc, Layout},
7 io::{Read, Write},
8 mem::ManuallyDrop,
9 ptr::NonNull,
10 };
11
12 pub(crate) use range_coding::{RangeDecoder, RangeEncoder};
13
14 use super::*;
15 use crate::Error;
16
17 const MAX_FREQ: u8 = 124;
18 const UNIT_SIZE: isize = 12;
19 const K_TOP_VALUE: u32 = 1 << 24;
20 const EMPTY_NODE: u16 = 0;
21
22 static K_EXP_ESCAPE: [u8; 16] = [25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2];
23
24 static K_INIT_BIN_ESC: [u16; 8] = [
25 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051,
26 ];
27
28 #[derive(Copy, Clone)]
29 #[repr(C)]
30 struct Node {
31 stamp: u16,
32 nu: u16,
33 next: TaggedOffset,
34 prev: TaggedOffset,
35 }
36
37 impl Pointee for Node {
38 const TAG: u32 = TAG_NODE;
39 }
40
41 #[derive(Copy, Clone)]
42 #[repr(C)]
43 union NodeUnion {
44 node: Node,
45 next_ref: TaggedOffset,
46 }
47
48 impl Pointee for NodeUnion {
49 const TAG: u32 = TAG_NODE;
50 }
51
52 #[derive(Copy, Clone)]
53 #[repr(C)]
54 struct Context {
55 num_stats: u16,
56 union2: Union2,
57 union4: Union4,
58 suffix: TaggedOffset,
59 }
60
61 impl Pointee for Context {
62 const TAG: u32 = TAG_CONTEXT;
63 }
64
65 pub(crate) struct PPMd7<RC> {
66 min_context: NonNull<Context>,
67 max_context: NonNull<Context>,
68 found_state: NonNull<State>,
69 order_fall: u32,
70 init_esc: u32,
71 prev_success: u32,
72 max_order: u32,
73 hi_bits_flag: u32,
74 run_length: i32,
75 init_rl: i32,
76 size: u32,
77 glue_count: u32,
78 align_offset: u32,
79 lo_unit: NonNull<u8>,
80 hi_unit: NonNull<u8>,
81 text: NonNull<u8>,
82 units_start: NonNull<u8>,
83 index2units: [u8; 40],
84 units2index: [u8; 128],
85 free_list: [TaggedOffset; 38],
86 ns2bs_index: [u8; 256],
87 ns2index: [u8; 256],
88 exp_escape: [u8; 16],
89 dummy_see: See,
90 see: [[See; 16]; 25],
91 bin_summ: [[u16; 64]; 128],
92 memory_ptr: NonNull<u8>,
93 memory_layout: Layout,
94 rc: RC,
95 }
96
97 impl<RC> Drop for PPMd7<RC> {
98 fn drop(&mut self) {
99 unsafe {
100 dealloc(self.memory_ptr.as_ptr(), self.memory_layout);
101 }
102 }
103 }
104
105 impl<RC> MemoryAllocator for PPMd7<RC> {
106 fn base_memory_ptr(&self) -> NonNull<u8> {
107 self.memory_ptr
108 }
109
110 #[cfg(not(feature = "unstable-tagged-offsets"))]
111 fn units_start(&self) -> NonNull<u8> {
112 self.units_start
113 }
114
115 #[cfg(feature = "unstable-tagged-offsets")]
116 fn size(&self) -> u32 {
117 self.size
118 }
119 }
120
121 impl<RC> PPMd7<RC> {
122 fn construct(rc: RC, order: u32, mem_size: u32) -> Result<Self, Error> {
123 let mut units2index = [0u8; 128];
124 let mut index2units = [0u8; 40];
125
126 let mut k = 0;
127 for i in 0..PPMD_NUM_INDEXES {
128 let step: u32 = if i >= 12 { 4 } else { (i >> 2) + 1 };
129 for _ in 0..step {
130 units2index[k as usize] = i as u8;
131 k += 1;
132 }
133 index2units[i as usize] = k as u8;
134 }
135
136 let mut ns2bs_index = [0u8; 256];
137 ns2bs_index[0] = (0 << 1) as u8;
138 ns2bs_index[1] = (1 << 1) as u8;
139 ns2bs_index[2..11].fill((2 << 1) as u8);
140 ns2bs_index[11..256].fill((3 << 1) as u8);
141
142 let mut ns2index = [0u8; 256];
143 for i in 0..3 {
144 ns2index[i as usize] = i as u8;
145 }
146
147 let mut m = 3;
148 let mut k = 1;
149 for i in 3..256 {
150 ns2index[i as usize] = m as u8;
151 k -= 1;
152 if k == 0 {
153 m += 1;
154 k = m - 2;
155 }
156 }
157
158 let align_offset = (4u32.wrapping_sub(mem_size)) & 3;
159 let total_size = (align_offset + mem_size) as usize;
160
161 let memory_layout = Layout::from_size_align(total_size, align_of::<usize>())
162 .expect("Failed to create memory layout");
163
164 let allocation = unsafe {
165 assert_ne!(total_size, 0);
166 NonNull::new(alloc_zeroed(memory_layout))
167 };
168
169 let Some(memory_ptr) = allocation else {
170 return Err(Error::MemoryAllocation);
171 };
172
173 let mut ppmd = Self {
174 min_context: NonNull::dangling(),
175 max_context: NonNull::dangling(),
176 found_state: NonNull::dangling(),
177 order_fall: 0,
178 init_esc: 0,
179 prev_success: 0,
180 max_order: order,
181 hi_bits_flag: 0,
182 run_length: 0,
183 init_rl: 0,
184 size: mem_size,
185 glue_count: 0,
186 align_offset,
187 lo_unit: NonNull::dangling(),
188 hi_unit: NonNull::dangling(),
189 text: NonNull::dangling(),
190 units_start: NonNull::dangling(),
191 units2index,
192 index2units,
193 ns2bs_index,
194 ns2index,
195 exp_escape: K_EXP_ESCAPE,
196 dummy_see: See::default(),
197 see: [[See::default(); 16]; 25],
198 free_list: [TaggedOffset::null(); PPMD_NUM_INDEXES as usize],
199 bin_summ: [[0; 64]; 128],
200 memory_ptr,
201 memory_layout,
202 rc,
203 };
204
205 unsafe { ppmd.restart_model() };
206
207 Ok(ppmd)
208 }
209
210 unsafe fn offset_for_ptr<T: Pointee>(&self, ptr: NonNull<T>) -> TaggedOffset {
211 unsafe { TaggedOffset::from_ptr(self, ptr) }
212 }
213
214 unsafe fn insert_node(&mut self, node: NonNull<Node>, indx: u32) {
215 let mut node_union_ptr = node.cast::<NodeUnion>();
216 node_union_ptr.as_mut().next_ref = self.free_list[indx as usize];
217 self.free_list[indx as usize] = self.offset_for_ptr(node);
218 }
219
220 unsafe fn remove_node(&mut self, indx: u32) -> NonNull<u8> {
221 let offset = self.free_list[indx as usize];
222 let node_ptr = offset.as_ptr::<Node, _>(self);
223 self.free_list[indx as usize] = node_ptr.cast::<NodeUnion>().as_ref().next_ref;
224 node_ptr.cast()
225 }
226
227 unsafe fn split_block(&mut self, mut ptr: NonNull<u8>, old_index: u32, new_index: u32) {
228 unsafe {
229 let nu = (self.index2units[old_index as usize] as u32)
230 - (self.index2units[new_index as usize] as u32);
231 ptr = ptr.offset(self.index2units[new_index as usize] as isize * UNIT_SIZE);
232 let mut i = self.units2index[(nu as usize) - 1] as u32;
233
234 if self.index2units[i as usize] as u32 != nu {
235 i -= 1;
236 let k = self.index2units[i as usize] as u32;
237 self.insert_node(ptr.offset(k as isize * UNIT_SIZE).cast(), nu - k - 1);
238 }
239
240 self.insert_node(ptr.cast(), i);
241 }
242 }
243
244 /// We use the first u16 field of the 12-bytes as record type stamp.
245 /// State { symbol: u8, freq: u8, .. : freq != 0
246 /// Context { num_stats: u16, .. : num_stats != 0
247 /// Node { stamp: u16 : stamp == 0 for free record
248 /// : stamp == 1 for head record and guard
249 /// Last 12-bytes record in array is always containing the 12-bytes order-0 Context
250 /// record.
251 unsafe fn glue_free_blocks(&mut self) {
252 unsafe {
253 let mut n = TaggedOffset::null();
254 self.glue_count = 255;
255
256 // We set guard node at lo_unit.
257 if self.lo_unit != self.hi_unit {
258 self.lo_unit.cast::<Node>().as_mut().stamp = 1;
259 }
260
261 // Create list of free blocks. We still need one additional list walk pass before glue.
262 let mut i = 0;
263 while i < PPMD_NUM_INDEXES {
264 let nu = self.index2units[i as usize] as u16;
265 let mut next = self.free_list[i as usize];
266 self.free_list[i as usize] = TaggedOffset::null();
267 while next.is_not_null() {
268 let node_ptr = next.as_ptr::<Node, _>(self);
269 let un = node_ptr.cast::<NodeUnion>().as_mut();
270 let tmp = next;
271 next = un.next_ref;
272 un.node.stamp = EMPTY_NODE;
273 un.node.nu = nu;
274 un.node.next = n;
275 n = tmp;
276 }
277 i += 1;
278 }
279
280 let mut head = n;
281
282 // Glue and fill must walk the list in same direction.
283 self.glue_blocks(n, &mut head);
284 self.fill_list(head);
285 }
286 }
287
288 /// Glue free blocks.
289 unsafe fn glue_blocks(&mut self, mut n: TaggedOffset, head: *mut TaggedOffset) {
290 unsafe {
291 let mut prev = head;
292 while n.is_not_null() {
293 let mut node = n.as_ptr::<Node, _>(self);
294 let mut nu = node.as_ref().nu as u32;
295 n = node.as_ref().next;
296 if nu == 0 {
297 *prev = n;
298 } else {
299 prev = &raw mut node.as_mut().next;
300 loop {
301 let node2 = node.offset(nu as isize).as_mut();
302 nu += node2.nu as u32;
303 if node2.stamp != EMPTY_NODE || nu >= 0x10000 {
304 break;
305 }
306 (*node.as_ptr()).nu = nu as u16;
307 node2.nu = 0;
308 }
309 }
310 }
311 }
312 }
313
314 /// Fill lists of free blocks.
315 unsafe fn fill_list(&mut self, head: TaggedOffset) {
316 unsafe {
317 let mut n = head;
318 while n.is_not_null() {
319 let mut node = n.as_ptr::<Node, _>(self);
320 let mut nu = node.as_ref().nu as u32;
321
322 n = node.as_ref().next;
323 if nu == 0 {
324 continue;
325 }
326 while nu > 128 {
327 self.insert_node(node, PPMD_NUM_INDEXES - 1);
328 nu -= 128;
329 node = node.offset(128);
330 }
331
332 let mut index = self.units2index[(nu as usize) - 1] as u32;
333 if self.index2units[index as usize] as u32 != nu {
334 index -= 1;
335 let k = self.index2units[index as usize] as u32;
336 self.insert_node(node.offset(k as isize).cast(), nu - k - 1);
337 }
338 self.insert_node(node, index);
339 }
340 }
341 }
342
343 #[inline(never)]
344 unsafe fn alloc_units_rare(&mut self, index: u32) -> Option<NonNull<u8>> {
345 unsafe {
346 if self.glue_count == 0 {
347 self.glue_free_blocks();
348 if self.free_list[index as usize].is_not_null() {
349 return Some(self.remove_node(index));
350 }
351 }
352
353 let mut i = index;
354
355 loop {
356 i += 1;
357 if i == PPMD_NUM_INDEXES {
358 let num_bytes = self.index2units[index as usize] as u32 * UNIT_SIZE as u32;
359 let us = self.units_start;
360 self.glue_count -= 1;
361 return if us.offset_from(self.text) > num_bytes as isize {
362 self.units_start = us.offset(-(num_bytes as isize));
363 Some(self.units_start)
364 } else {
365 None
366 };
367 }
368 if self.free_list[i as usize].is_not_null() {
369 break;
370 }
371 }
372
373 let block = self.remove_node(i);
374 self.split_block(block, i, index);
375 Some(block)
376 }
377 }
378
379 unsafe fn alloc_units(&mut self, index: u32) -> Option<NonNull<u8>> {
380 unsafe {
381 if self.free_list[index as usize].is_not_null() {
382 return Some(self.remove_node(index));
383 }
384 let num_bytes = self.index2units[index as usize] as u32 * UNIT_SIZE as u32;
385 let lo = self.lo_unit;
386 if self.hi_unit.offset_from(lo) as u32 >= num_bytes {
387 self.lo_unit = lo.offset(num_bytes as isize);
388 return Some(lo);
389 }
390
391 self.alloc_units_rare(index)
392 }
393 }
394
395 #[inline(never)]
396 unsafe fn restart_model(&mut self) {
397 unsafe {
398 self.free_list = [TaggedOffset::null(); 38];
399
400 self.text = self.memory_ptr.offset(self.align_offset as isize);
401 self.hi_unit = self.text.offset(self.size as isize);
402 self.units_start = self
403 .hi_unit
404 .offset(-(self.size as isize / 8 / UNIT_SIZE * 7 * UNIT_SIZE));
405 self.lo_unit = self.units_start;
406 self.glue_count = 0;
407
408 self.order_fall = self.max_order;
409 self.init_rl = -(if self.max_order < 12 {
410 self.max_order as i32
411 } else {
412 12
413 }) - 1;
414 self.run_length = self.init_rl;
415 self.prev_success = 0;
416
417 self.hi_unit = self.hi_unit.offset(-UNIT_SIZE);
418 let mut mc = self.hi_unit.cast::<Context>();
419 let s = self.lo_unit.cast::<State>();
420
421 self.lo_unit = self.lo_unit.offset((256 / 2) * UNIT_SIZE);
422 self.min_context = mc;
423 self.max_context = mc;
424 self.found_state = s;
425
426 {
427 let mc = mc.as_mut();
428 mc.num_stats = 256;
429 mc.union2.summ_freq = (256 + 1) as u16;
430 mc.union4.stats = self.offset_for_ptr(s);
431 mc.suffix = TaggedOffset::null();
432 }
433
434 (0..256).for_each(|i| {
435 let s = s.offset(i).as_mut();
436 s.symbol = i as u8;
437 s.freq = 1;
438 s.set_successor(TaggedOffset::null());
439 });
440
441 (0..128).for_each(|i| {
442 (0..8).for_each(|k| {
443 let val = PPMD_BIN_SCALE - (K_INIT_BIN_ESC[k] as u32) / (i as u32 + 2);
444
445 (0..64).step_by(8).for_each(|m| {
446 self.bin_summ[i][k + m] = val as u16;
447 });
448 });
449 });
450
451 (0..25).for_each(|i| {
452 let summ = (5 * i as u32 + 10) << (PPMD_PERIOD_BITS - 4);
453 (0..16).for_each(|k| {
454 let s = &mut self.see[i][k];
455 s.summ = summ as u16;
456 s.shift = (PPMD_PERIOD_BITS - 4) as u8;
457 s.count = 4;
458 });
459 });
460
461 self.dummy_see.summ = 0;
462 self.dummy_see.shift = PPMD_PERIOD_BITS as u8;
463 self.dummy_see.count = 64;
464 }
465 }
466
467 /// It's called when `found_state.successor` is RAW-successor, that is the link to position
468 /// in raw text. So we create Context records and write the links to `found_state.successor`
469 /// and to identical RAW-successors in suffix contexts of `min_context`.
470 ///
471 /// The function returns:
472 ///
473 /// if (`porder_fall` == 0) then `min_context` is already at MAX order,
474 /// { return pointer to new or existing context of same MAX order }
475 /// else
476 /// { return pointer to new real context that will be (order+1) in comparison with `min_context` }
477 ///
478 /// also it can return a pointer to a real context of same order.
479 #[inline(never)]
480 unsafe fn create_successors(&mut self) -> Option<NonNull<Context>> {
481 unsafe {
482 let mut c = self.min_context;
483 let up_branch = self.found_state.as_ref().get_successor();
484 let mut num_ps = 0;
485 let mut ps: [Option<NonNull<State>>; 64] = [None; 64];
486
487 if self.order_fall != 0 {
488 let fresh = num_ps;
489 num_ps += 1;
490 ps[fresh as usize] = Some(self.found_state);
491 }
492
493 while c.as_ref().suffix.is_not_null() {
494 let mut s;
495 c = self.get_context(c.as_ref().suffix);
496
497 if c.as_ref().num_stats != 1 {
498 let sym = self.found_state.as_ref().symbol;
499 s = self.get_multi_state_stats(c);
500 while s.as_ref().symbol != sym {
501 s = s.offset(1);
502 }
503 } else {
504 s = self.get_single_state(c);
505 }
506 let successor = s.as_ref().get_successor();
507 if successor != up_branch {
508 // c is the real record Context here.
509 c = self.get_context(successor);
510 if num_ps == 0 {
511 // c is the real record MAX Order Context here,
512 // so we don't need to create any new contexts.
513 return Some(c);
514 }
515 break;
516 } else {
517 let fresh = num_ps;
518 num_ps += 1;
519 ps[fresh as usize] = Some(s);
520 }
521 }
522
523 // All created contexts will have single-symbol with new RAW-successor
524 // All new RAW-successors will point to next position in RAW text
525 // after `found_state.successor`
526 let new_sym = *up_branch.as_ptr::<u8, _>(self).as_ref();
527 let new_offset = up_branch.get_offset() + 1;
528 let up_branch = TaggedOffset::from_bytes_offset(new_offset);
529
530 let new_freq = if c.as_ref().num_stats == 1 {
531 self.get_single_state(c).as_ref().freq
532 } else {
533 let mut s = self.get_multi_state_stats(c);
534 while s.as_ref().symbol != new_sym {
535 s = s.offset(1);
536 }
537 let cf = (s.as_ref().freq as u32) - 1;
538 let s0 = (c.as_ref().union2.summ_freq as u32) - c.as_ref().num_stats as u32 - cf;
539
540 // cf - is frequency of symbol that will be successor in new context records.
541 // s0 - is commutative frequency sum of another symbols from parent context.
542 // max(new_freq) = (s.freq + 1), when (s0 == 1)
543 // We have a requirement (Context::get_one_state().freq <= 128) in bin_summ
544 // so (s.freq < 128) - is a requirement for multi-symbol contexts.
545 1 + (if 2 * cf <= s0 {
546 (5 * cf > s0) as u32
547 } else {
548 ((2 * cf + s0 - 1) / (2 * s0)) + 1
549 }) as u8
550 };
551
552 // Create a new single-symbol contexts from low order to high order in loop.
553 loop {
554 let mut c1: NonNull<Context> = if self.hi_unit != self.lo_unit {
555 self.hi_unit = self.hi_unit.offset(-UNIT_SIZE);
556 self.hi_unit.cast()
557 } else if self.free_list[0].is_not_null() {
558 self.remove_node(0).cast()
559 } else {
560 self.alloc_units_rare(0)?.cast()
561 };
562
563 c1.as_mut().num_stats = 1;
564
565 {
566 let state = self.get_single_state(c1).as_mut();
567 state.symbol = new_sym;
568 state.freq = new_freq;
569 state.set_successor(up_branch);
570 }
571
572 c1.as_mut().suffix = self.offset_for_ptr(c);
573 num_ps -= 1;
574
575 let mut successor = ps[num_ps as usize].expect("successor not set");
576 successor.as_mut().set_successor(self.offset_for_ptr(c1));
577
578 c = c1;
579 if num_ps == 0 {
580 break;
581 }
582 }
583
584 Some(c)
585 }
586 }
587
588 #[inline(never)]
589 unsafe fn update_model(&mut self) {
590 unsafe {
591 let mut c: NonNull<Context>;
592
593 let mc = self.min_context;
594
595 if self.found_state.as_ref().freq < MAX_FREQ / 4 && mc.as_ref().suffix.is_not_null() {
596 // Update freqs in suffix context
597 c = self.get_context(mc.as_ref().suffix);
598
599 if c.as_ref().num_stats == 1 {
600 let s = self.get_single_state(c).as_mut();
601 if s.freq < 32 {
602 s.freq += 1;
603 }
604 } else {
605 let mut s = self.get_multi_state_stats(c);
606 let sym = self.found_state.as_ref().symbol;
607 if s.as_ref().symbol != sym {
608 while s.as_ref().symbol != sym {
609 s = s.offset(1);
610 }
611 if s.offset(0).as_ref().freq >= s.offset(-1).as_ref().freq {
612 Self::swap_states(s);
613 s = s.offset(-1);
614 }
615 }
616 if s.as_ref().freq < MAX_FREQ - 9 {
617 s.as_mut().freq += 2;
618 c.as_mut().union2.summ_freq += 2;
619 }
620 }
621 }
622
623 if self.order_fall == 0 {
624 // MAX ORDER context
625 // (found_state.Successor) is RAW-successor.
626 match self.create_successors() {
627 None => {
628 self.restart_model();
629 return;
630 }
631 Some(mc) => {
632 self.min_context = mc;
633 self.max_context = mc;
634 }
635 }
636
637 self.found_state
638 .as_mut()
639 .set_successor(self.offset_for_ptr(self.min_context));
640 return;
641 }
642
643 // NON MAX ORDER context
644 let mut text = self.text;
645 let mut fresh = text;
646 text = text.offset(1);
647 *fresh.as_mut() = self.found_state.as_ref().symbol;
648 self.text = text;
649 if text >= self.units_start {
650 self.restart_model();
651 return;
652 }
653 let mut max_successor = self.offset_for_ptr::<u8>(text);
654
655 let mut min_successor = self.found_state.as_ref().get_successor();
656
657 if min_successor.is_null() {
658 // found_state has NULL-successor here.
659 // And only root 0-order context can contain NULL-successors.
660 // We change successor in found_state to RAW-successor,
661 // And next context will be same 0-order root Context.
662 self.found_state.as_mut().set_successor(max_successor);
663 min_successor = self.offset_for_ptr(self.min_context);
664 } else {
665 // There is a successor for found_state in min_context.
666 // So the next context will be one order higher than min_context.
667
668 if min_successor.get_offset() <= max_successor.get_offset() {
669 // min_successor is RAW-successor. So we will create real contexts records:
670 match self.create_successors() {
671 None => {
672 self.restart_model();
673 return;
674 }
675 Some(context) => {
676 min_successor = self.offset_for_ptr(context);
677 }
678 }
679 }
680
681 // min_successor now is real Context pointer that points to existing (Order+1) context.
682
683 self.order_fall -= 1;
684 if self.order_fall == 0 {
685 // If we move to max_order context, then min_successor will be common Successor for both:
686 // min_context that is (max_order - 1)
687 // max_context that is (max_order)
688 // so we don't need new RAW-successor, and we can use real min_successor
689 // as successors for both min_context and max_context.
690 max_successor = min_successor;
691
692 // if (max_context != min_context)
693 // {
694 // There was order fall from max_order, and we don't need current symbol
695 // to transfer some RAW-successors to real contexts.
696 // So we roll back pointer in raw data for one position.
697 // }
698 self.text = self
699 .text
700 .offset(-((self.max_context != self.min_context) as isize));
701 }
702 }
703
704 let mc = self.min_context;
705 c = self.max_context;
706
707 self.min_context = self.get_context(min_successor);
708 self.max_context = self.min_context;
709
710 if c == mc {
711 return;
712 }
713
714 // s0 : is pure escape freq
715 let ns = mc.as_ref().num_stats as u32;
716 let s0 = (mc.as_ref().union2.summ_freq as u32)
717 - ns
718 - ((self.found_state.as_ref().freq as u32) - 1);
719
720 while c != mc {
721 let mut sum;
722 let ns1 = c.as_ref().num_stats as u32;
723 if ns1 != 1 {
724 if ns1 & 1 == 0 {
725 // Expand for one unit
726 let old_nu = ns1 >> 1;
727 let i = self.units2index[(old_nu as usize) - 1] as u32;
728 if i != self.units2index[old_nu as usize] as u32 {
729 let Some(ptr) = self.alloc_units(i + 1) else {
730 self.restart_model();
731 return;
732 };
733
734 let old_ptr = self.get_multi_state_stats(c).cast();
735 std::ptr::copy(
736 old_ptr.cast().as_ptr(),
737 ptr.as_ptr(),
738 old_nu as usize * UNIT_SIZE as usize,
739 );
740 self.insert_node(old_ptr, i);
741 c.as_mut().union4.stats = self.offset_for_ptr(ptr.cast::<State>());
742 }
743 }
744 sum = c.as_mut().union2.summ_freq as u32;
745 // Max increase of escape_freq is 3 here.
746 // Total increase of union2.summ_freq for all symbols is less than 256 here.
747 sum += ((2 * (ns1) < ns) as u32)
748 + 2 * ((4 * (ns1) <= ns) as u32 & (sum <= (8 * (ns1))) as u32);
749 } else {
750 // Instead of 1-symbol context we create 2-symbol context.
751 let Some(s_ptr) = self.alloc_units(0) else {
752 self.restart_model();
753 return;
754 };
755 let mut s = s_ptr.cast::<State>();
756
757 let mut freq = c.as_ref().union2.state2.freq as u32;
758 s.as_mut().symbol = c.as_ref().union2.state2.symbol;
759 s.as_mut()
760 .set_successor(c.as_ref().union4.state4.get_successor());
761 c.as_mut().union4.stats = self.offset_for_ptr(s);
762 if freq < (MAX_FREQ / 4 - 1) as u32 {
763 freq <<= 1;
764 } else {
765 freq = (MAX_FREQ - 4) as u32;
766 }
767 // (max(s.freq) == 120), when we convert from 1-symbol into 2-symbol context.
768 s.as_mut().freq = freq as u8;
769 // max(init_esc = K_EXP_ESCAPE[*]) is 25. So the max(escape_freq) is 26 here.
770 sum = freq + self.init_esc + ((ns > 3) as u32);
771 }
772
773 let mut s = self.get_multi_state_stats(c).offset(ns1 as isize);
774 let mut cf = 2 * (sum + 6) * self.found_state.as_ref().freq as u32;
775 let sf = s0 + sum;
776 s.as_mut().symbol = self.found_state.as_ref().symbol;
777 c.as_mut().num_stats = (ns1 + 1) as u16;
778
779 s.as_mut().set_successor(max_successor);
780 if cf < 6 * sf {
781 cf = 1 + ((cf > sf) as u32) + ((cf >= 4 * sf) as u32);
782 sum += 3;
783 // It can add (0, 1, 2) to escape_freq
784 } else {
785 cf = 4
786 + ((cf >= 9 * sf) as u32)
787 + ((cf >= 12 * sf) as u32)
788 + ((cf >= 15 * sf) as u32);
789 sum += cf;
790 }
791
792 c.as_mut().union2.summ_freq = sum as u16;
793 s.as_mut().freq = cf as u8;
794
795 c = self.get_context(c.as_ref().suffix);
796 }
797 }
798 }
799
800 unsafe fn swap_states(s: NonNull<State>) {
801 let s_ptr = s.as_ptr();
802 std::ptr::swap(s_ptr, s_ptr.offset(-1));
803 }
804
805 #[inline(never)]
806 unsafe fn rescale(&mut self) {
807 unsafe {
808 let stats = self.get_multi_state_stats(self.min_context);
809 let mut s = self.found_state;
810
811 // Sort the list by freq
812 if s != stats {
813 let tmp = *s.as_ref();
814 while s != stats {
815 *s.offset(0).as_mut() = *s.offset(-1).as_ref();
816 s = s.offset(-1);
817 }
818 *s.as_mut() = tmp;
819 }
820
821 let mut sum_freq = s.as_ref().freq as u32;
822 let mut esc_freq = (self.min_context.as_ref().union2.summ_freq as u32) - sum_freq;
823
824 // if (p.order_fall == 0), adder = 0 : it's allowed to remove symbol from MAX order context
825 // if (p.order_fall != 0), adder = 1 : it's NOT allowed to remove symbol from NON-MAX order context
826
827 let adder = (self.order_fall != 0) as u32;
828
829 sum_freq = (sum_freq + 4 + adder) >> 1;
830 let mut i = (self.min_context.as_ref().num_stats as u32) - 1;
831 s.as_mut().freq = sum_freq as u8;
832
833 for _ in 0..i {
834 s = s.offset(1);
835 let mut freq = s.as_ref().freq as u32;
836 esc_freq -= freq;
837 freq = (freq + adder) >> 1;
838 sum_freq += freq;
839 s.as_mut().freq = freq as u8;
840 if freq > s.offset(-1).as_ref().freq as u32 {
841 let tmp = *s.as_mut();
842 let mut s1 = s;
843 loop {
844 *s1.offset(0).as_mut() = *s1.offset(-1).as_ref();
845 s1 = s1.offset(-1);
846 if !(s1 != stats && freq > s1.offset(-1).as_ref().freq as u32) {
847 break;
848 }
849 }
850 *s1.as_mut() = tmp;
851 }
852 }
853
854 if s.as_ref().freq as i32 == 0 {
855 // Remove all items with freq == 0
856
857 i = 0;
858 while s.as_ref().freq == 0 {
859 i += 1;
860 s = s.offset(-1);
861 }
862
863 // We increase (esc_freq) for the number of removed symbols.
864 // So we will have (0.5) increase for escape_freq in average per
865 // removed symbol after escape_freq halving
866 esc_freq += i;
867 let mut mc = self.min_context;
868 let num_stats = mc.as_ref().num_stats as u32;
869 let num_stats_new = num_stats.wrapping_sub(i);
870 mc.as_mut().num_stats = num_stats_new as u16;
871 let n0 = (num_stats + 1) >> 1;
872
873 if num_stats_new == 1 {
874 // Create Single-Symbol context
875 let mut freq = stats.as_ref().freq as u32;
876 loop {
877 esc_freq >>= 1;
878 freq = (freq + 1) >> 1;
879 if esc_freq <= 1 {
880 break;
881 }
882 }
883
884 s = self.get_single_state(mc);
885 *s.as_mut() = *stats.as_ref();
886 s.as_mut().freq = freq as u8; // (freq <= 260 / 4)
887 self.found_state = s;
888 self.insert_node(stats.cast(), self.units2index[(n0 as usize) - 1] as u32);
889 return;
890 }
891
892 let n1 = (num_stats_new + 1) >> 1;
893 if n0 != n1 {
894 let i0 = self.units2index[(n0 as usize) - 1] as u32;
895 let i1 = self.units2index[(n1 as usize) - 1] as u32;
896 if i0 != i1 {
897 if self.free_list[i1 as usize].is_not_null() {
898 let ptr = self.remove_node(i1);
899 self.min_context.as_mut().union4.stats =
900 self.offset_for_ptr(ptr.cast::<State>());
901 std::ptr::copy(
902 stats.cast().as_ptr(),
903 ptr.as_ptr(),
904 n1 as usize * UNIT_SIZE as usize,
905 );
906 self.insert_node(stats.cast(), i0);
907 } else {
908 self.split_block(stats.cast(), i0, i1);
909 }
910 }
911 }
912 }
913
914 // escape_freq halving here.
915 self.min_context.as_mut().union2.summ_freq =
916 (sum_freq + esc_freq - (esc_freq >> 1)) as u16;
917 self.found_state = self.get_multi_state_stats(self.min_context);
918 }
919 }
920
921 unsafe fn make_esc_freq(&mut self, num_masked: u32, esc_freq: &mut u32) -> SeeSource {
922 unsafe {
923 let num_stats = self.min_context.as_ref().num_stats as u32;
924
925 if num_stats != 256 {
926 let (base_context_idx, see_table_hash) =
927 self.calculate_see_table_hash(num_masked, num_stats);
928
929 let see = &mut self.see[base_context_idx][see_table_hash];
930
931 // If (see.summ) field is larger than 16-bit, we need only low 16 bits of summ.
932 let summ = see.summ as u32;
933 let r = summ >> see.shift as i32;
934 see.summ = (summ - r) as u16;
935 *esc_freq = r + (r == 0) as u32;
936
937 SeeSource::Table(base_context_idx, see_table_hash)
938 } else {
939 *esc_freq = 1;
940 SeeSource::Dummy
941 }
942 }
943 }
944
945 fn get_see(&mut self, see_source: SeeSource) -> &mut See {
946 match see_source {
947 SeeSource::Dummy => &mut self.dummy_see,
948 SeeSource::Table(i, k) => &mut self.see[i][k],
949 }
950 }
951
952 unsafe fn calculate_see_table_hash(
953 &mut self,
954 num_masked: u32,
955 num_stats: u32,
956 ) -> (usize, usize) {
957 unsafe {
958 let non_masked = num_stats - num_masked;
959 let base_context_idx = self.ns2index[(non_masked as usize) - 1] as usize;
960
961 let mc = self.min_context.as_ref();
962 let suffix_context = self.get_context(mc.suffix);
963 let suffix_num_stats = suffix_context.as_ref().num_stats as u32;
964 let summ_freq = mc.union2.summ_freq as u32;
965
966 let context_hierarchy_hash = (non_masked < (suffix_num_stats - num_stats)) as usize;
967 let freq_distribution_hash = 2 * (summ_freq < (11 * num_stats)) as usize;
968 let symbol_masking_ratio_hash = 4 * (num_masked > non_masked) as usize;
969 let symbol_characteristics_hash = self.hi_bits_flag as usize;
970
971 let see_table_hash = context_hierarchy_hash
972 + freq_distribution_hash
973 + symbol_masking_ratio_hash
974 + symbol_characteristics_hash;
975
976 (base_context_idx, see_table_hash)
977 }
978 }
979
980 unsafe fn next_context(&mut self) {
981 unsafe {
982 let successor = self.found_state.as_ref().get_successor();
983 if self.order_fall == 0 && successor.is_real_context(self) {
984 let c = self.get_context(successor);
985 self.min_context = c;
986 self.max_context = self.min_context;
987 } else {
988 self.update_model();
989 };
990 }
991 }
992
993 unsafe fn update1(&mut self) {
994 unsafe {
995 let mut s = self.found_state;
996 let freq = s.as_ref().freq as u32 + 4;
997 self.min_context.as_mut().union2.summ_freq += 4;
998 s.as_mut().freq = freq as u8;
999 if freq > s.offset(-1).as_ref().freq as u32 {
1000 Self::swap_states(s);
1001 s = s.offset(-1);
1002 self.found_state = s;
1003 if freq > MAX_FREQ as u32 {
1004 self.rescale();
1005 }
1006 }
1007 self.next_context();
1008 }
1009 }
1010
1011 unsafe fn update1_0(&mut self) {
1012 unsafe {
1013 let s = self.found_state.as_mut();
1014 let mc = self.min_context.as_mut();
1015 let mut freq = s.freq as u32;
1016 let summ_freq = mc.union2.summ_freq as u32;
1017 self.prev_success = ((2 * freq) > summ_freq) as u32;
1018 self.run_length += self.prev_success as i32;
1019 mc.union2.summ_freq = (summ_freq + 4) as u16;
1020 freq += 4;
1021 s.freq = freq as u8;
1022 if freq > MAX_FREQ as u32 {
1023 self.rescale();
1024 }
1025 self.next_context();
1026 }
1027 }
1028
1029 unsafe fn update2(&mut self) {
1030 unsafe {
1031 let s = self.found_state.as_mut();
1032 let freq = s.freq as u32 + 4;
1033 self.run_length = self.init_rl;
1034 self.min_context.as_mut().union2.summ_freq += 4;
1035 s.freq = freq as u8;
1036 if freq > MAX_FREQ as u32 {
1037 self.rescale();
1038 }
1039 self.update_model();
1040 }
1041 }
1042
1043 unsafe fn update_bin(&mut self, mut s: NonNull<State>) {
1044 unsafe {
1045 let freq = s.as_ref().freq as u32;
1046 self.found_state = s;
1047 self.prev_success = 1;
1048 self.run_length += 1;
1049 s.as_mut().freq += ((freq < 128) as u32) as u8;
1050 self.next_context();
1051 }
1052 }
1053
1054 unsafe fn mask_symbols(char_mask: &mut [u8; 256], s: NonNull<State>, mut s2: NonNull<State>) {
1055 unsafe {
1056 char_mask[s.as_ref().symbol as usize] = 0;
1057 while s2 < s {
1058 let sym0 = s2.offset(0).as_ref().symbol as u32;
1059 let sym1 = s2.offset(1).as_ref().symbol as u32;
1060 s2 = s2.offset(2);
1061 char_mask[sym0 as usize] = 0;
1062 char_mask[sym1 as usize] = 0;
1063 }
1064 }
1065 }
1066
1067 const fn hi_bits_flag3(symbol: u32) -> u32 {
1068 (symbol + 0xC0) >> (8 - 3) & (1 << 3)
1069 }
1070
1071 const fn hi_bits_flag4(symbol: u32) -> u32 {
1072 (symbol + 0xC0) >> (8 - 4) & (1 << 4)
1073 }
1074
1075 unsafe fn get_bin_summ(&mut self) -> &mut u16 {
1076 unsafe {
1077 let state = self.get_single_state(self.min_context);
1078
1079 let hi_bits_flag3 = Self::hi_bits_flag3(self.found_state.as_ref().symbol as u32);
1080 let symbol = state.as_ref().symbol as u32;
1081 let hi_bits_flag4 = Self::hi_bits_flag4(symbol);
1082
1083 self.hi_bits_flag = hi_bits_flag3;
1084
1085 let freq_bin_idx = state.as_ref().freq as usize;
1086
1087 let num_stats = self
1088 .get_context(self.min_context.as_ref().suffix)
1089 .as_ref()
1090 .num_stats as usize;
1091
1092 let context_idx = (self.prev_success
1093 + ((self.run_length as u32 >> 26) & 0x20)
1094 + self.ns2bs_index[num_stats - 1] as u32
1095 + hi_bits_flag4
1096 + hi_bits_flag3) as usize;
1097
1098 &mut self.bin_summ[freq_bin_idx - 1][context_idx]
1099 }
1100 }
1101
1102 #[inline(always)]
1103 unsafe fn get_context(&mut self, suffix: TaggedOffset) -> NonNull<Context> {
1104 unsafe { suffix.as_ptr(self) }
1105 }
1106
1107 #[inline(always)]
1108 fn get_single_state(&mut self, context: NonNull<Context>) -> NonNull<State> {
1109 let context_ptr = context.as_ptr();
1110 unsafe {
1111 // Safety: We know that context is not null, so a field address from it can't be null.
1112 let single_state = &raw mut (*context_ptr).union2;
1113 NonNull::new_unchecked(single_state).cast()
1114 }
1115 }
1116
1117 #[inline(always)]
1118 unsafe fn get_multi_state_stats(&mut self, mut context: NonNull<Context>) -> NonNull<State> {
1119 unsafe { context.as_mut().union4.stats.as_ptr(self) }
1120 }
1121 }
1122
1123 impl<R: Read> PPMd7<RangeDecoder<R>> {
1124 pub(crate) fn new_decoder(
1125 reader: R,
1126 order: u32,
1127 mem_size: u32,
1128 ) -> Result<PPMd7<RangeDecoder<R>>, Error> {
1129 let range_decoder = RangeDecoder::new(reader)?;
1130 Self::construct(range_decoder, order, mem_size)
1131 }
1132
1133 pub(crate) fn into_inner(self) -> R {
1134 let manual_drop_self = ManuallyDrop::new(self);
1135 unsafe {
1136 dealloc(
1137 manual_drop_self.memory_ptr.as_ptr(),
1138 manual_drop_self.memory_layout,
1139 );
1140 }
1141 let rc = unsafe { std::ptr::read(&manual_drop_self.rc) };
1142 let RangeDecoder { reader, .. } = rc;
1143 reader
1144 }
1145
1146 pub(crate) fn range_decoder_code(&self) -> u32 {
1147 self.rc.code
1148 }
1149 }
1150
1151 impl<W: Write> PPMd7<RangeEncoder<W>> {
1152 pub(crate) fn new_encoder(
1153 writer: W,
1154 order: u32,
1155 mem_size: u32,
1156 ) -> Result<PPMd7<RangeEncoder<W>>, Error> {
1157 let range_encoder = RangeEncoder::new(writer);
1158 Self::construct(range_encoder, order, mem_size)
1159 }
1160
1161 pub(crate) fn into_inner(self) -> W {
1162 let manual_drop_self = ManuallyDrop::new(self);
1163 unsafe {
1164 dealloc(
1165 manual_drop_self.memory_ptr.as_ptr(),
1166 manual_drop_self.memory_layout,
1167 );
1168 }
1169 let rc = unsafe { std::ptr::read(&manual_drop_self.rc) };
1170 let RangeEncoder { writer, .. } = rc;
1171 writer
1172 }
1173
1174 pub(crate) fn flush_range_encoder(&mut self) -> Result<(), std::io::Error> {
1175 self.rc.flush()
1176 }
1177 }