jcphuff.pas 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. Unit JcpHuff;
  2. { This file contains Huffman entropy encoding routines for progressive JPEG.
  3. We do not support output suspension in this module, since the library
  4. currently does not allow multiple-scan files to be written with output
  5. suspension. }
  6. { Original: jcphuff.c; Copyright (C) 1995-1997, Thomas G. Lane. }
  7. interface
  8. {$I jconfig.inc}
  9. uses
  10. jmorecfg,
  11. jinclude,
  12. jpeglib,
  13. jdeferr,
  14. jerror,
  15. jutils,
  16. jcomapi,
  17. jchuff; { Declarations shared with jchuff.c }
  18. { Module initialization routine for progressive Huffman entropy encoding. }
  19. {GLOBAL}
  20. procedure jinit_phuff_encoder (cinfo : j_compress_ptr);
  21. implementation
  22. { Expanded entropy encoder object for progressive Huffman encoding. }
  23. type
  24. phuff_entropy_ptr = ^phuff_entropy_encoder;
  25. phuff_entropy_encoder = record
  26. pub : jpeg_entropy_encoder; { public fields }
  27. { Mode flag: TRUE for optimization, FALSE for actual data output }
  28. gather_statistics : boolean;
  29. { Bit-level coding status.
  30. next_output_byte/free_in_buffer are local copies of cinfo^.dest fields.}
  31. next_output_byte : JOCTETptr; { => next byte to write in buffer }
  32. free_in_buffer : size_t; { # of byte spaces remaining in buffer }
  33. put_buffer : INT32; { current bit-accumulation buffer }
  34. put_bits : int; { # of bits now in it }
  35. cinfo : j_compress_ptr; { link to cinfo (needed for dump_buffer) }
  36. { Coding status for DC components }
  37. last_dc_val : array[0..MAX_COMPS_IN_SCAN-1] of int;
  38. { last DC coef for each component }
  39. { Coding status for AC components }
  40. ac_tbl_no : int; { the table number of the single component }
  41. EOBRUN : uInt; { run length of EOBs }
  42. BE : uInt; { # of buffered correction bits before MCU }
  43. bit_buffer : JBytePtr; { buffer for correction bits (1 per char) }
  44. { packing correction bits tightly would save some space but cost time... }
  45. restarts_to_go : uInt; { MCUs left in this restart interval }
  46. next_restart_num : int; { next restart number to write (0-7) }
  47. { Pointers to derived tables (these workspaces have image lifespan).
  48. Since any one scan codes only DC or only AC, we only need one set
  49. of tables, not one for DC and one for AC. }
  50. derived_tbls : array[0..NUM_HUFF_TBLS-1] of c_derived_tbl_ptr;
  51. { Statistics tables for optimization; again, one set is enough }
  52. count_ptrs : array[0..NUM_HUFF_TBLS-1] of TLongTablePtr;
  53. end;
  54. { MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  55. buffer can hold. Larger sizes may slightly improve compression, but
  56. 1000 is already well into the realm of overkill.
  57. The minimum safe size is 64 bits. }
  58. const
  59. MAX_CORR_BITS = 1000; { Max # of correction bits I can buffer }
  60. { Forward declarations }
  61. {METHODDEF}
  62. function encode_mcu_DC_first (cinfo : j_compress_ptr;
  63. const MCU_data: array of JBLOCKROW) : boolean;
  64. far; forward;
  65. {METHODDEF}
  66. function encode_mcu_AC_first (cinfo : j_compress_ptr;
  67. const MCU_data: array of JBLOCKROW) : boolean;
  68. far; forward;
  69. {METHODDEF}
  70. function encode_mcu_DC_refine (cinfo : j_compress_ptr;
  71. const MCU_data: array of JBLOCKROW) : boolean;
  72. far; forward;
  73. {METHODDEF}
  74. function encode_mcu_AC_refine (cinfo : j_compress_ptr;
  75. const MCU_data: array of JBLOCKROW) : boolean;
  76. far; forward;
  77. {METHODDEF}
  78. procedure finish_pass_phuff (cinfo : j_compress_ptr); far; forward;
  79. {METHODDEF}
  80. procedure finish_pass_gather_phuff (cinfo : j_compress_ptr); far; forward;
  81. { Initialize for a Huffman-compressed scan using progressive JPEG. }
  82. {METHODDEF}
  83. procedure start_pass_phuff (cinfo : j_compress_ptr;
  84. gather_statistics : boolean); far;
  85. var
  86. entropy : phuff_entropy_ptr;
  87. is_DC_band : boolean;
  88. ci, tbl : int;
  89. compptr : jpeg_component_info_ptr;
  90. begin
  91. entropy := phuff_entropy_ptr (cinfo^.entropy);
  92. entropy^.cinfo := cinfo;
  93. entropy^.gather_statistics := gather_statistics;
  94. is_DC_band := (cinfo^.Ss = 0);
  95. { We assume jcmaster.c already validated the scan parameters. }
  96. { Select execution routines }
  97. if (cinfo^.Ah = 0) then
  98. begin
  99. if (is_DC_band) then
  100. entropy^.pub.encode_mcu := encode_mcu_DC_first
  101. else
  102. entropy^.pub.encode_mcu := encode_mcu_AC_first;
  103. end
  104. else
  105. begin
  106. if (is_DC_band) then
  107. entropy^.pub.encode_mcu := encode_mcu_DC_refine
  108. else
  109. begin
  110. entropy^.pub.encode_mcu := encode_mcu_AC_refine;
  111. { AC refinement needs a correction bit buffer }
  112. if (entropy^.bit_buffer = NIL) then
  113. entropy^.bit_buffer := JBytePtr(
  114. cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
  115. MAX_CORR_BITS * SIZEOF(byte)) );
  116. end;
  117. end;
  118. if (gather_statistics) then
  119. entropy^.pub.finish_pass := finish_pass_gather_phuff
  120. else
  121. entropy^.pub.finish_pass := finish_pass_phuff;
  122. { Only DC coefficients may be interleaved, so cinfo^.comps_in_scan = 1
  123. for AC coefficients. }
  124. for ci := 0 to pred(cinfo^.comps_in_scan) do
  125. begin
  126. compptr := cinfo^.cur_comp_info[ci];
  127. { Initialize DC predictions to 0 }
  128. entropy^.last_dc_val[ci] := 0;
  129. { Get table index }
  130. if (is_DC_band) then
  131. begin
  132. if (cinfo^.Ah <> 0) then { DC refinement needs no table }
  133. continue;
  134. tbl := compptr^.dc_tbl_no;
  135. end
  136. else
  137. begin
  138. tbl := compptr^.ac_tbl_no;
  139. entropy^.ac_tbl_no := tbl;
  140. end;
  141. if (gather_statistics) then
  142. begin
  143. { Check for invalid table index }
  144. { (make_c_derived_tbl does this in the other path) }
  145. if (tbl < 0) or (tbl >= NUM_HUFF_TBLS) then
  146. ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, tbl);
  147. { Allocate and zero the statistics tables }
  148. { Note that jpeg_gen_optimal_table expects 257 entries in each table! }
  149. if (entropy^.count_ptrs[tbl] = NIL) then
  150. entropy^.count_ptrs[tbl] := TLongTablePtr(
  151. cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
  152. 257 * SIZEOF(long)) );
  153. MEMZERO(entropy^.count_ptrs[tbl], 257 * SIZEOF(long));
  154. end else
  155. begin
  156. { Compute derived values for Huffman table }
  157. { We may do this more than once for a table, but it's not expensive }
  158. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  159. entropy^.derived_tbls[tbl]);
  160. end;
  161. end;
  162. { Initialize AC stuff }
  163. entropy^.EOBRUN := 0;
  164. entropy^.BE := 0;
  165. { Initialize bit buffer to empty }
  166. entropy^.put_buffer := 0;
  167. entropy^.put_bits := 0;
  168. { Initialize restart stuff }
  169. entropy^.restarts_to_go := cinfo^.restart_interval;
  170. entropy^.next_restart_num := 0;
  171. end;
  172. {LOCAL}
  173. procedure dump_buffer (entropy : phuff_entropy_ptr);
  174. { Empty the output buffer; we do not support suspension in this module. }
  175. var
  176. dest : jpeg_destination_mgr_ptr;
  177. begin
  178. dest := entropy^.cinfo^.dest;
  179. if (not dest^.empty_output_buffer (entropy^.cinfo)) then
  180. ERREXIT(j_common_ptr(entropy^.cinfo), JERR_CANT_SUSPEND);
  181. { After a successful buffer dump, must reset buffer pointers }
  182. entropy^.next_output_byte := dest^.next_output_byte;
  183. entropy^.free_in_buffer := dest^.free_in_buffer;
  184. end;
  185. { Outputting bits to the file }
  186. { Only the right 24 bits of put_buffer are used; the valid bits are
  187. left-justified in this part. At most 16 bits can be passed to emit_bits
  188. in one call, and we never retain more than 7 bits in put_buffer
  189. between calls, so 24 bits are sufficient. }
  190. {LOCAL}
  191. procedure emit_bits (entropy : phuff_entropy_ptr;
  192. code : uInt;
  193. size : int); {INLINE}
  194. { Emit some bits, unless we are in gather mode }
  195. var
  196. {register} put_buffer : INT32;
  197. {register} put_bits : int;
  198. var
  199. c : int;
  200. begin
  201. { This routine is heavily used, so it's worth coding tightly. }
  202. put_buffer := INT32 (code);
  203. put_bits := entropy^.put_bits;
  204. { if size is 0, caller used an invalid Huffman table entry }
  205. if (size = 0) then
  206. ERREXIT(j_common_ptr(entropy^.cinfo), JERR_HUFF_MISSING_CODE);
  207. if (entropy^.gather_statistics) then
  208. exit; { do nothing if we're only getting stats }
  209. put_buffer := put_buffer and ((INT32(1) shl size) - 1);
  210. { mask off any extra bits in code }
  211. Inc(put_bits, size); { new number of bits in buffer }
  212. put_buffer := put_buffer shl (24 - put_bits); { align incoming bits }
  213. put_buffer := put_buffer or entropy^.put_buffer;
  214. { and merge with old buffer contents }
  215. while (put_bits >= 8) do
  216. begin
  217. c := int ((put_buffer shr 16) and $FF);
  218. {emit_byte(entropy, c);}
  219. { Outputting bytes to the file.
  220. NB: these must be called only when actually outputting,
  221. that is, entropy^.gather_statistics = FALSE. }
  222. { Emit a byte }
  223. entropy^.next_output_byte^ := JOCTET(c);
  224. Inc(entropy^.next_output_byte);
  225. Dec(entropy^.free_in_buffer);
  226. if (entropy^.free_in_buffer = 0) then
  227. dump_buffer(entropy);
  228. if (c = $FF) then
  229. begin { need to stuff a zero byte? }
  230. {emit_byte(entropy, 0);}
  231. entropy^.next_output_byte^ := JOCTET(0);
  232. Inc(entropy^.next_output_byte);
  233. Dec(entropy^.free_in_buffer);
  234. if (entropy^.free_in_buffer = 0) then
  235. dump_buffer(entropy);
  236. end;
  237. put_buffer := put_buffer shl 8;
  238. Dec(put_bits, 8);
  239. end;
  240. entropy^.put_buffer := put_buffer; { update variables }
  241. entropy^.put_bits := put_bits;
  242. end;
  243. {LOCAL}
  244. procedure flush_bits (entropy : phuff_entropy_ptr);
  245. begin
  246. emit_bits(entropy, $7F, 7); { fill any partial byte with ones }
  247. entropy^.put_buffer := 0; { and reset bit-buffer to empty }
  248. entropy^.put_bits := 0;
  249. end;
  250. { Emit (or just count) a Huffman symbol. }
  251. {LOCAL}
  252. procedure emit_symbol (entropy : phuff_entropy_ptr;
  253. tbl_no : int;
  254. symbol : int); {INLINE}
  255. var
  256. tbl : c_derived_tbl_ptr;
  257. begin
  258. if (entropy^.gather_statistics) then
  259. Inc(entropy^.count_ptrs[tbl_no]^[symbol])
  260. else
  261. begin
  262. tbl := entropy^.derived_tbls[tbl_no];
  263. emit_bits(entropy, tbl^.ehufco[symbol], tbl^.ehufsi[symbol]);
  264. end;
  265. end;
  266. { Emit bits from a correction bit buffer. }
  267. {LOCAL}
  268. procedure emit_buffered_bits (entropy : phuff_entropy_ptr;
  269. bufstart : JBytePtr;
  270. nbits : uInt);
  271. var
  272. bufptr : byteptr;
  273. begin
  274. if (entropy^.gather_statistics) then
  275. exit; { no real work }
  276. bufptr := byteptr(bufstart);
  277. while (nbits > 0) do
  278. begin
  279. emit_bits(entropy, uInt(bufptr^), 1);
  280. Inc(bufptr);
  281. Dec(nbits);
  282. end;
  283. end;
  284. { Emit any pending EOBRUN symbol. }
  285. {LOCAL}
  286. procedure emit_eobrun (entropy : phuff_entropy_ptr);
  287. var
  288. {register} temp, nbits : int;
  289. begin
  290. if (entropy^.EOBRUN > 0) then
  291. begin { if there is any pending EOBRUN }
  292. temp := entropy^.EOBRUN;
  293. nbits := 0;
  294. temp := temp shr 1;
  295. while (temp <> 0) do
  296. begin
  297. Inc(nbits);
  298. temp := temp shr 1;
  299. end;
  300. { safety check: shouldn't happen given limited correction-bit buffer }
  301. if (nbits > 14) then
  302. ERREXIT(j_common_ptr(entropy^.cinfo), JERR_HUFF_MISSING_CODE);
  303. emit_symbol(entropy, entropy^.ac_tbl_no, nbits shl 4);
  304. if (nbits <> 0) then
  305. emit_bits(entropy, entropy^.EOBRUN, nbits);
  306. entropy^.EOBRUN := 0;
  307. { Emit any buffered correction bits }
  308. emit_buffered_bits(entropy, entropy^.bit_buffer, entropy^.BE);
  309. entropy^.BE := 0;
  310. end;
  311. end;
  312. { Emit a restart marker & resynchronize predictions. }
  313. {LOCAL}
  314. procedure emit_restart (entropy : phuff_entropy_ptr;
  315. restart_num : int);
  316. var
  317. ci : int;
  318. begin
  319. emit_eobrun(entropy);
  320. if (not entropy^.gather_statistics) then
  321. begin
  322. flush_bits(entropy);
  323. {emit_byte(entropy, $FF);}
  324. { Outputting bytes to the file.
  325. NB: these must be called only when actually outputting,
  326. that is, entropy^.gather_statistics = FALSE. }
  327. entropy^.next_output_byte^ := JOCTET($FF);
  328. Inc(entropy^.next_output_byte);
  329. Dec(entropy^.free_in_buffer);
  330. if (entropy^.free_in_buffer = 0) then
  331. dump_buffer(entropy);
  332. {emit_byte(entropy, JPEG_RST0 + restart_num);}
  333. entropy^.next_output_byte^ := JOCTET(JPEG_RST0 + restart_num);
  334. Inc(entropy^.next_output_byte);
  335. Dec(entropy^.free_in_buffer);
  336. if (entropy^.free_in_buffer = 0) then
  337. dump_buffer(entropy);
  338. end;
  339. if (entropy^.cinfo^.Ss = 0) then
  340. begin
  341. { Re-initialize DC predictions to 0 }
  342. for ci := 0 to pred(entropy^.cinfo^.comps_in_scan) do
  343. entropy^.last_dc_val[ci] := 0;
  344. end
  345. else
  346. begin
  347. { Re-initialize all AC-related fields to 0 }
  348. entropy^.EOBRUN := 0;
  349. entropy^.BE := 0;
  350. end;
  351. end;
  352. { MCU encoding for DC initial scan (either spectral selection,
  353. or first pass of successive approximation). }
  354. {METHODDEF}
  355. function encode_mcu_DC_first (cinfo : j_compress_ptr;
  356. const MCU_data: array of JBLOCKROW) : boolean;
  357. var
  358. entropy : phuff_entropy_ptr;
  359. {register} temp, temp2 : int;
  360. {register} nbits : int;
  361. blkn, ci : int;
  362. Al : int;
  363. block : JBLOCK_PTR;
  364. compptr : jpeg_component_info_ptr;
  365. ishift_temp : int;
  366. begin
  367. entropy := phuff_entropy_ptr (cinfo^.entropy);
  368. Al := cinfo^.Al;
  369. entropy^.next_output_byte := cinfo^.dest^.next_output_byte;
  370. entropy^.free_in_buffer := cinfo^.dest^.free_in_buffer;
  371. { Emit restart marker if needed }
  372. if (cinfo^.restart_interval <> 0) then
  373. if (entropy^.restarts_to_go = 0) then
  374. emit_restart(entropy, entropy^.next_restart_num);
  375. { Encode the MCU data blocks }
  376. for blkn := 0 to pred(cinfo^.blocks_in_MCU) do
  377. begin
  378. block := JBLOCK_PTR(MCU_data[blkn]);
  379. ci := cinfo^.MCU_membership[blkn];
  380. compptr := cinfo^.cur_comp_info[ci];
  381. { Compute the DC value after the required point transform by Al.
  382. This is simply an arithmetic right shift. }
  383. {temp2 := IRIGHT_SHIFT( int(block^[0]), Al);}
  384. {IRIGHT_SHIFT_IS_UNSIGNED}
  385. ishift_temp := int(block^[0]);
  386. if ishift_temp < 0 then
  387. temp2 := (ishift_temp shr Al) or ((not 0) shl (16-Al))
  388. else
  389. temp2 := ishift_temp shr Al;
  390. { DC differences are figured on the point-transformed values. }
  391. temp := temp2 - entropy^.last_dc_val[ci];
  392. entropy^.last_dc_val[ci] := temp2;
  393. { Encode the DC coefficient difference per section G.1.2.1 }
  394. temp2 := temp;
  395. if (temp < 0) then
  396. begin
  397. temp := -temp; { temp is abs value of input }
  398. { For a negative input, want temp2 := bitwise complement of abs(input) }
  399. { This code assumes we are on a two's complement machine }
  400. Dec(temp2);
  401. end;
  402. { Find the number of bits needed for the magnitude of the coefficient }
  403. nbits := 0;
  404. while (temp <> 0) do
  405. begin
  406. Inc(nbits);
  407. temp := temp shr 1;
  408. end;
  409. { Check for out-of-range coefficient values.
  410. Since we're encoding a difference, the range limit is twice as much. }
  411. if (nbits > MAX_COEF_BITS+1) then
  412. ERREXIT(j_common_ptr(cinfo), JERR_BAD_DCT_COEF);
  413. { Count/emit the Huffman-coded symbol for the number of bits }
  414. emit_symbol(entropy, compptr^.dc_tbl_no, nbits);
  415. { Emit that number of bits of the value, if positive, }
  416. { or the complement of its magnitude, if negative. }
  417. if (nbits <> 0) then { emit_bits rejects calls with size 0 }
  418. emit_bits(entropy, uInt(temp2), nbits);
  419. end;
  420. cinfo^.dest^.next_output_byte := entropy^.next_output_byte;
  421. cinfo^.dest^.free_in_buffer := entropy^.free_in_buffer;
  422. { Update restart-interval state too }
  423. if (cinfo^.restart_interval <> 0) then
  424. begin
  425. if (entropy^.restarts_to_go = 0) then
  426. begin
  427. entropy^.restarts_to_go := cinfo^.restart_interval;
  428. Inc(entropy^.next_restart_num);
  429. with entropy^ do
  430. next_restart_num := next_restart_num and 7;
  431. end;
  432. Dec(entropy^.restarts_to_go);
  433. end;
  434. encode_mcu_DC_first := TRUE;
  435. end;
  436. { MCU encoding for AC initial scan (either spectral selection,
  437. or first pass of successive approximation). }
  438. {METHODDEF}
  439. function encode_mcu_AC_first (cinfo : j_compress_ptr;
  440. const MCU_data: array of JBLOCKROW) : boolean;
  441. var
  442. entropy : phuff_entropy_ptr;
  443. {register} temp, temp2 : int;
  444. {register} nbits : int;
  445. {register} r, k : int;
  446. Se : int;
  447. Al : int;
  448. block : JBLOCK_PTR;
  449. begin
  450. entropy := phuff_entropy_ptr (cinfo^.entropy);
  451. Se := cinfo^.Se;
  452. Al := cinfo^.Al;
  453. entropy^.next_output_byte := cinfo^.dest^.next_output_byte;
  454. entropy^.free_in_buffer := cinfo^.dest^.free_in_buffer;
  455. { Emit restart marker if needed }
  456. if (cinfo^.restart_interval <> 0) then
  457. if (entropy^.restarts_to_go = 0) then
  458. emit_restart(entropy, entropy^.next_restart_num);
  459. { Encode the MCU data block }
  460. block := JBLOCK_PTR(MCU_data[0]);
  461. { Encode the AC coefficients per section G.1.2.2, fig. G.3 }
  462. r := 0; { r := run length of zeros }
  463. for k := cinfo^.Ss to Se do
  464. begin
  465. temp := (block^[jpeg_natural_order[k]]);
  466. if (temp = 0) then
  467. begin
  468. Inc(r);
  469. continue;
  470. end;
  471. { We must apply the point transform by Al. For AC coefficients this
  472. is an integer division with rounding towards 0. To do this portably
  473. in C, we shift after obtaining the absolute value; so the code is
  474. interwoven with finding the abs value (temp) and output bits (temp2). }
  475. if (temp < 0) then
  476. begin
  477. temp := -temp; { temp is abs value of input }
  478. temp := temp shr Al; { apply the point transform }
  479. { For a negative coef, want temp2 := bitwise complement of abs(coef) }
  480. temp2 := not temp;
  481. end
  482. else
  483. begin
  484. temp := temp shr Al; { apply the point transform }
  485. temp2 := temp;
  486. end;
  487. { Watch out for case that nonzero coef is zero after point transform }
  488. if (temp = 0) then
  489. begin
  490. Inc(r);
  491. continue;
  492. end;
  493. { Emit any pending EOBRUN }
  494. if (entropy^.EOBRUN > 0) then
  495. emit_eobrun(entropy);
  496. { if run length > 15, must emit special run-length-16 codes ($F0) }
  497. while (r > 15) do
  498. begin
  499. emit_symbol(entropy, entropy^.ac_tbl_no, $F0);
  500. Dec(r, 16);
  501. end;
  502. { Find the number of bits needed for the magnitude of the coefficient }
  503. nbits := 0; { there must be at least one 1 bit }
  504. repeat
  505. Inc(nbits);
  506. temp := temp shr 1;
  507. until (temp = 0);
  508. { Check for out-of-range coefficient values }
  509. if (nbits > MAX_COEF_BITS) then
  510. ERREXIT(j_common_ptr(cinfo), JERR_BAD_DCT_COEF);
  511. { Count/emit Huffman symbol for run length / number of bits }
  512. emit_symbol(entropy, entropy^.ac_tbl_no, (r shl 4) + nbits);
  513. { Emit that number of bits of the value, if positive, }
  514. { or the complement of its magnitude, if negative. }
  515. emit_bits(entropy, uInt(temp2), nbits);
  516. r := 0; { reset zero run length }
  517. end;
  518. if (r > 0) then
  519. begin { If there are trailing zeroes, }
  520. Inc(entropy^.EOBRUN); { count an EOB }
  521. if (entropy^.EOBRUN = $7FFF) then
  522. emit_eobrun(entropy); { force it out to avoid overflow }
  523. end;
  524. cinfo^.dest^.next_output_byte := entropy^.next_output_byte;
  525. cinfo^.dest^.free_in_buffer := entropy^.free_in_buffer;
  526. { Update restart-interval state too }
  527. if (cinfo^.restart_interval <> 0) then
  528. begin
  529. if (entropy^.restarts_to_go = 0) then
  530. begin
  531. entropy^.restarts_to_go := cinfo^.restart_interval;
  532. Inc(entropy^.next_restart_num);
  533. with entropy^ do
  534. next_restart_num := next_restart_num and 7;
  535. end;
  536. Dec(entropy^.restarts_to_go);
  537. end;
  538. encode_mcu_AC_first := TRUE;
  539. end;
  540. { MCU encoding for DC successive approximation refinement scan.
  541. Note: we assume such scans can be multi-component, although the spec
  542. is not very clear on the point. }
  543. {METHODDEF}
  544. function encode_mcu_DC_refine (cinfo : j_compress_ptr;
  545. const MCU_data: array of JBLOCKROW) : boolean;
  546. var
  547. entropy : phuff_entropy_ptr;
  548. {register} temp : int;
  549. blkn : int;
  550. Al : int;
  551. block : JBLOCK_PTR;
  552. begin
  553. entropy := phuff_entropy_ptr (cinfo^.entropy);
  554. Al := cinfo^.Al;
  555. entropy^.next_output_byte := cinfo^.dest^.next_output_byte;
  556. entropy^.free_in_buffer := cinfo^.dest^.free_in_buffer;
  557. { Emit restart marker if needed }
  558. if (cinfo^.restart_interval <> 0) then
  559. if (entropy^.restarts_to_go = 0) then
  560. emit_restart(entropy, entropy^.next_restart_num);
  561. { Encode the MCU data blocks }
  562. for blkn := 0 to pred(cinfo^.blocks_in_MCU) do
  563. begin
  564. block := JBLOCK_PTR(MCU_data[blkn]);
  565. { We simply emit the Al'th bit of the DC coefficient value. }
  566. temp := block^[0];
  567. emit_bits(entropy, uInt(temp shr Al), 1);
  568. end;
  569. cinfo^.dest^.next_output_byte := entropy^.next_output_byte;
  570. cinfo^.dest^.free_in_buffer := entropy^.free_in_buffer;
  571. { Update restart-interval state too }
  572. if (cinfo^.restart_interval <> 0) then
  573. begin
  574. if (entropy^.restarts_to_go = 0) then
  575. begin
  576. entropy^.restarts_to_go := cinfo^.restart_interval;
  577. Inc(entropy^.next_restart_num);
  578. with entropy^ do
  579. next_restart_num := next_restart_num and 7;
  580. end;
  581. Dec(entropy^.restarts_to_go);
  582. end;
  583. encode_mcu_DC_refine := TRUE;
  584. end;
  585. { MCU encoding for AC successive approximation refinement scan. }
  586. {METHODDEF}
  587. function encode_mcu_AC_refine (cinfo : j_compress_ptr;
  588. const MCU_data: array of JBLOCKROW) : boolean;
  589. var
  590. entropy : phuff_entropy_ptr;
  591. {register} temp : int;
  592. {register} r, k : int;
  593. EOB : int;
  594. BR_buffer : JBytePtr;
  595. BR : uInt;
  596. Se : int;
  597. Al : int;
  598. block : JBLOCK_PTR;
  599. absvalues : array[0..DCTSIZE2-1] of int;
  600. begin
  601. entropy := phuff_entropy_ptr(cinfo^.entropy);
  602. Se := cinfo^.Se;
  603. Al := cinfo^.Al;
  604. entropy^.next_output_byte := cinfo^.dest^.next_output_byte;
  605. entropy^.free_in_buffer := cinfo^.dest^.free_in_buffer;
  606. { Emit restart marker if needed }
  607. if (cinfo^.restart_interval <> 0) then
  608. if (entropy^.restarts_to_go = 0) then
  609. emit_restart(entropy, entropy^.next_restart_num);
  610. { Encode the MCU data block }
  611. block := JBLOCK_PTR(MCU_data[0]);
  612. { It is convenient to make a pre-pass to determine the transformed
  613. coefficients' absolute values and the EOB position. }
  614. EOB := 0;
  615. for k := cinfo^.Ss to Se do
  616. begin
  617. temp := block^[jpeg_natural_order[k]];
  618. { We must apply the point transform by Al. For AC coefficients this
  619. is an integer division with rounding towards 0. To do this portably
  620. in C, we shift after obtaining the absolute value. }
  621. if (temp < 0) then
  622. temp := -temp; { temp is abs value of input }
  623. temp := temp shr Al; { apply the point transform }
  624. absvalues[k] := temp; { save abs value for main pass }
  625. if (temp = 1) then
  626. EOB := k; { EOB := index of last newly-nonzero coef }
  627. end;
  628. { Encode the AC coefficients per section G.1.2.3, fig. G.7 }
  629. r := 0; { r := run length of zeros }
  630. BR := 0; { BR := count of buffered bits added now }
  631. BR_buffer := JBytePtr(@(entropy^.bit_buffer^[entropy^.BE]));
  632. { Append bits to buffer }
  633. for k := cinfo^.Ss to Se do
  634. begin
  635. temp := absvalues[k];
  636. if (temp = 0) then
  637. begin
  638. Inc(r);
  639. continue;
  640. end;
  641. { Emit any required ZRLs, but not if they can be folded into EOB }
  642. while (r > 15) and (k <= EOB) do
  643. begin
  644. { emit any pending EOBRUN and the BE correction bits }
  645. emit_eobrun(entropy);
  646. { Emit ZRL }
  647. emit_symbol(entropy, entropy^.ac_tbl_no, $F0);
  648. Dec(r, 16);
  649. { Emit buffered correction bits that must be associated with ZRL }
  650. emit_buffered_bits(entropy, BR_buffer, BR);
  651. BR_buffer := entropy^.bit_buffer; { BE bits are gone now }
  652. BR := 0;
  653. end;
  654. { If the coef was previously nonzero, it only needs a correction bit.
  655. NOTE: a straight translation of the spec's figure G.7 would suggest
  656. that we also need to test r > 15. But if r > 15, we can only get here
  657. if k > EOB, which implies that this coefficient is not 1. }
  658. if (temp > 1) then
  659. begin
  660. { The correction bit is the next bit of the absolute value. }
  661. BR_buffer^[BR] := byte (temp and 1);
  662. Inc(BR);
  663. continue;
  664. end;
  665. { Emit any pending EOBRUN and the BE correction bits }
  666. emit_eobrun(entropy);
  667. { Count/emit Huffman symbol for run length / number of bits }
  668. emit_symbol(entropy, entropy^.ac_tbl_no, (r shl 4) + 1);
  669. { Emit output bit for newly-nonzero coef }
  670. if (block^[jpeg_natural_order[k]] < 0) then
  671. temp := 0
  672. else
  673. temp := 1;
  674. emit_bits(entropy, uInt(temp), 1);
  675. { Emit buffered correction bits that must be associated with this code }
  676. emit_buffered_bits(entropy, BR_buffer, BR);
  677. BR_buffer := entropy^.bit_buffer; { BE bits are gone now }
  678. BR := 0;
  679. r := 0; { reset zero run length }
  680. end;
  681. if (r > 0) or (BR > 0) then
  682. begin { If there are trailing zeroes, }
  683. Inc(entropy^.EOBRUN); { count an EOB }
  684. Inc(entropy^.BE, BR); { concat my correction bits to older ones }
  685. { We force out the EOB if we risk either:
  686. 1. overflow of the EOB counter;
  687. 2. overflow of the correction bit buffer during the next MCU. }
  688. if (entropy^.EOBRUN = $7FFF) or
  689. (entropy^.BE > (MAX_CORR_BITS-DCTSIZE2+1)) then
  690. emit_eobrun(entropy);
  691. end;
  692. cinfo^.dest^.next_output_byte := entropy^.next_output_byte;
  693. cinfo^.dest^.free_in_buffer := entropy^.free_in_buffer;
  694. { Update restart-interval state too }
  695. if (cinfo^.restart_interval <> 0) then
  696. begin
  697. if (entropy^.restarts_to_go = 0) then
  698. begin
  699. entropy^.restarts_to_go := cinfo^.restart_interval;
  700. Inc(entropy^.next_restart_num);
  701. with entropy^ do
  702. next_restart_num := next_restart_num and 7;
  703. end;
  704. Dec(entropy^.restarts_to_go);
  705. end;
  706. encode_mcu_AC_refine := TRUE;
  707. end;
  708. { Finish up at the end of a Huffman-compressed progressive scan. }
  709. {METHODDEF}
  710. procedure finish_pass_phuff (cinfo : j_compress_ptr);
  711. var
  712. entropy : phuff_entropy_ptr;
  713. begin
  714. entropy := phuff_entropy_ptr (cinfo^.entropy);
  715. entropy^.next_output_byte := cinfo^.dest^.next_output_byte;
  716. entropy^.free_in_buffer := cinfo^.dest^.free_in_buffer;
  717. { Flush out any buffered data }
  718. emit_eobrun(entropy);
  719. flush_bits(entropy);
  720. cinfo^.dest^.next_output_byte := entropy^.next_output_byte;
  721. cinfo^.dest^.free_in_buffer := entropy^.free_in_buffer;
  722. end;
  723. { Finish up a statistics-gathering pass and create the new Huffman tables. }
  724. {METHODDEF}
  725. procedure finish_pass_gather_phuff (cinfo : j_compress_ptr);
  726. var
  727. entropy : phuff_entropy_ptr;
  728. is_DC_band : boolean;
  729. ci, tbl : int;
  730. compptr : jpeg_component_info_ptr;
  731. htblptr : ^JHUFF_TBL_PTR;
  732. did : array[0..NUM_HUFF_TBLS-1] of boolean;
  733. begin
  734. entropy := phuff_entropy_ptr (cinfo^.entropy);
  735. { Flush out buffered data (all we care about is counting the EOB symbol) }
  736. emit_eobrun(entropy);
  737. is_DC_band := (cinfo^.Ss = 0);
  738. { It's important not to apply jpeg_gen_optimal_table more than once
  739. per table, because it clobbers the input frequency counts! }
  740. MEMZERO(@did, SIZEOF(did));
  741. for ci := 0 to pred(cinfo^.comps_in_scan) do
  742. begin
  743. compptr := cinfo^.cur_comp_info[ci];
  744. if (is_DC_band) then
  745. begin
  746. if (cinfo^.Ah <> 0) then { DC refinement needs no table }
  747. continue;
  748. tbl := compptr^.dc_tbl_no;
  749. end
  750. else
  751. begin
  752. tbl := compptr^.ac_tbl_no;
  753. end;
  754. if (not did[tbl]) then
  755. begin
  756. if (is_DC_band) then
  757. htblptr := @(cinfo^.dc_huff_tbl_ptrs[tbl])
  758. else
  759. htblptr := @(cinfo^.ac_huff_tbl_ptrs[tbl]);
  760. if (htblptr^ = NIL) then
  761. htblptr^ := jpeg_alloc_huff_table(j_common_ptr(cinfo));
  762. jpeg_gen_optimal_table(cinfo, htblptr^, entropy^.count_ptrs[tbl]^);
  763. did[tbl] := TRUE;
  764. end;
  765. end;
  766. end;
  767. { Module initialization routine for progressive Huffman entropy encoding. }
  768. {GLOBAL}
  769. procedure jinit_phuff_encoder (cinfo : j_compress_ptr);
  770. var
  771. entropy : phuff_entropy_ptr;
  772. i : int;
  773. begin
  774. entropy := phuff_entropy_ptr(
  775. cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
  776. SIZEOF(phuff_entropy_encoder)) );
  777. cinfo^.entropy := jpeg_entropy_encoder_ptr(entropy);
  778. entropy^.pub.start_pass := start_pass_phuff;
  779. { Mark tables unallocated }
  780. for i := 0 to pred(NUM_HUFF_TBLS) do
  781. begin
  782. entropy^.derived_tbls[i] := NIL;
  783. entropy^.count_ptrs[i] := NIL;
  784. end;
  785. entropy^.bit_buffer := NIL; { needed only in AC refinement scan }
  786. end;
  787. end.