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

📄 jmemmgr.pas

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

{ This file contains the JPEG system-independent memory management
  routines.  This code is usable across a wide variety of machines; most
  of the system dependencies have been isolated in a separate file.
  The major functions provided here are:
    * pool-based allocation and freeing of memory;
    * policy decisions about how to divide available memory among the
      virtual arrays;
    * control logic for swapping virtual arrays between main memory and
      backing storage.
  The separate system-dependent file provides the actual backing-storage
  access code, and it contains the policy decision about how much total
  main memory to use.
  This file is system-dependent in the sense that some of its functions
  are unnecessary in some systems.  For example, if there is enough virtual
  memory so that backing storage will never be used, much of the virtual
  array control logic could be removed.  (Of course, if you have that much
  memory then you shouldn't care about a little bit of unused code...) }

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

interface

{$I jconfig.inc}

uses
   jmorecfg,
   jinclude,
   jdeferr,
   jerror,
   jpeglib,
   jutils,
{$IFDEF VER70}
{$ifndef NO_GETENV}
   Dos,                 	{ DOS unit should declare getenv() }
                                { function GetEnv(name : string) : string; }
{$endif}
   jmemdos;                     { import the system-dependent declarations }
{$ELSE}
   jmemnobs;
  {$DEFINE NO_GETENV}
{$ENDIF}

{ Memory manager initialization.
  When this is called, only the error manager pointer is valid in cinfo! }

{GLOBAL}
procedure jinit_memory_mgr (cinfo : j_common_ptr);

implementation


{ Some important notes:
    The allocation routines provided here must never return NIL.
    They should exit to error_exit if unsuccessful.

    It's not a good idea to try to merge the sarray and barray routines,
    even though they are textually almost the same, because samples are
    usually stored as bytes while coefficients are shorts or ints.  Thus,
    in machines where byte pointers have a different representation from
    word pointers, the resulting machine code could not be the same.  }


{ Many machines require storage alignment: longs must start on 4-byte
  boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
  always returns pointers that are multiples of the worst-case alignment
  requirement, and we had better do so too.
  There isn't any really portable way to determine the worst-case alignment
  requirement.  This module assumes that the alignment requirement is
  multiples of sizeof(ALIGN_TYPE).
  By default, we define ALIGN_TYPE as double.  This is necessary on some
  workstations (where doubles really do need 8-byte alignment) and will work
  fine on nearly everything.  If your machine has lesser alignment needs,
  you can save a few bytes by making ALIGN_TYPE smaller.
  The only place I know of where this will NOT work is certain Macintosh
  680x0 compilers that define double as a 10-byte IEEE extended float.
  Doing 10-byte alignment is counterproductive because longwords won't be
  aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
  such a compiler. }

{$ifndef ALIGN_TYPE} { so can override from jconfig.h }
type
  ALIGN_TYPE = double;
{$endif}


{ We allocate objects from "pools", where each pool is gotten with a single
  request to jpeg_get_small() or jpeg_get_large().  There is no per-object
  overhead within a pool, except for alignment padding.  Each pool has a
  header with a link to the next pool of the same class.
  Small and large pool headers are identical except that the latter's
  link pointer must be FAR on 80x86 machines.
  Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  of the alignment requirement of ALIGN_TYPE. }

type
  small_pool_ptr = ^small_pool_hdr;
  small_pool_hdr = record
  case byte of
    0:(hdr : record
               next : small_pool_ptr;   { next in list of pools }
               bytes_used : size_t;     { how many bytes already used within pool }
               bytes_left : size_t;     { bytes still available in this pool }
             end);
    1:(dummy : ALIGN_TYPE);             { included in union to ensure alignment }
  end; {small_pool_hdr;}

type
  large_pool_ptr = ^large_pool_hdr; {FAR}
  large_pool_hdr = record
  case byte of
    0:(hdr : record
               next : large_pool_ptr;   { next in list of pools }
               bytes_used : size_t;     { how many bytes already used within pool }
               bytes_left : size_t;     { bytes still available in this pool }
             end);
    1:(dummy : ALIGN_TYPE);             { included in union to ensure alignment }
  end; {large_pool_hdr;}


{ Here is the full definition of a memory manager object. }

type
  my_mem_ptr = ^my_memory_mgr;
  my_memory_mgr = record
    pub : jpeg_memory_mgr;	{ public fields }

    { Each pool identifier (lifetime class) names a linked list of pools. }
    small_list : array[0..JPOOL_NUMPOOLS-1] of small_pool_ptr ;
    large_list : array[0..JPOOL_NUMPOOLS-1] of large_pool_ptr ;

    { Since we only have one lifetime class of virtual arrays, only one
      linked list is necessary (for each datatype).  Note that the virtual
      array control blocks being linked together are actually stored somewhere
      in the small-pool list. }

    virt_sarray_list : jvirt_sarray_ptr;
    virt_barray_list : jvirt_barray_ptr;

    { This counts total space obtained from jpeg_get_small/large }
    total_space_allocated : long;

    { alloc_sarray and alloc_barray set this value for use by virtual
      array routines. }

    last_rowsperchunk : JDIMENSION;	{ from most recent alloc_sarray/barray }
  end; {my_memory_mgr;}

  {$ifndef AM_MEMORY_MANAGER}	{ only jmemmgr.c defines these }

{ The control blocks for virtual arrays.
  Note that these blocks are allocated in the "small" pool area.
  System-dependent info for the associated backing store (if any) is hidden
  inside the backing_store_info struct. }
type
  jvirt_sarray_control = record
    mem_buffer : JSAMPARRAY;	{ => the in-memory buffer }
    rows_in_array : JDIMENSION;	{ total virtual array height }
    samplesperrow : JDIMENSION;	{ width of array (and of memory buffer) }
    maxaccess : JDIMENSION;	{ max rows accessed by access_virt_sarray }
    rows_in_mem : JDIMENSION;	{ height of memory buffer }
    rowsperchunk : JDIMENSION;	{ allocation chunk size in mem_buffer }
    cur_start_row : JDIMENSION;	{ first logical row # in the buffer }
    first_undef_row : JDIMENSION;	{ row # of first uninitialized row }
    pre_zero : boolean;		{ pre-zero mode requested? }
    dirty : boolean;		{ do current buffer contents need written? }
    b_s_open : boolean;		{ is backing-store data valid? }
    next : jvirt_sarray_ptr;	{ link to next virtual sarray control block }
    b_s_info : backing_store_info;	{ System-dependent control info }
  end;

  jvirt_barray_control = record
    mem_buffer : JBLOCKARRAY;	{ => the in-memory buffer }
    rows_in_array : JDIMENSION;	{ total virtual array height }
    blocksperrow : JDIMENSION;	{ width of array (and of memory buffer) }
    maxaccess : JDIMENSION;	{ max rows accessed by access_virt_barray }
    rows_in_mem : JDIMENSION;	{ height of memory buffer }
    rowsperchunk : JDIMENSION;	{ allocation chunk size in mem_buffer }
    cur_start_row : JDIMENSION;	{ first logical row # in the buffer }
    first_undef_row : JDIMENSION;	{ row # of first uninitialized row }
    pre_zero : boolean;		{ pre-zero mode requested? }
    dirty : boolean;		{ do current buffer contents need written? }
    b_s_open : boolean;		{ is backing-store data valid? }
    next : jvirt_barray_ptr;	{ link to next virtual barray control block }
    b_s_info : backing_store_info;	{ System-dependent control info }
  end;
  {$endif}  { AM_MEMORY_MANAGER}

{$ifdef MEM_STATS}      	{ optional extra stuff for statistics }

{LOCAL}
procedure print_mem_stats (cinfo : j_common_ptr; pool_id : int);
var
  mem : my_mem_ptr;
  shdr_ptr : small_pool_ptr;
  lhdr_ptr : large_pool_ptr;
begin
  mem := my_mem_ptr (cinfo^.mem);

  { Since this is only a debugging stub, we can cheat a little by using
    fprintf directly rather than going through the trace message code.
    This is helpful because message parm array can't handle longs. }

  WriteLn(output, 'Freeing pool ', pool_id,', total space := ',
	   mem^.total_space_allocated);

  lhdr_ptr := mem^.large_list[pool_id];
  while (lhdr_ptr <> NIL) do
  begin
    WriteLn(output, '  Large chunk used ',
	    long (lhdr_ptr^.hdr.bytes_used));
    lhdr_ptr := lhdr_ptr^.hdr.next;
  end;

  shdr_ptr := mem^.small_list[pool_id];

  while (shdr_ptr <> NIL) do
  begin
    WriteLn(output, '  Small chunk used ',
                    long (shdr_ptr^.hdr.bytes_used), ' free ',
                    long (shdr_ptr^.hdr.bytes_left) );
    shdr_ptr := shdr_ptr^.hdr.next;
  end;
end;

{$endif} { MEM_STATS }


{LOCAL}
procedure out_of_memory (cinfo : j_common_ptr; which : int);
{ Report an out-of-memory error and stop execution }
{ If we compiled MEM_STATS support, report alloc requests before dying }
begin
{$ifdef MEM_STATS}
  cinfo^.err^.trace_level := 2;	{ force self_destruct to report stats }
{$endif}
  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
end;


{ Allocation of "small" objects.

  For these, we use pooled storage.  When a new pool must be created,
  we try to get enough space for the current request plus a "slop" factor,
  where the slop will be the amount of leftover space in the new pool.
  The speed vs. space tradeoff is largely determined by the slop values.
  A different slop value is provided for each pool class (lifetime),
  and we also distinguish the first pool of a class from later ones.
  NOTE: the values given work fairly well on both 16- and 32-bit-int
  machines, but may be too small if longs are 64 bits or more. }

const
  first_pool_slop : array[0..JPOOL_NUMPOOLS-1] of size_t  =
	(1600,			{ first PERMANENT pool }
	16000);			{ first IMAGE pool }

const
  extra_pool_slop : array[0..JPOOL_NUMPOOLS-1] of size_t =
	(0,			{ additional PERMANENT pools }
	5000);			{ additional IMAGE pools }

const
  MIN_SLOP = 50;		{ greater than 0 to avoid futile looping }


{METHODDEF}
function alloc_small (cinfo : j_common_ptr;
                      pool_id : int;
                      sizeofobject : size_t) : pointer; far;
type
  byteptr = ^byte;
{ Allocate a "small" object }
var
  mem : my_mem_ptr;
  hdr_ptr, prev_hdr_ptr : small_pool_ptr;
  data_ptr : byteptr;
  odd_bytes, min_request, slop : size_t;
begin
  mem := my_mem_ptr (cinfo^.mem);

  { Check for unsatisfiable request (do now to ensure no overflow below) }
  if (sizeofobject > size_t(MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr))) then
    out_of_memory(cinfo, 1);	{ request exceeds malloc's ability }

  { Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) }
  odd_bytes := sizeofobject mod SIZEOF(ALIGN_TYPE);
  if (odd_bytes > 0) then
    Inc(sizeofobject, SIZEOF(ALIGN_TYPE) - odd_bytes);

  { See if space is available in any existing pool }
  if (pool_id < 0) or (pool_id >= JPOOL_NUMPOOLS) then
    ERREXIT1(j_common_ptr(cinfo), JERR_BAD_POOL_ID, pool_id);	{ safety check }
  prev_hdr_ptr := NIL;
  hdr_ptr := mem^.small_list[pool_id];
  while (hdr_ptr <> NIL) do
  begin
    if (hdr_ptr^.hdr.bytes_left >= sizeofobject) then
      break;			{ found pool with enough space }
    prev_hdr_ptr := hdr_ptr;
    hdr_ptr := hdr_ptr^.hdr.next;
  end;

  { Time to make a new pool? }
  if (hdr_ptr = NIL) then
  begin
    { min_request is what we need now, slop is what will be leftover }
    min_request := sizeofobject + SIZEOF(small_pool_hdr);
    if (prev_hdr_ptr = NIL) then	{ first pool in class? }
      slop := first_pool_slop[pool_id]
    else
      slop := extra_pool_slop[pool_id];
    { Don't ask for more than MAX_ALLOC_CHUNK }
    if (slop > size_t (MAX_ALLOC_CHUNK-min_request)) then
      slop := size_t (MAX_ALLOC_CHUNK-min_request);
    { Try to get space, if fail reduce slop and try again }
    while TRUE do
    begin
      hdr_ptr := small_pool_ptr(jpeg_get_small(cinfo, min_request + slop));
      if (hdr_ptr <> NIL) then

⌨️ 快捷键说明

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