DEADSOFTWARE

hopefully no more windows
[d2df-editor.git] / src / lib / vampimg / JpegLib / imjchuff.pas
1 unit imjchuff;
3 { This file contains Huffman entropy encoding routines.
5 Much of the complexity here has to do with supporting output suspension.
6 If the data destination module demands suspension, we want to be able to
7 back up to the start of the current MCU. To do this, we copy state
8 variables into local working storage, and update them back to the
9 permanent JPEG objects only upon successful completion of an MCU. }
11 { Original: jchuff.c; Copyright (C) 1991-1997, Thomas G. Lane. }
13 interface
15 {$I imjconfig.inc}
17 uses
18 imjmorecfg, { longptr definition missing }
19 imjpeglib,
20 imjdeferr,
21 imjerror,
22 imjutils,
23 imjinclude,
24 imjcomapi;
26 { The legal range of a DCT coefficient is
27 -1024 .. +1023 for 8-bit data;
28 -16384 .. +16383 for 12-bit data.
29 Hence the magnitude should always fit in 10 or 14 bits respectively. }
32 {$ifdef BITS_IN_JSAMPLE_IS_8}
33 const
34 MAX_COEF_BITS = 10;
35 {$else}
36 const
37 MAX_COEF_BITS = 14;
38 {$endif}
40 { Derived data constructed for each Huffman table }
41 { Declarations shared with jcphuff.c }
42 type
43 c_derived_tbl_ptr = ^c_derived_tbl;
44 c_derived_tbl = record
45 ehufco : array[0..256-1] of uInt; { code for each symbol }
46 ehufsi : array[0..256-1] of byte; { length of code for each symbol }
47 { If no code has been allocated for a symbol S, ehufsi[S] contains 0 }
48 end;
49 { for JCHUFF und JCPHUFF }
50 type
51 TLongTable = array[0..256] of long;
52 TLongTablePtr = ^TLongTable;
54 { Compute the derived values for a Huffman table.
55 Note this is also used by jcphuff.c. }
57 {GLOBAL}
58 procedure jpeg_make_c_derived_tbl (cinfo : j_compress_ptr;
59 isDC : boolean;
60 tblno : int;
61 var pdtbl : c_derived_tbl_ptr);
63 { Generate the optimal coding for the given counts, fill htbl.
64 Note this is also used by jcphuff.c. }
66 {GLOBAL}
67 procedure jpeg_gen_optimal_table (cinfo : j_compress_ptr;
68 htbl : JHUFF_TBL_PTR;
69 var freq : TLongTable); { Nomssi }
71 { Module initialization routine for Huffman entropy encoding. }
73 {GLOBAL}
74 procedure jinit_huff_encoder (cinfo : j_compress_ptr);
76 implementation
78 { Expanded entropy encoder object for Huffman encoding.
80 The savable_state subrecord contains fields that change within an MCU,
81 but must not be updated permanently until we complete the MCU. }
83 type
84 savable_state = record
85 put_buffer : INT32; { current bit-accumulation buffer }
86 put_bits : int; { # of bits now in it }
87 last_dc_val : array[0..MAX_COMPS_IN_SCAN-1] of int;
88 { last DC coef for each component }
89 end;
92 type
93 huff_entropy_ptr = ^huff_entropy_encoder;
94 huff_entropy_encoder = record
95 pub : jpeg_entropy_encoder; { public fields }
97 saved : savable_state; { Bit buffer & DC state at start of MCU }
99 { These fields are NOT loaded into local working state. }
100 restarts_to_go : uInt; { MCUs left in this restart interval }
101 next_restart_num : int; { next restart number to write (0-7) }
103 { Pointers to derived tables (these workspaces have image lifespan) }
104 dc_derived_tbls : array[0..NUM_HUFF_TBLS-1] of c_derived_tbl_ptr;
105 ac_derived_tbls : array[0..NUM_HUFF_TBLS-1] of c_derived_tbl_ptr;
107 {$ifdef ENTROPY_OPT_SUPPORTED} { Statistics tables for optimization }
108 dc_count_ptrs : array[0..NUM_HUFF_TBLS-1] of TLongTablePtr;
109 ac_count_ptrs : array[0..NUM_HUFF_TBLS-1] of TLongTablePtr;
110 {$endif}
111 end;
115 { Working state while writing an MCU.
116 This struct contains all the fields that are needed by subroutines. }
118 type
119 working_state = record
120 next_output_byte : JOCTETptr; { => next byte to write in buffer }
121 free_in_buffer : size_t; { # of byte spaces remaining in buffer }
122 cur : savable_state; { Current bit buffer & DC state }
123 cinfo : j_compress_ptr; { dump_buffer needs access to this }
124 end;
127 { Forward declarations }
128 {METHODDEF}
129 function encode_mcu_huff (cinfo : j_compress_ptr;
130 const MCU_data : array of JBLOCKROW) : boolean;
131 forward;
132 {METHODDEF}
133 procedure finish_pass_huff (cinfo : j_compress_ptr); forward;
134 {$ifdef ENTROPY_OPT_SUPPORTED}
135 {METHODDEF}
136 function encode_mcu_gather (cinfo : j_compress_ptr;
137 const MCU_data: array of JBLOCKROW) : boolean;
138 forward;
140 {METHODDEF}
141 procedure finish_pass_gather (cinfo : j_compress_ptr); forward;
142 {$endif}
145 { Initialize for a Huffman-compressed scan.
146 If gather_statistics is TRUE, we do not output anything during the scan,
147 just count the Huffman symbols used and generate Huffman code tables. }
149 {METHODDEF}
150 procedure start_pass_huff (cinfo : j_compress_ptr;
151 gather_statistics : boolean);
152 var
153 entropy : huff_entropy_ptr;
154 ci, dctbl, actbl : int;
155 compptr : jpeg_component_info_ptr;
156 begin
157 entropy := huff_entropy_ptr (cinfo^.entropy);
159 if (gather_statistics) then
160 begin
161 {$ifdef ENTROPY_OPT_SUPPORTED}
162 entropy^.pub.encode_mcu := encode_mcu_gather;
163 entropy^.pub.finish_pass := finish_pass_gather;
164 {$else}
165 ERREXIT(j_common_ptr(cinfo), JERR_NOT_COMPILED);
166 {$endif}
167 end
168 else
169 begin
170 entropy^.pub.encode_mcu := encode_mcu_huff;
171 entropy^.pub.finish_pass := finish_pass_huff;
172 end;
174 for ci := 0 to pred(cinfo^.comps_in_scan) do
175 begin
176 compptr := cinfo^.cur_comp_info[ci];
177 dctbl := compptr^.dc_tbl_no;
178 actbl := compptr^.ac_tbl_no;
179 if (gather_statistics) then
180 begin
181 {$ifdef ENTROPY_OPT_SUPPORTED}
182 { Check for invalid table indexes }
183 { (make_c_derived_tbl does this in the other path) }
184 if (dctbl < 0) or (dctbl >= NUM_HUFF_TBLS) then
185 ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, dctbl);
186 if (actbl < 0) or (actbl >= NUM_HUFF_TBLS) then
187 ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, actbl);
188 { Allocate and zero the statistics tables }
189 { Note that jpeg_gen_optimal_table expects 257 entries in each table! }
190 if (entropy^.dc_count_ptrs[dctbl] = NIL) then
191 entropy^.dc_count_ptrs[dctbl] := TLongTablePtr(
192 cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
193 257 * SIZEOF(long)) );
194 MEMZERO(entropy^.dc_count_ptrs[dctbl], 257 * SIZEOF(long));
195 if (entropy^.ac_count_ptrs[actbl] = NIL) then
196 entropy^.ac_count_ptrs[actbl] := TLongTablePtr(
197 cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
198 257 * SIZEOF(long)) );
199 MEMZERO(entropy^.ac_count_ptrs[actbl], 257 * SIZEOF(long));
200 {$endif}
201 end
202 else
203 begin
204 { Compute derived values for Huffman tables }
205 { We may do this more than once for a table, but it's not expensive }
206 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
207 entropy^.dc_derived_tbls[dctbl]);
208 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
209 entropy^.ac_derived_tbls[actbl]);
210 end;
211 { Initialize DC predictions to 0 }
212 entropy^.saved.last_dc_val[ci] := 0;
213 end;
215 { Initialize bit buffer to empty }
216 entropy^.saved.put_buffer := 0;
217 entropy^.saved.put_bits := 0;
219 { Initialize restart stuff }
220 entropy^.restarts_to_go := cinfo^.restart_interval;
221 entropy^.next_restart_num := 0;
222 end;
225 { Compute the derived values for a Huffman table.
226 This routine also performs some validation checks on the table.
228 Note this is also used by jcphuff.c. }
230 {GLOBAL}
231 procedure jpeg_make_c_derived_tbl (cinfo : j_compress_ptr;
232 isDC : boolean;
233 tblno : int;
234 var pdtbl : c_derived_tbl_ptr);
235 var
236 htbl : JHUFF_TBL_PTR;
237 dtbl : c_derived_tbl_ptr;
238 p, i, l, lastp, si, maxsymbol : int;
239 huffsize : array[0..257-1] of byte;
240 huffcode : array[0..257-1] of uInt;
241 code : uInt;
242 begin
243 { Note that huffsize[] and huffcode[] are filled in code-length order,
244 paralleling the order of the symbols themselves in htbl->huffval[]. }
246 { Find the input Huffman table }
247 if (tblno < 0) or (tblno >= NUM_HUFF_TBLS) then
248 ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, tblno);
249 if isDC then
250 htbl := cinfo^.dc_huff_tbl_ptrs[tblno]
251 else
252 htbl := cinfo^.ac_huff_tbl_ptrs[tblno];
253 if (htbl = NIL) then
254 ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, tblno);
256 { Allocate a workspace if we haven't already done so. }
257 if (pdtbl = NIL) then
258 pdtbl := c_derived_tbl_ptr(
259 cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
260 SIZEOF(c_derived_tbl)) );
261 dtbl := pdtbl;
263 { Figure C.1: make table of Huffman code length for each symbol }
265 p := 0;
266 for l := 1 to 16 do
267 begin
268 i := int(htbl^.bits[l]);
269 if (i < 0) and (p + i > 256) then { protect against table overrun }
270 ERREXIT(j_common_ptr(cinfo), JERR_BAD_HUFF_TABLE);
271 while (i > 0) do
272 begin
273 huffsize[p] := byte(l);
274 Inc(p);
275 Dec(i);
276 end;
277 end;
278 huffsize[p] := 0;
279 lastp := p;
281 { Figure C.2: generate the codes themselves }
282 { We also validate that the counts represent a legal Huffman code tree. }
284 code := 0;
285 si := huffsize[0];
286 p := 0;
287 while (huffsize[p] <> 0) do
288 begin
289 while (( int(huffsize[p]) ) = si) do
290 begin
291 huffcode[p] := code;
292 Inc(p);
293 Inc(code);
294 end;
295 { code is now 1 more than the last code used for codelength si; but
296 it must still fit in si bits, since no code is allowed to be all ones. }
298 if (INT32(code) >= (INT32(1) shl si)) then
299 ERREXIT(j_common_ptr(cinfo), JERR_BAD_HUFF_TABLE);
300 code := code shl 1;
301 Inc(si);
302 end;
304 { Figure C.3: generate encoding tables }
305 { These are code and size indexed by symbol value }
307 { Set all codeless symbols to have code length 0;
308 this lets us detect duplicate VAL entries here, and later
309 allows emit_bits to detect any attempt to emit such symbols. }
311 MEMZERO(@dtbl^.ehufsi, SIZEOF(dtbl^.ehufsi));
313 { This is also a convenient place to check for out-of-range
314 and duplicated VAL entries. We allow 0..255 for AC symbols
315 but only 0..15 for DC. (We could constrain them further
316 based on data depth and mode, but this seems enough.) }
318 if isDC then
319 maxsymbol := 15
320 else
321 maxsymbol := 255;
323 for p := 0 to pred(lastp) do
324 begin
325 i := htbl^.huffval[p];
326 if (i < 0) or (i > maxsymbol) or (dtbl^.ehufsi[i] <> 0) then
327 ERREXIT(j_common_ptr(cinfo), JERR_BAD_HUFF_TABLE);
328 dtbl^.ehufco[i] := huffcode[p];
329 dtbl^.ehufsi[i] := huffsize[p];
330 end;
331 end;
334 { Outputting bytes to the file }
337 {LOCAL}
338 function dump_buffer (var state : working_state) : boolean;
339 { Empty the output buffer; return TRUE if successful, FALSE if must suspend }
340 var
341 dest : jpeg_destination_mgr_ptr;
342 begin
343 dest := state.cinfo^.dest;
345 if (not dest^.empty_output_buffer (state.cinfo)) then
346 begin
347 dump_buffer := FALSE;
348 exit;
349 end;
350 { After a successful buffer dump, must reset buffer pointers }
351 state.next_output_byte := dest^.next_output_byte;
352 state.free_in_buffer := dest^.free_in_buffer;
353 dump_buffer := TRUE;
354 end;
357 { Outputting bits to the file }
359 { Only the right 24 bits of put_buffer are used; the valid bits are
360 left-justified in this part. At most 16 bits can be passed to emit_bits
361 in one call, and we never retain more than 7 bits in put_buffer
362 between calls, so 24 bits are sufficient. }
365 {LOCAL}
366 function emit_bits (var state : working_state;
367 code : uInt;
368 size : int) : boolean; {INLINE}
369 { Emit some bits; return TRUE if successful, FALSE if must suspend }
370 var
371 { This routine is heavily used, so it's worth coding tightly. }
372 {register} put_buffer : INT32;
373 {register} put_bits : int;
374 var
375 c : int;
376 begin
377 put_buffer := INT32 (code);
378 put_bits := state.cur.put_bits;
380 { if size is 0, caller used an invalid Huffman table entry }
381 if (size = 0) then
382 ERREXIT(j_common_ptr(state.cinfo), JERR_HUFF_MISSING_CODE);
384 put_buffer := put_buffer and pred(INT32(1) shl size);
385 { mask off any extra bits in code }
387 Inc(put_bits, size); { new number of bits in buffer }
389 put_buffer := put_buffer shl (24 - put_bits);
390 { align incoming bits }
391 put_buffer := put_buffer or state.cur.put_buffer;
392 { and merge with old buffer contents }
393 while (put_bits >= 8) do
394 begin
395 c := int ((put_buffer shr 16) and $FF);
397 {emit_byte(state, c, return FALSE);}
398 { Emit a byte, return FALSE if must suspend. }
399 state.next_output_byte^ := JOCTET (c);
400 Inc(state.next_output_byte);
401 Dec(state.free_in_buffer);
402 if (state.free_in_buffer = 0) then
403 if not dump_buffer(state) then
404 begin
405 emit_bits := FALSE;
406 exit;
407 end;
409 if (c = $FF) then { need to stuff a zero byte? }
410 begin
411 {emit_byte(state, 0, return FALSE);}
412 state.next_output_byte^ := JOCTET (0);
413 Inc(state.next_output_byte);
414 Dec(state.free_in_buffer);
415 if (state.free_in_buffer = 0) then
416 if not dump_buffer(state) then
417 begin
418 emit_bits := FALSE;
419 exit;
420 end;
422 end;
423 put_buffer := put_buffer shl 8;
424 Dec(put_bits, 8);
425 end;
427 state.cur.put_buffer := put_buffer; { update state variables }
428 state.cur.put_bits := put_bits;
430 emit_bits := TRUE;
431 end;
434 {LOCAL}
435 function flush_bits (var state : working_state) : boolean;
436 begin
437 if (not emit_bits(state, $7F, 7)) then { fill any partial byte with ones }
438 begin
439 flush_bits := FALSE;
440 exit;
441 end;
442 state.cur.put_buffer := 0; { and reset bit-buffer to empty }
443 state.cur.put_bits := 0;
444 flush_bits := TRUE;
445 end;
448 { Encode a single block's worth of coefficients }
450 {LOCAL}
451 function encode_one_block (var state : working_state;
452 const block : JBLOCK;
453 last_dc_val : int;
454 dctbl : c_derived_tbl_ptr;
455 actbl : c_derived_tbl_ptr) : boolean;
456 var
457 {register} temp, temp2 : int;
458 {register} nbits : int;
459 {register} k, r, i : int;
460 begin
461 { Encode the DC coefficient difference per section F.1.2.1 }
463 temp2 := block[0] - last_dc_val;
464 temp := temp2;
466 if (temp < 0) then
467 begin
468 temp := -temp; { temp is abs value of input }
469 { For a negative input, want temp2 := bitwise complement of abs(input) }
470 { This code assumes we are on a two's complement machine }
471 Dec(temp2);
472 end;
474 { Find the number of bits needed for the magnitude of the coefficient }
475 nbits := 0;
476 while (temp <> 0) do
477 begin
478 Inc(nbits);
479 temp := temp shr 1;
480 end;
482 { Check for out-of-range coefficient values.
483 Since we're encoding a difference, the range limit is twice as much. }
485 if (nbits > MAX_COEF_BITS+1) then
486 ERREXIT(j_common_ptr(state.cinfo), JERR_BAD_DCT_COEF);
488 { Emit the Huffman-coded symbol for the number of bits }
489 if not emit_bits(state, dctbl^.ehufco[nbits], dctbl^.ehufsi[nbits]) then
490 begin
491 encode_one_block := FALSE;
492 exit;
493 end;
495 { Emit that number of bits of the value, if positive, }
496 { or the complement of its magnitude, if negative. }
497 if (nbits <> 0) then { emit_bits rejects calls with size 0 }
498 if not emit_bits(state, uInt(temp2), nbits) then
499 begin
500 encode_one_block := FALSE;
501 exit;
502 end;
504 { Encode the AC coefficients per section F.1.2.2 }
506 r := 0; { r := run length of zeros }
508 for k := 1 to pred(DCTSIZE2) do
509 begin
510 temp := block[jpeg_natural_order[k]];
511 if (temp = 0) then
512 begin
513 Inc(r);
514 end
515 else
516 begin
517 { if run length > 15, must emit special run-length-16 codes ($F0) }
518 while (r > 15) do
519 begin
520 if not emit_bits(state, actbl^.ehufco[$F0], actbl^.ehufsi[$F0]) then
521 begin
522 encode_one_block := FALSE;
523 exit;
524 end;
525 Dec(r, 16);
526 end;
528 temp2 := temp;
529 if (temp < 0) then
530 begin
531 temp := -temp; { temp is abs value of input }
532 { This code assumes we are on a two's complement machine }
533 Dec(temp2);
534 end;
536 { Find the number of bits needed for the magnitude of the coefficient }
537 nbits := 0; { there must be at least one 1 bit }
538 repeat
539 Inc(nbits);
540 temp := temp shr 1;
541 until (temp = 0);
543 { Check for out-of-range coefficient values }
544 if (nbits > MAX_COEF_BITS) then
545 ERREXIT(j_common_ptr(state.cinfo), JERR_BAD_DCT_COEF);
547 { Emit Huffman symbol for run length / number of bits }
548 i := (r shl 4) + nbits;
549 if not emit_bits(state, actbl^.ehufco[i], actbl^.ehufsi[i]) then
550 begin
551 encode_one_block := FALSE;
552 exit;
553 end;
555 { Emit that number of bits of the value, if positive, }
556 { or the complement of its magnitude, if negative. }
557 if not emit_bits(state, uInt(temp2), nbits) then
558 begin
559 encode_one_block := FALSE;
560 exit;
561 end;
563 r := 0;
564 end;
565 end;
567 { If the last coef(s) were zero, emit an end-of-block code }
568 if (r > 0) then
569 if not emit_bits(state, actbl^.ehufco[0], actbl^.ehufsi[0]) then
570 begin
571 encode_one_block := FALSE;
572 exit;
573 end;
575 encode_one_block := TRUE;
576 end;
579 { Emit a restart marker & resynchronize predictions. }
581 {LOCAL}
582 function emit_restart (var state : working_state;
583 restart_num : int) : boolean;
584 var
585 ci : int;
586 begin
587 if (not flush_bits(state)) then
588 begin
589 emit_restart := FALSE;
590 exit;
591 end;
593 {emit_byte(state, $FF, return FALSE);}
594 { Emit a byte, return FALSE if must suspend. }
595 state.next_output_byte^ := JOCTET ($FF);
596 Inc(state.next_output_byte);
597 Dec(state.free_in_buffer);
598 if (state.free_in_buffer = 0) then
599 if not dump_buffer(state) then
600 begin
601 emit_restart := FALSE;
602 exit;
603 end;
605 {emit_byte(state, JPEG_RST0 + restart_num, return FALSE);}
606 { Emit a byte, return FALSE if must suspend. }
607 state.next_output_byte^ := JOCTET (JPEG_RST0 + restart_num);
608 Inc(state.next_output_byte);
609 Dec(state.free_in_buffer);
610 if (state.free_in_buffer = 0) then
611 if not dump_buffer(state) then
612 begin
613 emit_restart := FALSE;
614 exit;
615 end;
617 { Re-initialize DC predictions to 0 }
618 for ci := 0 to pred(state.cinfo^.comps_in_scan) do
619 state.cur.last_dc_val[ci] := 0;
621 { The restart counter is not updated until we successfully write the MCU. }
623 emit_restart := TRUE;
624 end;
627 { Encode and output one MCU's worth of Huffman-compressed coefficients. }
629 {METHODDEF}
630 function encode_mcu_huff (cinfo : j_compress_ptr;
631 const MCU_data: array of JBLOCKROW) : boolean;
632 var
633 entropy : huff_entropy_ptr;
634 state : working_state;
635 blkn, ci : int;
636 compptr : jpeg_component_info_ptr;
637 begin
638 entropy := huff_entropy_ptr (cinfo^.entropy);
639 { Load up working state }
640 state.next_output_byte := cinfo^.dest^.next_output_byte;
641 state.free_in_buffer := cinfo^.dest^.free_in_buffer;
642 {ASSIGN_STATE(state.cur, entropy^.saved);}
643 state.cur := entropy^.saved;
644 state.cinfo := cinfo;
646 { Emit restart marker if needed }
647 if (cinfo^.restart_interval <> 0) then
648 begin
649 if (entropy^.restarts_to_go = 0) then
650 if not emit_restart(state, entropy^.next_restart_num) then
651 begin
652 encode_mcu_huff := FALSE;
653 exit;
654 end;
655 end;
657 { Encode the MCU data blocks }
658 for blkn := 0 to pred(cinfo^.blocks_in_MCU) do
659 begin
660 ci := cinfo^.MCU_membership[blkn];
661 compptr := cinfo^.cur_comp_info[ci];
662 if not encode_one_block(state,
663 MCU_data[blkn]^[0],
664 state.cur.last_dc_val[ci],
665 entropy^.dc_derived_tbls[compptr^.dc_tbl_no],
666 entropy^.ac_derived_tbls[compptr^.ac_tbl_no]) then
667 begin
668 encode_mcu_huff := FALSE;
669 exit;
670 end;
671 { Update last_dc_val }
672 state.cur.last_dc_val[ci] := MCU_data[blkn]^[0][0];
673 end;
675 { Completed MCU, so update state }
676 cinfo^.dest^.next_output_byte := state.next_output_byte;
677 cinfo^.dest^.free_in_buffer := state.free_in_buffer;
678 {ASSIGN_STATE(entropy^.saved, state.cur);}
679 entropy^.saved := state.cur;
681 { Update restart-interval state too }
682 if (cinfo^.restart_interval <> 0) then
683 begin
684 if (entropy^.restarts_to_go = 0) then
685 begin
686 entropy^.restarts_to_go := cinfo^.restart_interval;
687 Inc(entropy^.next_restart_num);
688 with entropy^ do
689 next_restart_num := next_restart_num and 7;
690 end;
691 Dec(entropy^.restarts_to_go);
692 end;
694 encode_mcu_huff := TRUE;
695 end;
698 { Finish up at the end of a Huffman-compressed scan. }
700 {METHODDEF}
701 procedure finish_pass_huff (cinfo : j_compress_ptr);
702 var
703 entropy : huff_entropy_ptr;
704 state : working_state;
705 begin
706 entropy := huff_entropy_ptr (cinfo^.entropy);
708 { Load up working state ... flush_bits needs it }
709 state.next_output_byte := cinfo^.dest^.next_output_byte;
710 state.free_in_buffer := cinfo^.dest^.free_in_buffer;
711 {ASSIGN_STATE(state.cur, entropy^.saved);}
712 state.cur := entropy^.saved;
713 state.cinfo := cinfo;
715 { Flush out the last data }
716 if not flush_bits(state) then
717 ERREXIT(j_common_ptr(cinfo), JERR_CANT_SUSPEND);
719 { Update state }
720 cinfo^.dest^.next_output_byte := state.next_output_byte;
721 cinfo^.dest^.free_in_buffer := state.free_in_buffer;
722 {ASSIGN_STATE(entropy^.saved, state.cur);}
723 entropy^.saved := state.cur;
724 end;
727 { Huffman coding optimization.
729 We first scan the supplied data and count the number of uses of each symbol
730 that is to be Huffman-coded. (This process MUST agree with the code above.)
731 Then we build a Huffman coding tree for the observed counts.
732 Symbols which are not needed at all for the particular image are not
733 assigned any code, which saves space in the DHT marker as well as in
734 the compressed data. }
736 {$ifdef ENTROPY_OPT_SUPPORTED}
739 { Process a single block's worth of coefficients }
741 {LOCAL}
742 procedure htest_one_block (cinfo : j_compress_ptr;
743 const block : JBLOCK;
744 last_dc_val : int;
745 dc_counts : TLongTablePtr;
746 ac_counts : TLongTablePtr);
748 var
749 {register} temp : int;
750 {register} nbits : int;
751 {register} k, r : int;
752 begin
753 { Encode the DC coefficient difference per section F.1.2.1 }
754 temp := block[0] - last_dc_val;
755 if (temp < 0) then
756 temp := -temp;
758 { Find the number of bits needed for the magnitude of the coefficient }
759 nbits := 0;
760 while (temp <> 0) do
761 begin
762 Inc(nbits);
763 temp := temp shr 1;
764 end;
766 { Check for out-of-range coefficient values.
767 Since we're encoding a difference, the range limit is twice as much. }
769 if (nbits > MAX_COEF_BITS+1) then
770 ERREXIT(j_common_ptr(cinfo), JERR_BAD_DCT_COEF);
772 { Count the Huffman symbol for the number of bits }
773 Inc(dc_counts^[nbits]);
775 { Encode the AC coefficients per section F.1.2.2 }
777 r := 0; { r := run length of zeros }
779 for k := 1 to pred(DCTSIZE2) do
780 begin
781 temp := block[jpeg_natural_order[k]];
782 if (temp = 0) then
783 begin
784 Inc(r);
785 end
786 else
787 begin
788 { if run length > 15, must emit special run-length-16 codes ($F0) }
789 while (r > 15) do
790 begin
791 Inc(ac_counts^[$F0]);
792 Dec(r, 16);
793 end;
795 { Find the number of bits needed for the magnitude of the coefficient }
796 if (temp < 0) then
797 temp := -temp;
799 { Find the number of bits needed for the magnitude of the coefficient }
800 nbits := 0; { there must be at least one 1 bit }
801 repeat
802 Inc(nbits);
803 temp := temp shr 1;
804 until (temp = 0);
807 { Count Huffman symbol for run length / number of bits }
808 Inc(ac_counts^[(r shl 4) + nbits]);
810 r := 0;
811 end;
812 end;
814 { If the last coef(s) were zero, emit an end-of-block code }
815 if (r > 0) then
816 Inc(ac_counts^[0]);
817 end;
820 { Trial-encode one MCU's worth of Huffman-compressed coefficients.
821 No data is actually output, so no suspension return is possible. }
823 {METHODDEF}
824 function encode_mcu_gather (cinfo : j_compress_ptr;
825 const MCU_data: array of JBLOCKROW) : boolean;
826 var
827 entropy : huff_entropy_ptr;
828 blkn, ci : int;
829 compptr : jpeg_component_info_ptr;
830 begin
831 entropy := huff_entropy_ptr (cinfo^.entropy);
832 { Take care of restart intervals if needed }
833 if (cinfo^.restart_interval <> 0) then
834 begin
835 if (entropy^.restarts_to_go = 0) then
836 begin
837 { Re-initialize DC predictions to 0 }
838 for ci := 0 to pred(cinfo^.comps_in_scan) do
839 entropy^.saved.last_dc_val[ci] := 0;
840 { Update restart state }
841 entropy^.restarts_to_go := cinfo^.restart_interval;
842 end;
843 Dec(entropy^.restarts_to_go);
844 end;
846 for blkn := 0 to pred(cinfo^.blocks_in_MCU) do
847 begin
848 ci := cinfo^.MCU_membership[blkn];
849 compptr := cinfo^.cur_comp_info[ci];
850 htest_one_block(cinfo, MCU_data[blkn]^[0],
851 entropy^.saved.last_dc_val[ci],
852 entropy^.dc_count_ptrs[compptr^.dc_tbl_no],
853 entropy^.ac_count_ptrs[compptr^.ac_tbl_no]);
854 entropy^.saved.last_dc_val[ci] := MCU_data[blkn]^[0][0];
855 end;
857 encode_mcu_gather := TRUE;
858 end;
861 { Generate the best Huffman code table for the given counts, fill htbl.
862 Note this is also used by jcphuff.c.
864 The JPEG standard requires that no symbol be assigned a codeword of all
865 one bits (so that padding bits added at the end of a compressed segment
866 can't look like a valid code). Because of the canonical ordering of
867 codewords, this just means that there must be an unused slot in the
868 longest codeword length category. Section K.2 of the JPEG spec suggests
869 reserving such a slot by pretending that symbol 256 is a valid symbol
870 with count 1. In theory that's not optimal; giving it count zero but
871 including it in the symbol set anyway should give a better Huffman code.
872 But the theoretically better code actually seems to come out worse in
873 practice, because it produces more all-ones bytes (which incur stuffed
874 zero bytes in the final file). In any case the difference is tiny.
876 The JPEG standard requires Huffman codes to be no more than 16 bits long.
877 If some symbols have a very small but nonzero probability, the Huffman tree
878 must be adjusted to meet the code length restriction. We currently use
879 the adjustment method suggested in JPEG section K.2. This method is *not*
880 optimal; it may not choose the best possible limited-length code. But
881 typically only very-low-frequency symbols will be given less-than-optimal
882 lengths, so the code is almost optimal. Experimental comparisons against
883 an optimal limited-length-code algorithm indicate that the difference is
884 microscopic --- usually less than a hundredth of a percent of total size.
885 So the extra complexity of an optimal algorithm doesn't seem worthwhile. }
888 {GLOBAL}
889 procedure jpeg_gen_optimal_table (cinfo : j_compress_ptr;
890 htbl : JHUFF_TBL_PTR;
891 var freq : TLongTable);
892 const
893 MAX_CLEN = 32; { assumed maximum initial code length }
894 var
895 bits : array[0..MAX_CLEN+1-1] of UINT8; { bits[k] := # of symbols with code length k }
896 codesize : array[0..257-1] of int; { codesize[k] := code length of symbol k }
897 others : array[0..257-1] of int; { next symbol in current branch of tree }
898 c1, c2 : int;
899 p, i, j : int;
900 v : long;
901 begin
902 { This algorithm is explained in section K.2 of the JPEG standard }
904 MEMZERO(@bits, SIZEOF(bits));
905 MEMZERO(@codesize, SIZEOF(codesize));
906 for i := 0 to 256 do
907 others[i] := -1; { init links to empty }
909 freq[256] := 1; { make sure 256 has a nonzero count }
910 { Including the pseudo-symbol 256 in the Huffman procedure guarantees
911 that no real symbol is given code-value of all ones, because 256
912 will be placed last in the largest codeword category. }
914 { Huffman's basic algorithm to assign optimal code lengths to symbols }
916 while TRUE do
917 begin
918 { Find the smallest nonzero frequency, set c1 := its symbol }
919 { In case of ties, take the larger symbol number }
920 c1 := -1;
921 v := long(1000000000);
922 for i := 0 to 256 do
923 begin
924 if (freq[i] <> 0) and (freq[i] <= v) then
925 begin
926 v := freq[i];
927 c1 := i;
928 end;
929 end;
931 { Find the next smallest nonzero frequency, set c2 := its symbol }
932 { In case of ties, take the larger symbol number }
933 c2 := -1;
934 v := long(1000000000);
935 for i := 0 to 256 do
936 begin
937 if (freq[i] <> 0) and (freq[i] <= v) and (i <> c1) then
938 begin
939 v := freq[i];
940 c2 := i;
941 end;
942 end;
944 { Done if we've merged everything into one frequency }
945 if (c2 < 0) then
946 break;
948 { Else merge the two counts/trees }
949 Inc(freq[c1], freq[c2]);
950 freq[c2] := 0;
952 { Increment the codesize of everything in c1's tree branch }
953 Inc(codesize[c1]);
954 while (others[c1] >= 0) do
955 begin
956 c1 := others[c1];
957 Inc(codesize[c1]);
958 end;
960 others[c1] := c2; { chain c2 onto c1's tree branch }
962 { Increment the codesize of everything in c2's tree branch }
963 Inc(codesize[c2]);
964 while (others[c2] >= 0) do
965 begin
966 c2 := others[c2];
967 Inc(codesize[c2]);
968 end;
969 end;
971 { Now count the number of symbols of each code length }
972 for i := 0 to 256 do
973 begin
974 if (codesize[i]<>0) then
975 begin
976 { The JPEG standard seems to think that this can't happen, }
977 { but I'm paranoid... }
978 if (codesize[i] > MAX_CLEN) then
979 ERREXIT(j_common_ptr(cinfo), JERR_HUFF_CLEN_OVERFLOW);
981 Inc(bits[codesize[i]]);
982 end;
983 end;
985 { JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
986 Huffman procedure assigned any such lengths, we must adjust the coding.
987 Here is what the JPEG spec says about how this next bit works:
988 Since symbols are paired for the longest Huffman code, the symbols are
989 removed from this length category two at a time. The prefix for the pair
990 (which is one bit shorter) is allocated to one of the pair; then,
991 skipping the BITS entry for that prefix length, a code word from the next
992 shortest nonzero BITS entry is converted into a prefix for two code words
993 one bit longer. }
995 for i := MAX_CLEN downto 17 do
996 begin
997 while (bits[i] > 0) do
998 begin
999 j := i - 2; { find length of new prefix to be used }
1000 while (bits[j] = 0) do
1001 Dec(j);
1003 Dec(bits[i], 2); { remove two symbols }
1004 Inc(bits[i-1]); { one goes in this length }
1005 Inc(bits[j+1], 2); { two new symbols in this length }
1006 Dec(bits[j]); { symbol of this length is now a prefix }
1007 end;
1008 end;
1010 { Delphi 2: FOR-loop variable 'i' may be undefined after loop }
1011 i := 16; { Nomssi: work around }
1013 { Remove the count for the pseudo-symbol 256 from the largest codelength }
1014 while (bits[i] = 0) do { find largest codelength still in use }
1015 Dec(i);
1016 Dec(bits[i]);
1018 { Return final symbol counts (only for lengths 0..16) }
1019 MEMCOPY(@htbl^.bits, @bits, SIZEOF(htbl^.bits));
1021 { Return a list of the symbols sorted by code length }
1022 { It's not real clear to me why we don't need to consider the codelength
1023 changes made above, but the JPEG spec seems to think this works. }
1025 p := 0;
1026 for i := 1 to MAX_CLEN do
1027 begin
1028 for j := 0 to 255 do
1029 begin
1030 if (codesize[j] = i) then
1031 begin
1032 htbl^.huffval[p] := UINT8 (j);
1033 Inc(p);
1034 end;
1035 end;
1036 end;
1038 { Set sent_table FALSE so updated table will be written to JPEG file. }
1039 htbl^.sent_table := FALSE;
1040 end;
1043 { Finish up a statistics-gathering pass and create the new Huffman tables. }
1045 {METHODDEF}
1046 procedure finish_pass_gather (cinfo : j_compress_ptr);
1047 var
1048 entropy : huff_entropy_ptr;
1049 ci, dctbl, actbl : int;
1050 compptr : jpeg_component_info_ptr;
1051 htblptr : ^JHUFF_TBL_PTR;
1052 did_dc : array[0..NUM_HUFF_TBLS-1] of boolean;
1053 did_ac : array[0..NUM_HUFF_TBLS-1] of boolean;
1054 begin
1055 entropy := huff_entropy_ptr (cinfo^.entropy);
1057 { It's important not to apply jpeg_gen_optimal_table more than once
1058 per table, because it clobbers the input frequency counts! }
1060 MEMZERO(@did_dc, SIZEOF(did_dc));
1061 MEMZERO(@did_ac, SIZEOF(did_ac));
1063 for ci := 0 to pred(cinfo^.comps_in_scan) do
1064 begin
1065 compptr := cinfo^.cur_comp_info[ci];
1066 dctbl := compptr^.dc_tbl_no;
1067 actbl := compptr^.ac_tbl_no;
1068 if (not did_dc[dctbl]) then
1069 begin
1070 htblptr := @(cinfo^.dc_huff_tbl_ptrs[dctbl]);
1071 if ( htblptr^ = NIL) then
1072 htblptr^ := jpeg_alloc_huff_table(j_common_ptr(cinfo));
1073 jpeg_gen_optimal_table(cinfo, htblptr^, entropy^.dc_count_ptrs[dctbl]^);
1074 did_dc[dctbl] := TRUE;
1075 end;
1076 if (not did_ac[actbl]) then
1077 begin
1078 htblptr := @(cinfo^.ac_huff_tbl_ptrs[actbl]);
1079 if ( htblptr^ = NIL) then
1080 htblptr^ := jpeg_alloc_huff_table(j_common_ptr(cinfo));
1081 jpeg_gen_optimal_table(cinfo, htblptr^, entropy^.ac_count_ptrs[actbl]^);
1082 did_ac[actbl] := TRUE;
1083 end;
1084 end;
1085 end;
1087 {$endif} { ENTROPY_OPT_SUPPORTED }
1090 { Module initialization routine for Huffman entropy encoding. }
1092 {GLOBAL}
1093 procedure jinit_huff_encoder (cinfo : j_compress_ptr);
1094 var
1095 entropy : huff_entropy_ptr;
1096 i : int;
1097 begin
1098 entropy := huff_entropy_ptr(
1099 cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
1100 SIZEOF(huff_entropy_encoder)) );
1101 cinfo^.entropy := jpeg_entropy_encoder_ptr (entropy);
1102 entropy^.pub.start_pass := start_pass_huff;
1104 { Mark tables unallocated }
1105 for i := 0 to pred(NUM_HUFF_TBLS) do
1106 begin
1107 entropy^.ac_derived_tbls[i] := NIL;
1108 entropy^.dc_derived_tbls[i] := NIL;
1109 {$ifdef ENTROPY_OPT_SUPPORTED}
1110 entropy^.ac_count_ptrs[i] := NIL;
1111 entropy^.dc_count_ptrs[i] := NIL;
1112 {$endif}
1113 end;
1114 end;
1116 end.