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

📄 jdhuff.pas

📁 DELPHI版的JPEG文件解码源程序
💻 PAS
📖 第 1 页 / 共 3 页
字号:
Unit JdHuff;

{ This file contains declarations for Huffman entropy decoding routines
  that are shared between the sequential decoder (jdhuff.c) and the
  progressive decoder (jdphuff.c).  No other modules need to see these. }

{ This file contains Huffman entropy decoding routines.

  Much of the complexity here has to do with supporting input suspension.
  If the data source module demands suspension, we want to be able to back
  up to the start of the current MCU.  To do this, we copy state variables
  into local working storage, and update them back to the permanent
  storage only upon successful completion of an MCU. }

{ Original: jdhuff.h+jdhuff.c;  Copyright (C) 1991-1997, Thomas G. Lane. }



interface

{$I jconfig.inc}

uses
  jmorecfg,
  jinclude,
  jdeferr,
  jerror,
  jutils,
  jpeglib;


{ Declarations shared with jdphuff.c }



{ Derived data constructed for each Huffman table }

const
  HUFF_LOOKAHEAD  = 8;          { # of bits of lookahead }

type
  d_derived_tbl_ptr = ^d_derived_tbl;
  d_derived_tbl = record
    { Basic tables: (element [0] of each array is unused) }
    maxcode : array[0..18-1] of INT32;       { largest code of length k (-1 if none) }
    { (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) }
    valoffset : array[0..17-1] of INT32;     { huffval[] offset for codes of length k }
    { valoffset[k] = huffval[] index of 1st symbol of code length k, less
      the smallest code of length k; so given a code of length k, the
      corresponding symbol is huffval[code + valoffset[k]] }

    { Link to public Huffman table (needed only in jpeg_huff_decode) }
    pub : JHUFF_TBL_PTR;

    { Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
      the input data stream.  If the next Huffman code is no more
      than HUFF_LOOKAHEAD bits long, we can obtain its length and
      the corresponding symbol directly from these tables. }

    look_nbits : array[0..(1 shl HUFF_LOOKAHEAD)-1] of int;
                                { # bits, or 0 if too long }
    look_sym : array[0..(1 shl HUFF_LOOKAHEAD)-1] of UINT8;
                                { symbol, or unused }
  end;

{ Fetching the next N bits from the input stream is a time-critical operation
  for the Huffman decoders.  We implement it with a combination of inline
  macros and out-of-line subroutines.  Note that N (the number of bits
  demanded at one time) never exceeds 15 for JPEG use.

  We read source bytes into get_buffer and dole out bits as needed.
  If get_buffer already contains enough bits, they are fetched in-line
  by the macros CHECK_BIT_BUFFER and GET_BITS.  When there aren't enough
  bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  as full as possible (not just to the number of bits needed; this
  prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  at least the requested number of bits --- dummy zeroes are inserted if
  necessary. }


type
  bit_buf_type = INT32 ;        { type of bit-extraction buffer }
const
  BIT_BUF_SIZE = 32;            { size of buffer in bits }

{ If long is > 32 bits on your machine, and shifting/masking longs is
  reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  appropriately should be a win.  Unfortunately we can't define the size
  with something like  #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  because not all machines measure sizeof in 8-bit bytes. }

type
  bitread_perm_state = record   { Bitreading state saved across MCUs }
    get_buffer : bit_buf_type;  { current bit-extraction buffer }
    bits_left : int;            { # of unused bits in it }
  end;

type
  bitread_working_state = record
    { Bitreading working state within an MCU }
    { current data source location }
    { We need a copy, rather than munging the original, in case of suspension }
    next_input_byte : JOCTETptr;  { => next byte to read from source }
    bytes_in_buffer : size_t;     { # of bytes remaining in source buffer }
    { Bit input buffer --- note these values are kept in register variables,
      not in this struct, inside the inner loops. }

    get_buffer : bit_buf_type;  { current bit-extraction buffer }
    bits_left : int;            { # of unused bits in it }
    { Pointer needed by jpeg_fill_bit_buffer }
    cinfo : j_decompress_ptr;   { back link to decompress master record }
  end;

{ Module initialization routine for Huffman entropy decoding. }

{GLOBAL}
procedure jinit_huff_decoder (cinfo : j_decompress_ptr);

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

{ Compute the derived values for a Huffman table.
  Note this is also used by jdphuff.c. }

{GLOBAL}
procedure jpeg_make_d_derived_tbl (cinfo : j_decompress_ptr;
                                   isDC : boolean;
                                   tblno : int;
			           var pdtbl : d_derived_tbl_ptr);

{ Load up the bit buffer to a depth of at least nbits }

function jpeg_fill_bit_buffer	(var state : bitread_working_state;
                                 get_buffer : bit_buf_type;  {register}
	                         bits_left : int; {register}
                                 nbits : int) : boolean;

implementation

{$IFDEF MACRO}

{ Macros to declare and load/save bitread local variables. }
{$define BITREAD_STATE_VARS}
	get_buffer : bit_buf_type ; {register}
	bits_left : int; {register}
	br_state : bitread_working_state;

{$define BITREAD_LOAD_STATE(cinfop,permstate)}
	br_state.cinfo := cinfop;
	br_state.next_input_byte := cinfop^.src^.next_input_byte;
	br_state.bytes_in_buffer := cinfop^.src^.bytes_in_buffer;
	get_buffer := permstate.get_buffer;
	bits_left := permstate.bits_left;

{$define BITREAD_SAVE_STATE(cinfop,permstate) }
	cinfop^.src^.next_input_byte := br_state.next_input_byte;
	cinfop^.src^.bytes_in_buffer := br_state.bytes_in_buffer;
	permstate.get_buffer := get_buffer;
	permstate.bits_left := bits_left;


{ These macros provide the in-line portion of bit fetching.
  Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  before using GET_BITS, PEEK_BITS, or DROP_BITS.
  The variables get_buffer and bits_left are assumed to be locals,
  but the state struct might not be (jpeg_huff_decode needs this).
 	CHECK_BIT_BUFFER(state,n,action);
 		Ensure there are N bits in get_buffer; if suspend, take action.
       val = GET_BITS(n);
 		Fetch next N bits.
       val = PEEK_BITS(n);
 		Fetch next N bits without removing them from the buffer.
 	DROP_BITS(n);
 		Discard next N bits.
  The value N should be a simple variable, not an expression, because it
  is evaluated multiple times. }


{$define CHECK_BIT_BUFFER(state,nbits,action)}
  if (bits_left < (nbits)) then
  begin
    if (not jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) then
    begin
      action;
      exit;
    end;
    get_buffer := state.get_buffer;
    bits_left := state.bits_left;
  end;


{$define GET_BITS(nbits)}
	Dec(bits_left, (nbits));
	( (int(get_buffer shr bits_left)) and ( pred(1 shl (nbits)) ) )

{$define PEEK_BITS(nbits)}
	int(get_buffer shr (bits_left -  (nbits))) and pred(1 shl (nbits))

{$define DROP_BITS(nbits)}
	Dec(bits_left, nbits);




{ Code for extracting next Huffman-coded symbol from input bit stream.
  Again, this is time-critical and we make the main paths be macros.

  We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  without looping.  Usually, more than 95% of the Huffman codes will be 8
  or fewer bits long.  The few overlength codes are handled with a loop,
  which need not be inline code.

  Notes about the HUFF_DECODE macro:
  1. Near the end of the data segment, we may fail to get enough bits
     for a lookahead.  In that case, we do it the hard way.
  2. If the lookahead table contains no entry, the next code must be
     more than HUFF_LOOKAHEAD bits long.
  3. jpeg_huff_decode returns -1 if forced to suspend. }




macro HUFF_DECODE(s,br_state,htbl,return FALSE,slowlabel);
label showlabel;
var
 nb, look : int; {register}
begin
  if (bits_left < HUFF_LOOKAHEAD) then
  begin
    if (not jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) then
    begin
      decode_mcu := FALSE;
      exit;
    end;
    get_buffer := br_state.get_buffer;
    bits_left := br_state.bits_left;
    if (bits_left < HUFF_LOOKAHEAD) then
    begin
      nb := 1;
      goto slowlabel;
    end;
  end;
  {look := PEEK_BITS(HUFF_LOOKAHEAD);}
  look := int(get_buffer shr (bits_left -  HUFF_LOOKAHEAD)) and
                 pred(1 shl HUFF_LOOKAHEAD);

  nb := htbl^.look_nbits[look];
  if (nb <> 0) then
  begin
    {DROP_BITS(nb);}
    Dec(bits_left, nb);

    s := htbl^.look_sym[look];
  end
  else
  begin
    nb := HUFF_LOOKAHEAD+1;
slowlabel:
    s := jpeg_huff_decode(br_state,get_buffer,bits_left,htbl,nb));
    if (s < 0) then
    begin
      result := FALSE;
      exit;
    end;
    get_buffer := br_state.get_buffer;
    bits_left := br_state.bits_left;
  end;
end;


{$ENDIF} {MACRO}

{ Expanded entropy decoder object for Huffman decoding.

  The savable_state subrecord contains fields that change within an MCU,
  but must not be updated permanently until we complete the MCU. }

type
  savable_state = record
    last_dc_val : array[0..MAX_COMPS_IN_SCAN-1] of int; { last DC coef for each component }
  end;


type
  huff_entropy_ptr = ^huff_entropy_decoder;
  huff_entropy_decoder = record
    pub : jpeg_entropy_decoder; { public fields }

    { These fields are loaded into local variables at start of each MCU.
      In case of suspension, we exit WITHOUT updating them. }

    bitstate : bitread_perm_state;	{ Bit buffer at start of MCU }
    saved : savable_state;		{ Other state at start of MCU }

    { These fields are NOT loaded into local working state. }
    restarts_to_go : uInt;              { MCUs left in this restart interval }

    { Pointers to derived tables (these workspaces have image lifespan) }
    dc_derived_tbls : array[0..NUM_HUFF_TBLS] of d_derived_tbl_ptr;
    ac_derived_tbls : array[0..NUM_HUFF_TBLS] of d_derived_tbl_ptr;

    { Precalculated info set up by start_pass for use in decode_mcu: }

    { Pointers to derived tables to be used for each block within an MCU }
    dc_cur_tbls : array[0..D_MAX_BLOCKS_IN_MCU-1] of d_derived_tbl_ptr;
    ac_cur_tbls : array[0..D_MAX_BLOCKS_IN_MCU-1] of d_derived_tbl_ptr;
    { Whether we care about the DC and AC coefficient values for each block }
    dc_needed : array[0..D_MAX_BLOCKS_IN_MCU-1] of boolean;
    ac_needed : array[0..D_MAX_BLOCKS_IN_MCU-1] of boolean;
  end;



{ Initialize for a Huffman-compressed scan. }

{METHODDEF}
procedure start_pass_huff_decoder (cinfo : j_decompress_ptr); far;
var
  entropy : huff_entropy_ptr;
  ci, blkn, dctbl, actbl : int;
  compptr : jpeg_component_info_ptr;
begin
  entropy := huff_entropy_ptr (cinfo^.entropy);

  { Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
    This ought to be an error condition, but we make it a warning because
    there are some baseline files out there with all zeroes in these bytes. }

  if (cinfo^.Ss <> 0) or (cinfo^.Se <> DCTSIZE2-1) or
     (cinfo^.Ah <> 0) or (cinfo^.Al <> 0) then
    WARNMS(j_common_ptr(cinfo), JWRN_NOT_SEQUENTIAL);

  for ci := 0 to pred(cinfo^.comps_in_scan) do
  begin
    compptr := cinfo^.cur_comp_info[ci];
    dctbl := compptr^.dc_tbl_no;
    actbl := compptr^.ac_tbl_no;
    { Compute derived values for Huffman tables }
    { We may do this more than once for a table, but it's not expensive }
    jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
			    entropy^.dc_derived_tbls[dctbl]);
    jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
			    entropy^.ac_derived_tbls[actbl]);
    { Initialize DC predictions to 0 }
    entropy^.saved.last_dc_val[ci] := 0;
  end;

  { Precalculate decoding info for each block in an MCU of this scan }
  for blkn := 0 to pred(cinfo^.blocks_in_MCU) do
  begin
    ci := cinfo^.MCU_membership[blkn];
    compptr := cinfo^.cur_comp_info[ci];
    { Precalculate which table to use for each block }
    entropy^.dc_cur_tbls[blkn] := entropy^.dc_derived_tbls[compptr^.dc_tbl_no];
    entropy^.ac_cur_tbls[blkn] := entropy^.ac_derived_tbls[compptr^.ac_tbl_no];
    { Decide whether we really care about the coefficient values }
    if (compptr^.component_needed) then
    begin
      entropy^.dc_needed[blkn] := TRUE;
      { we don't need the ACs if producing a 1/8th-size image }
      entropy^.ac_needed[blkn] := (compptr^.DCT_scaled_size > 1);
    end
    else
    begin
      entropy^.ac_needed[blkn] := FALSE;
      entropy^.dc_needed[blkn] := FALSE;
    end;
  end;

  { Initialize bitread state variables }
  entropy^.bitstate.bits_left := 0;
  entropy^.bitstate.get_buffer := 0; { unnecessary, but keeps Purify quiet }
  entropy^.pub.insufficient_data := FALSE;

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


{ Compute the derived values for a Huffman table.
  This routine also performs some validation checks on the table.

  Note this is also used by jdphuff.c. }

{GLOBAL}
procedure jpeg_make_d_derived_tbl (cinfo : j_decompress_ptr;
                                   isDC : boolean;
                                   tblno : int;
	                           var pdtbl : d_derived_tbl_ptr);
var
  htbl : JHUFF_TBL_PTR;
  dtbl : d_derived_tbl_ptr;
  p, i, l, si, numsymbols : int;
  lookbits, ctr : int;
  huffsize : array[0..257-1] of byte;
  huffcode : array[0..257-1] of uInt;

⌨️ 快捷键说明

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