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

📄 jdhuff.pas

📁 DELPHI版的JPEG文件解码源程序
💻 PAS
📖 第 1 页 / 共 3 页
字号:
  code : uInt;
var
  sym : int;
begin
  { Note that huffsize[] and huffcode[] are filled in code-length order,
    paralleling the order of the symbols themselves in htbl^.huffval[]. }

  { Find the input Huffman table }
  if (tblno < 0) or (tblno >= NUM_HUFF_TBLS) then
    ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, tblno);
  if isDC then
    htbl := cinfo^.dc_huff_tbl_ptrs[tblno]
  else
    htbl := cinfo^.ac_huff_tbl_ptrs[tblno];
  if (htbl = NIL) then
    ERREXIT1(j_common_ptr(cinfo), JERR_NO_HUFF_TABLE, tblno);

  { 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 }

  p := 0;
  for l := 1 to 16 do
  begin
    i := int(htbl^.bits[l]);
    if (i < 0) or (p + i > 256) then  { protect against table overrun }
      ERREXIT(j_common_ptr(cinfo), JERR_BAD_HUFF_TABLE);
    while (i > 0) do
    begin
      huffsize[p] := byte(l);
      Inc(p);
      Dec(i);
    end;
  end;
  huffsize[p] := 0;
  numsymbols := p;

  { Figure C.2: generate the codes themselves }
  { We also validate that the counts represent a legal Huffman code tree. }

  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 is now 1 more than the last code used for codelength si; but
      it must still fit in si bits, since no code is allowed to be all ones. }

    if (INT32(code) >= (INT32(1) shl si)) then
      ERREXIT(j_common_ptr(cinfo), JERR_BAD_HUFF_TABLE);

    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
      { valoffset[l] = huffval[] index of 1st symbol of code length l,
        minus the minimum code of length l }

      dtbl^.valoffset[l] := INT32(p) - INT32(huffcode[p]);
      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;

  { Validate symbols as being reasonable.
    For AC tables, we make no check, but accept all byte values 0..255.
    For DC tables, we require the symbols to be in range 0..15.
    (Tighter bounds could be applied depending on the data depth and mode,
    but this is sufficient to ensure safe decoding.) }

  if (isDC) then
  begin
    for i := 0 to pred(numsymbols) do
    begin
      sym := htbl^.huffval[i];
      if (sym < 0) or (sym > 15) then
	ERREXIT(j_common_ptr(cinfo), JERR_BAD_HUFF_TABLE);
    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_bytes;
{ 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;
var
  {register} c : int;
var
  cinfo : j_decompress_ptr;
begin
  next_input_byte := state.next_input_byte;
  bytes_in_buffer := state.bytes_in_buffer;
  cinfo := state.cinfo;

  { 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.) }
  { We fail to do so only if we hit a marker or are forced to suspend. }

  if (cinfo^.unread_marker = 0) then	{ cannot advance past a marker }
  begin
    while (bits_left < MIN_GET_BITS) do
    begin
      { Attempt to read a byte }
      if (bytes_in_buffer = 0) then
      begin
	if not cinfo^.src^.fill_input_buffer(cinfo) then
        begin
	  jpeg_fill_bit_buffer := FALSE;
          exit;
        end;
	next_input_byte := cinfo^.src^.next_input_byte;
	bytes_in_buffer := 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
        { Loop here to discard any padding FF's on terminating marker,
	  so that we can save a valid unread_marker value.  NOTE: we will
	  accept multiple FF's followed by a 0 as meaning a single FF data
	  byte.  This data pattern is not valid according to the standard. }

        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.
            Save the marker code for later use.
	    Fine point: it might appear that we should save the marker into
	    bitread working state, not straight into permanent state.  But
	    once we have hit a marker, we cannot need to suspend within the
	    current MCU, because we will read no more bytes from the data
	    source.  So it is OK to update permanent state right away. }

	  cinfo^.unread_marker := c;
          { See if we need to insert some fake zero bits. }
	  goto no_more_bytes;
	end;
      end;

      { OK, load c into get_buffer }
      get_buffer := (get_buffer shl 8) or c;
      Inc(bits_left, 8);
    end { end while }
  end
  else
  begin
  no_more_bytes:
    { We get here if we've read the marker that terminates the compressed
      data segment.  There should be enough bits in the buffer register
      to satisfy the request; if so, no problem. }

    if (nbits > bits_left) then
    begin
      { Uh-oh.  Report corrupted data to user and stuff zeroes into
        the data stream, so that we can produce some kind of image.
        We use a nonvolatile flag to ensure that only one warning message
        appears per data segment. }

      if not cinfo^.entropy^.insufficient_data then
      begin
	WARNMS(j_common_ptr(cinfo), JWRN_HIT_MARKER);
	cinfo^.entropy^.insufficient_data := TRUE;
      end;
      { Fill the buffer with zero bits }
      get_buffer := get_buffer shl (MIN_GET_BITS - bits_left);
      bits_left := MIN_GET_BITS;
    end;
  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[ int (code + htbl^.valoffset[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; }

⌨️ 快捷键说明

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