⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jdhuff.pas

📁 用pascal寫的jpeg codec, 測試過的
💻 PAS
📖 第 1 页 / 共 3 页
字号:
var
  dtbl : d_derived_tbl_ptr;
  p, i, l, si : int;
  lookbits, ctr : int;
  huffsize : array[0..257-1] of byte;
  huffcode : array[0..257-1] of uInt;
  code : uInt;
begin
  { Allocate a workspace if we haven't already done so. }
  if (pdtbl = NIL) then
    pdtbl := d_derived_tbl_ptr(
      cinfo^.mem^.alloc_small (j_common_ptr(cinfo), JPOOL_IMAGE,
				  SIZEOF(d_derived_tbl)) );
  dtbl := pdtbl;
  dtbl^.pub := htbl;		{ fill in back link }

  { Figure C.1: make table of Huffman code length for each symbol }
  { Note that this is in code-length order. }

  p := 0;
  for l := 1 to 16 do
  begin
    for i := 1 to int(htbl^.bits[l]) do
    begin
      huffsize[p] := byte(l);
      Inc(p);
    end;
  end;
  huffsize[p] := 0;

  { Figure C.2: generate the codes themselves }
  { Note that this is in code-length order. }

  code := 0;
  si := huffsize[0];
  p := 0;
  while (huffsize[p] <> 0) do
  begin
    while (( int (huffsize[p]) ) = si) do
    begin
      huffcode[p] := code;
      Inc(p);
      Inc(code);
    end;
    code := code shl 1;
    Inc(si);
  end;

  { Figure F.15: generate decoding tables for bit-sequential decoding }

  p := 0;
  for l := 1 to 16 do
  begin
    if (htbl^.bits[l] <> 0) then
    begin
      dtbl^.valptr[l] := p; { huffval[] index of 1st symbol of code length l }
      dtbl^.mincode[l] := huffcode[p]; { minimum code of length l }
      Inc(p, htbl^.bits[l]);
      dtbl^.maxcode[l] := huffcode[p-1]; { maximum code of length l }
    end
    else
    begin
      dtbl^.maxcode[l] := -1;	{ -1 if no codes of this length }
    end;
  end;
  dtbl^.maxcode[17] := long($FFFFF); { ensures jpeg_huff_decode terminates }

  { Compute lookahead tables to speed up decoding.
    First we set all the table entries to 0, indicating "too long";
    then we iterate through the Huffman codes that are short enough and
    fill in all the entries that correspond to bit sequences starting
    with that code. }

  MEMZERO(@dtbl^.look_nbits, SIZEOF(dtbl^.look_nbits));

  p := 0;
  for l := 1 to HUFF_LOOKAHEAD do
  begin
    for i := 1 to int (htbl^.bits[l]) do
    begin
      { l := current code's length, p := its index in huffcode[] & huffval[]. }
      { Generate left-justified code followed by all possible bit sequences }
      lookbits := huffcode[p] shl (HUFF_LOOKAHEAD-l);
      for ctr := pred(1 shl (HUFF_LOOKAHEAD-l)) downto 0 do
      begin
	dtbl^.look_nbits[lookbits] := l;
	dtbl^.look_sym[lookbits] := htbl^.huffval[p];
	Inc(lookbits);
      end;
      Inc(p);
    end;
  end;
end;


{ Out-of-line code for bit fetching (shared with jdphuff.c).
  See jdhuff.h for info about usage.
  Note: current values of get_buffer and bits_left are passed as parameters,
  but are returned in the corresponding fields of the state struct.

  On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  of get_buffer to be used.  (On machines with wider words, an even larger
  buffer could be used.)  However, on some machines 32-bit shifts are
  quite slow and take time proportional to the number of places shifted.
  (This is true with most PC compilers, for instance.)  In this case it may
  be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
  average shift distance at the cost of more calls to jpeg_fill_bit_buffer. }

{$ifdef SLOW_SHIFT_32}
const
  MIN_GET_BITS = 15;	{ minimum allowable value }
{$else}
const
  MIN_GET_BITS = (BIT_BUF_SIZE-7);
{$endif}


{GLOBAL}
function jpeg_fill_bit_buffer (var state : bitread_working_state;
		              {register} get_buffer : bit_buf_type;
                              {register} bits_left : int;
		              nbits  : int) : boolean;
label
  no_more_data;
{ Load up the bit buffer to a depth of at least nbits }
var
  { Copy heavily used state fields into locals (hopefully registers) }
  {register} next_input_byte : {const} JOCTETptr;
  {register} bytes_in_buffer : size_t;
  {register} c : int;
begin
  next_input_byte := state.next_input_byte;
  bytes_in_buffer := state.bytes_in_buffer;

  { Attempt to load at least MIN_GET_BITS bits into get_buffer. }
  { (It is assumed that no request will be for more than that many bits.) }

  while (bits_left < MIN_GET_BITS) do
  begin
    { Attempt to read a byte }
    if (state.unread_marker <> 0) then
      goto no_more_data;	{ can't advance past a marker }

    if (bytes_in_buffer = 0) then
    begin
      if (not state.cinfo^.src^.fill_input_buffer (state.cinfo)) then
      begin
	jpeg_fill_bit_buffer := FALSE;
        exit;
      end;
      next_input_byte := state.cinfo^.src^.next_input_byte;
      bytes_in_buffer := state.cinfo^.src^.bytes_in_buffer;
    end;
    Dec(bytes_in_buffer);
    c := GETJOCTET(next_input_byte^);
    Inc(next_input_byte);

    { If it's $FF, check and discard stuffed zero byte }
    if (c = $FF) then
    begin
      repeat
	if (bytes_in_buffer = 0) then
        begin
	  if (not state.cinfo^.src^.fill_input_buffer (state.cinfo)) then
          begin
	    jpeg_fill_bit_buffer := FALSE;
            exit;
          end;
	  next_input_byte := state.cinfo^.src^.next_input_byte;
	  bytes_in_buffer := state.cinfo^.src^.bytes_in_buffer;
	end;
	Dec(bytes_in_buffer);
	c := GETJOCTET(next_input_byte^);
        Inc(next_input_byte);
      Until (c <> $FF);

      if (c = 0) then
      begin
	{ Found FF/00, which represents an FF data byte }
	c := $FF;
      end
      else
      begin
	{ Oops, it's actually a marker indicating end of compressed data. }
	{ Better put it back for use later }
	state.unread_marker := c;

      no_more_data:
	{ There should be enough bits still left in the data segment; }
	{ if so, just break out of the outer while loop. }
	if (bits_left >= nbits) then
	  break;
	{ Uh-oh.  Report corrupted data to user and stuff zeroes into
	  the data stream, so that we can produce some kind of image.
	  Note that this code will be repeated for each byte demanded
	  for the rest of the segment.  We use a nonvolatile flag to ensure
	  that only one warning message appears. }

	if (not state.printed_eod_ptr^) then
        begin
	  WARNMS(j_common_ptr(state.cinfo), JWRN_HIT_MARKER);
	  state.printed_eod_ptr^ := TRUE;
	end;
	c := 0;			{ insert a zero byte into bit buffer }
      end;
    end;

    { OK, load c into get_buffer }
    get_buffer := (get_buffer shl 8) or c;
    Inc(bits_left, 8);
  end;

  { Unload the local registers }
  state.next_input_byte := next_input_byte;
  state.bytes_in_buffer := bytes_in_buffer;
  state.get_buffer := get_buffer;
  state.bits_left := bits_left;

  jpeg_fill_bit_buffer := TRUE;
end;


{ Out-of-line code for Huffman code decoding.
  See jdhuff.h for info about usage. }

{GLOBAL}
function jpeg_huff_decode (var state : bitread_working_state;
		          {register} get_buffer : bit_buf_type;
                          {register} bits_left : int;
		          htbl : d_derived_tbl_ptr;
                          min_bits : int) : int;
var
  {register} l : int;
  {register} code : INT32;
begin
  l := min_bits;

  { HUFF_DECODE has determined that the code is at least min_bits }
  { bits long, so fetch that many bits in one swoop. }

  {CHECK_BIT_BUFFER(state, l, return -1);}
  if (bits_left < l) then
  begin
    if (not jpeg_fill_bit_buffer(state, get_buffer, bits_left, l)) then
    begin
      jpeg_huff_decode := -1;
      exit;
    end;
    get_buffer := state.get_buffer;
    bits_left := state.bits_left;
  end;

  {code := GET_BITS(l);}
  Dec(bits_left, l);
  code := (int(get_buffer shr bits_left)) and ( pred(1 shl l) );

  { Collect the rest of the Huffman code one bit at a time. }
  { This is per Figure F.16 in the JPEG spec. }

  while (code > htbl^.maxcode[l]) do
  begin
    code := code shl 1;
    {CHECK_BIT_BUFFER(state, 1, return -1);}
    if (bits_left < 1) then
    begin
      if (not jpeg_fill_bit_buffer(state, get_buffer, bits_left, 1)) then
      begin
        jpeg_huff_decode := -1;
        exit;
      end;
      get_buffer := state.get_buffer;
      bits_left := state.bits_left;
    end;

    {code := code or GET_BITS(1);}
    Dec(bits_left);
    code := code or ( (int(get_buffer shr bits_left)) and pred(1 shl 1) );

    Inc(l);
  end;

  { Unload the local registers }
  state.get_buffer := get_buffer;
  state.bits_left := bits_left;

  { With garbage input we may reach the sentinel value l := 17. }

  if (l > 16) then
  begin
    WARNMS(j_common_ptr(state.cinfo), JWRN_HUFF_BAD_CODE);
    jpeg_huff_decode := 0;	{ fake a zero as the safest result }
    exit;
  end;

  jpeg_huff_decode := htbl^.pub^.huffval[ htbl^.valptr[l] +
			    ( int (code - htbl^.mincode[l])) ];
end;


{ Figure F.12: extend sign bit.
  On some machines, a shift and add will be faster than a table lookup. }

{$ifdef AVOID_TABLES}

#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))

{$else}

{$define HUFF_EXTEND(x,s)
  if (x < extend_test[s]) then
    := x + extend_offset[s]
  else
   x;}

const
  extend_test : array[0..16-1] of int =   { entry n is 2**(n-1) }
  ($0000, $0001, $0002, $0004, $0008, $0010, $0020, $0040,
   $0080, $0100, $0200, $0400, $0800, $1000, $2000, $4000);

const
  extend_offset : array[0..16-1] of int = { entry n is (-1 << n) + 1 }
(0, ((-1) shl 1) + 1, ((-1) shl 2) + 1, ((-1) shl 3) + 1, ((-1) shl 4) + 1,
    ((-1) shl 5) + 1, ((-1) shl 6) + 1, ((-1) shl 7) + 1, ((-1) shl 8) + 1,
    ((-1) shl 9) + 1, ((-1) shl 10) + 1, ((-1) shl 11) + 1,((-1) shl 12) + 1,
   ((-1) shl 13) + 1, ((-1) shl 14) + 1, ((-1) shl 15) + 1);

{$endif} { AVOID_TABLES }


{ Check for a restart marker & resynchronize decoder.
  Returns FALSE if must suspend. }

{LOCAL}
function process_restart (cinfo : j_decompress_ptr) : boolean;
var
  entropy : huff_entropy_ptr;
  ci : int;
begin
  entropy := huff_entropy_ptr (cinfo^.entropy);

  { Throw away any unused bits remaining in bit buffer; }
  { include any full bytes in next_marker's count of discarded bytes }
  Inc(cinfo^.marker^.discarded_bytes, entropy^.bitstate.bits_left div 8);
  entropy^.bitstate.bits_left := 0;

  { Advance past the RSTn marker }
  if (not cinfo^.marker^.read_restart_marker (cinfo)) then
  begin
    process_restart := FALSE;
    exit;
  end;

  { Re-initialize DC predictions to 0 }
  for ci := 0 to pred(cinfo^.comps_in_scan) do
    entropy^.saved.last_dc_val[ci] := 0;

  { Reset restart counter }
  entropy^.restarts_to_go := cinfo^.restart_interval;

  { Next segment can get another out-of-data warning }
  entropy^.bitstate.printed_eod := FALSE;

  process_restart := TRUE;
end;


{ Decode and return one MCU's worth of Huffman-compressed coefficients.
  The coefficients are reordered from zigzag order into natural array order,
  but are not dequantized.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -