jchuff.pas 34 KB

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