kusano 7d535a
/*
kusano 7d535a
 * jmemmgr.c
kusano 7d535a
 *
kusano 7d535a
 * Copyright (C) 1991-1997, Thomas G. Lane.
kusano 7d535a
 * Modified 2011-2012 by Guido Vollbeding.
kusano 7d535a
 * This file is part of the Independent JPEG Group's software.
kusano 7d535a
 * For conditions of distribution and use, see the accompanying README file.
kusano 7d535a
 *
kusano 7d535a
 * This file contains the JPEG system-independent memory management
kusano 7d535a
 * routines.  This code is usable across a wide variety of machines; most
kusano 7d535a
 * of the system dependencies have been isolated in a separate file.
kusano 7d535a
 * The major functions provided here are:
kusano 7d535a
 *   * pool-based allocation and freeing of memory;
kusano 7d535a
 *   * policy decisions about how to divide available memory among the
kusano 7d535a
 *     virtual arrays;
kusano 7d535a
 *   * control logic for swapping virtual arrays between main memory and
kusano 7d535a
 *     backing storage.
kusano 7d535a
 * The separate system-dependent file provides the actual backing-storage
kusano 7d535a
 * access code, and it contains the policy decision about how much total
kusano 7d535a
 * main memory to use.
kusano 7d535a
 * This file is system-dependent in the sense that some of its functions
kusano 7d535a
 * are unnecessary in some systems.  For example, if there is enough virtual
kusano 7d535a
 * memory so that backing storage will never be used, much of the virtual
kusano 7d535a
 * array control logic could be removed.  (Of course, if you have that much
kusano 7d535a
 * memory then you shouldn't care about a little bit of unused code...)
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#define JPEG_INTERNALS
kusano 7d535a
#define AM_MEMORY_MANAGER	/* we define jvirt_Xarray_control structs */
kusano 7d535a
#include "jinclude.h"
kusano 7d535a
#include "jpeglib.h"
kusano 7d535a
#include "jmemsys.h"		/* import the system-dependent declarations */
kusano 7d535a
kusano 7d535a
#ifndef NO_GETENV
kusano 7d535a
#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare getenv() */</stdlib.h>
kusano 7d535a
extern char * getenv JPP((const char * name));
kusano 7d535a
#endif
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Some important notes:
kusano 7d535a
 *   The allocation routines provided here must never return NULL.
kusano 7d535a
 *   They should exit to error_exit if unsuccessful.
kusano 7d535a
 *
kusano 7d535a
 *   It's not a good idea to try to merge the sarray and barray routines,
kusano 7d535a
 *   even though they are textually almost the same, because samples are
kusano 7d535a
 *   usually stored as bytes while coefficients are shorts or ints.  Thus,
kusano 7d535a
 *   in machines where byte pointers have a different representation from
kusano 7d535a
 *   word pointers, the resulting machine code could not be the same.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Many machines require storage alignment: longs must start on 4-byte
kusano 7d535a
 * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
kusano 7d535a
 * always returns pointers that are multiples of the worst-case alignment
kusano 7d535a
 * requirement, and we had better do so too.
kusano 7d535a
 * There isn't any really portable way to determine the worst-case alignment
kusano 7d535a
 * requirement.  This module assumes that the alignment requirement is
kusano 7d535a
 * multiples of sizeof(ALIGN_TYPE).
kusano 7d535a
 * By default, we define ALIGN_TYPE as double.  This is necessary on some
kusano 7d535a
 * workstations (where doubles really do need 8-byte alignment) and will work
kusano 7d535a
 * fine on nearly everything.  If your machine has lesser alignment needs,
kusano 7d535a
 * you can save a few bytes by making ALIGN_TYPE smaller.
kusano 7d535a
 * The only place I know of where this will NOT work is certain Macintosh
kusano 7d535a
 * 680x0 compilers that define double as a 10-byte IEEE extended float.
kusano 7d535a
 * Doing 10-byte alignment is counterproductive because longwords won't be
kusano 7d535a
 * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
kusano 7d535a
 * such a compiler.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#ifndef ALIGN_TYPE		/* so can override from jconfig.h */
kusano 7d535a
#define ALIGN_TYPE  double
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * We allocate objects from "pools", where each pool is gotten with a single
kusano 7d535a
 * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
kusano 7d535a
 * overhead within a pool, except for alignment padding.  Each pool has a
kusano 7d535a
 * header with a link to the next pool of the same class.
kusano 7d535a
 * Small and large pool headers are identical except that the latter's
kusano 7d535a
 * link pointer must be FAR on 80x86 machines.
kusano 7d535a
 * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
kusano 7d535a
 * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
kusano 7d535a
 * of the alignment requirement of ALIGN_TYPE.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
typedef union small_pool_struct * small_pool_ptr;
kusano 7d535a
kusano 7d535a
typedef union small_pool_struct {
kusano 7d535a
  struct {
kusano 7d535a
    small_pool_ptr next;	/* next in list of pools */
kusano 7d535a
    size_t bytes_used;		/* how many bytes already used within pool */
kusano 7d535a
    size_t bytes_left;		/* bytes still available in this pool */
kusano 7d535a
  } hdr;
kusano 7d535a
  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
kusano 7d535a
} small_pool_hdr;
kusano 7d535a
kusano 7d535a
typedef union large_pool_struct FAR * large_pool_ptr;
kusano 7d535a
kusano 7d535a
typedef union large_pool_struct {
kusano 7d535a
  struct {
kusano 7d535a
    large_pool_ptr next;	/* next in list of pools */
kusano 7d535a
    size_t bytes_used;		/* how many bytes already used within pool */
kusano 7d535a
    size_t bytes_left;		/* bytes still available in this pool */
kusano 7d535a
  } hdr;
kusano 7d535a
  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
kusano 7d535a
} large_pool_hdr;
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Here is the full definition of a memory manager object.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
typedef struct {
kusano 7d535a
  struct jpeg_memory_mgr pub;	/* public fields */
kusano 7d535a
kusano 7d535a
  /* Each pool identifier (lifetime class) names a linked list of pools. */
kusano 7d535a
  small_pool_ptr small_list[JPOOL_NUMPOOLS];
kusano 7d535a
  large_pool_ptr large_list[JPOOL_NUMPOOLS];
kusano 7d535a
kusano 7d535a
  /* Since we only have one lifetime class of virtual arrays, only one
kusano 7d535a
   * linked list is necessary (for each datatype).  Note that the virtual
kusano 7d535a
   * array control blocks being linked together are actually stored somewhere
kusano 7d535a
   * in the small-pool list.
kusano 7d535a
   */
kusano 7d535a
  jvirt_sarray_ptr virt_sarray_list;
kusano 7d535a
  jvirt_barray_ptr virt_barray_list;
kusano 7d535a
kusano 7d535a
  /* This counts total space obtained from jpeg_get_small/large */
kusano 7d535a
  long total_space_allocated;
kusano 7d535a
kusano 7d535a
  /* alloc_sarray and alloc_barray set this value for use by virtual
kusano 7d535a
   * array routines.
kusano 7d535a
   */
kusano 7d535a
  JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
kusano 7d535a
} my_memory_mgr;
kusano 7d535a
kusano 7d535a
typedef my_memory_mgr * my_mem_ptr;
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * The control blocks for virtual arrays.
kusano 7d535a
 * Note that these blocks are allocated in the "small" pool area.
kusano 7d535a
 * System-dependent info for the associated backing store (if any) is hidden
kusano 7d535a
 * inside the backing_store_info struct.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
struct jvirt_sarray_control {
kusano 7d535a
  JSAMPARRAY mem_buffer;	/* => the in-memory buffer */
kusano 7d535a
  JDIMENSION rows_in_array;	/* total virtual array height */
kusano 7d535a
  JDIMENSION samplesperrow;	/* width of array (and of memory buffer) */
kusano 7d535a
  JDIMENSION maxaccess;		/* max rows accessed by access_virt_sarray */
kusano 7d535a
  JDIMENSION rows_in_mem;	/* height of memory buffer */
kusano 7d535a
  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
kusano 7d535a
  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
kusano 7d535a
  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
kusano 7d535a
  boolean pre_zero;		/* pre-zero mode requested? */
kusano 7d535a
  boolean dirty;		/* do current buffer contents need written? */
kusano 7d535a
  boolean b_s_open;		/* is backing-store data valid? */
kusano 7d535a
  jvirt_sarray_ptr next;	/* link to next virtual sarray control block */
kusano 7d535a
  backing_store_info b_s_info;	/* System-dependent control info */
kusano 7d535a
};
kusano 7d535a
kusano 7d535a
struct jvirt_barray_control {
kusano 7d535a
  JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
kusano 7d535a
  JDIMENSION rows_in_array;	/* total virtual array height */
kusano 7d535a
  JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
kusano 7d535a
  JDIMENSION maxaccess;		/* max rows accessed by access_virt_barray */
kusano 7d535a
  JDIMENSION rows_in_mem;	/* height of memory buffer */
kusano 7d535a
  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
kusano 7d535a
  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
kusano 7d535a
  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
kusano 7d535a
  boolean pre_zero;		/* pre-zero mode requested? */
kusano 7d535a
  boolean dirty;		/* do current buffer contents need written? */
kusano 7d535a
  boolean b_s_open;		/* is backing-store data valid? */
kusano 7d535a
  jvirt_barray_ptr next;	/* link to next virtual barray control block */
kusano 7d535a
  backing_store_info b_s_info;	/* System-dependent control info */
kusano 7d535a
};
kusano 7d535a
kusano 7d535a
kusano 7d535a
#ifdef MEM_STATS		/* optional extra stuff for statistics */
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
print_mem_stats (j_common_ptr cinfo, int pool_id)
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  small_pool_ptr shdr_ptr;
kusano 7d535a
  large_pool_ptr lhdr_ptr;
kusano 7d535a
kusano 7d535a
  /* Since this is only a debugging stub, we can cheat a little by using
kusano 7d535a
   * fprintf directly rather than going through the trace message code.
kusano 7d535a
   * This is helpful because message parm array can't handle longs.
kusano 7d535a
   */
kusano 7d535a
  fprintf(stderr, "Freeing pool %d, total space = %ld\n",
kusano 7d535a
	  pool_id, mem->total_space_allocated);
kusano 7d535a
kusano 7d535a
  for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
kusano 7d535a
       lhdr_ptr = lhdr_ptr->hdr.next) {
kusano 7d535a
    fprintf(stderr, "  Large chunk used %ld\n",
kusano 7d535a
	    (long) lhdr_ptr->hdr.bytes_used);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
kusano 7d535a
       shdr_ptr = shdr_ptr->hdr.next) {
kusano 7d535a
    fprintf(stderr, "  Small chunk used %ld free %ld\n",
kusano 7d535a
	    (long) shdr_ptr->hdr.bytes_used,
kusano 7d535a
	    (long) shdr_ptr->hdr.bytes_left);
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
#endif /* MEM_STATS */
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(noreturn_t)
kusano 7d535a
out_of_memory (j_common_ptr cinfo, int which)
kusano 7d535a
/* Report an out-of-memory error and stop execution */
kusano 7d535a
/* If we compiled MEM_STATS support, report alloc requests before dying */
kusano 7d535a
{
kusano 7d535a
#ifdef MEM_STATS
kusano 7d535a
  cinfo->err->trace_level = 2;	/* force self_destruct to report stats */
kusano 7d535a
#endif
kusano 7d535a
  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Allocation of "small" objects.
kusano 7d535a
 *
kusano 7d535a
 * For these, we use pooled storage.  When a new pool must be created,
kusano 7d535a
 * we try to get enough space for the current request plus a "slop" factor,
kusano 7d535a
 * where the slop will be the amount of leftover space in the new pool.
kusano 7d535a
 * The speed vs. space tradeoff is largely determined by the slop values.
kusano 7d535a
 * A different slop value is provided for each pool class (lifetime),
kusano 7d535a
 * and we also distinguish the first pool of a class from later ones.
kusano 7d535a
 * NOTE: the values given work fairly well on both 16- and 32-bit-int
kusano 7d535a
 * machines, but may be too small if longs are 64 bits or more.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
static const size_t first_pool_slop[JPOOL_NUMPOOLS] = 
kusano 7d535a
{
kusano 7d535a
	1600,			/* first PERMANENT pool */
kusano 7d535a
	16000			/* first IMAGE pool */
kusano 7d535a
};
kusano 7d535a
kusano 7d535a
static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = 
kusano 7d535a
{
kusano 7d535a
	0,			/* additional PERMANENT pools */
kusano 7d535a
	5000			/* additional IMAGE pools */
kusano 7d535a
};
kusano 7d535a
kusano 7d535a
#define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
kusano 7d535a
kusano 7d535a
kusano 7d535a
METHODDEF(void *)
kusano 7d535a
alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
kusano 7d535a
/* Allocate a "small" object */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  small_pool_ptr hdr_ptr, prev_hdr_ptr;
kusano 7d535a
  char * data_ptr;
kusano 7d535a
  size_t odd_bytes, min_request, slop;
kusano 7d535a
kusano 7d535a
  /* Check for unsatisfiable request (do now to ensure no overflow below) */
kusano 7d535a
  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
kusano 7d535a
    out_of_memory(cinfo, 1);	/* request exceeds malloc's ability */
kusano 7d535a
kusano 7d535a
  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
kusano 7d535a
  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
kusano 7d535a
  if (odd_bytes > 0)
kusano 7d535a
    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
kusano 7d535a
kusano 7d535a
  /* See if space is available in any existing pool */
kusano 7d535a
  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
kusano 7d535a
    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
kusano 7d535a
  prev_hdr_ptr = NULL;
kusano 7d535a
  hdr_ptr = mem->small_list[pool_id];
kusano 7d535a
  while (hdr_ptr != NULL) {
kusano 7d535a
    if (hdr_ptr->hdr.bytes_left >= sizeofobject)
kusano 7d535a
      break;			/* found pool with enough space */
kusano 7d535a
    prev_hdr_ptr = hdr_ptr;
kusano 7d535a
    hdr_ptr = hdr_ptr->hdr.next;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Time to make a new pool? */
kusano 7d535a
  if (hdr_ptr == NULL) {
kusano 7d535a
    /* min_request is what we need now, slop is what will be leftover */
kusano 7d535a
    min_request = sizeofobject + SIZEOF(small_pool_hdr);
kusano 7d535a
    if (prev_hdr_ptr == NULL)	/* first pool in class? */
kusano 7d535a
      slop = first_pool_slop[pool_id];
kusano 7d535a
    else
kusano 7d535a
      slop = extra_pool_slop[pool_id];
kusano 7d535a
    /* Don't ask for more than MAX_ALLOC_CHUNK */
kusano 7d535a
    if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
kusano 7d535a
      slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
kusano 7d535a
    /* Try to get space, if fail reduce slop and try again */
kusano 7d535a
    for (;;) {
kusano 7d535a
      hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
kusano 7d535a
      if (hdr_ptr != NULL)
kusano 7d535a
	break;
kusano 7d535a
      slop /= 2;
kusano 7d535a
      if (slop < MIN_SLOP)	/* give up when it gets real small */
kusano 7d535a
	out_of_memory(cinfo, 2); /* jpeg_get_small failed */
kusano 7d535a
    }
kusano 7d535a
    mem->total_space_allocated += min_request + slop;
kusano 7d535a
    /* Success, initialize the new pool header and add to end of list */
kusano 7d535a
    hdr_ptr->hdr.next = NULL;
kusano 7d535a
    hdr_ptr->hdr.bytes_used = 0;
kusano 7d535a
    hdr_ptr->hdr.bytes_left = sizeofobject + slop;
kusano 7d535a
    if (prev_hdr_ptr == NULL)	/* first pool in class? */
kusano 7d535a
      mem->small_list[pool_id] = hdr_ptr;
kusano 7d535a
    else
kusano 7d535a
      prev_hdr_ptr->hdr.next = hdr_ptr;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* OK, allocate the object from the current pool */
kusano 7d535a
  data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
kusano 7d535a
  data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
kusano 7d535a
  hdr_ptr->hdr.bytes_used += sizeofobject;
kusano 7d535a
  hdr_ptr->hdr.bytes_left -= sizeofobject;
kusano 7d535a
kusano 7d535a
  return (void *) data_ptr;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Allocation of "large" objects.
kusano 7d535a
 *
kusano 7d535a
 * The external semantics of these are the same as "small" objects,
kusano 7d535a
 * except that FAR pointers are used on 80x86.  However the pool
kusano 7d535a
 * management heuristics are quite different.  We assume that each
kusano 7d535a
 * request is large enough that it may as well be passed directly to
kusano 7d535a
 * jpeg_get_large; the pool management just links everything together
kusano 7d535a
 * so that we can free it all on demand.
kusano 7d535a
 * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
kusano 7d535a
 * structures.  The routines that create these structures (see below)
kusano 7d535a
 * deliberately bunch rows together to ensure a large request size.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(void FAR *)
kusano 7d535a
alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
kusano 7d535a
/* Allocate a "large" object */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  large_pool_ptr hdr_ptr;
kusano 7d535a
  size_t odd_bytes;
kusano 7d535a
kusano 7d535a
  /* Check for unsatisfiable request (do now to ensure no overflow below) */
kusano 7d535a
  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
kusano 7d535a
    out_of_memory(cinfo, 3);	/* request exceeds malloc's ability */
kusano 7d535a
kusano 7d535a
  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
kusano 7d535a
  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
kusano 7d535a
  if (odd_bytes > 0)
kusano 7d535a
    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
kusano 7d535a
kusano 7d535a
  /* Always make a new pool */
kusano 7d535a
  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
kusano 7d535a
    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
kusano 7d535a
kusano 7d535a
  hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
kusano 7d535a
					    SIZEOF(large_pool_hdr));
kusano 7d535a
  if (hdr_ptr == NULL)
kusano 7d535a
    out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
kusano 7d535a
  mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
kusano 7d535a
kusano 7d535a
  /* Success, initialize the new pool header and add to list */
kusano 7d535a
  hdr_ptr->hdr.next = mem->large_list[pool_id];
kusano 7d535a
  /* We maintain space counts in each pool header for statistical purposes,
kusano 7d535a
   * even though they are not needed for allocation.
kusano 7d535a
   */
kusano 7d535a
  hdr_ptr->hdr.bytes_used = sizeofobject;
kusano 7d535a
  hdr_ptr->hdr.bytes_left = 0;
kusano 7d535a
  mem->large_list[pool_id] = hdr_ptr;
kusano 7d535a
kusano 7d535a
  return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Creation of 2-D sample arrays.
kusano 7d535a
 * The pointers are in near heap, the samples themselves in FAR heap.
kusano 7d535a
 *
kusano 7d535a
 * To minimize allocation overhead and to allow I/O of large contiguous
kusano 7d535a
 * blocks, we allocate the sample rows in groups of as many rows as possible
kusano 7d535a
 * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
kusano 7d535a
 * NB: the virtual array control routines, later in this file, know about
kusano 7d535a
 * this chunking of rows.  The rowsperchunk value is left in the mem manager
kusano 7d535a
 * object so that it can be saved away if this sarray is the workspace for
kusano 7d535a
 * a virtual array.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(JSAMPARRAY)
kusano 7d535a
alloc_sarray (j_common_ptr cinfo, int pool_id,
kusano 7d535a
	      JDIMENSION samplesperrow, JDIMENSION numrows)
kusano 7d535a
/* Allocate a 2-D sample array */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  JSAMPARRAY result;
kusano 7d535a
  JSAMPROW workspace;
kusano 7d535a
  JDIMENSION rowsperchunk, currow, i;
kusano 7d535a
  long ltemp;
kusano 7d535a
kusano 7d535a
  /* Calculate max # of rows allowed in one allocation chunk */
kusano 7d535a
  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
kusano 7d535a
	  ((long) samplesperrow * SIZEOF(JSAMPLE));
kusano 7d535a
  if (ltemp <= 0)
kusano 7d535a
    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
kusano 7d535a
  if (ltemp < (long) numrows)
kusano 7d535a
    rowsperchunk = (JDIMENSION) ltemp;
kusano 7d535a
  else
kusano 7d535a
    rowsperchunk = numrows;
kusano 7d535a
  mem->last_rowsperchunk = rowsperchunk;
kusano 7d535a
kusano 7d535a
  /* Get space for row pointers (small object) */
kusano 7d535a
  result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
kusano 7d535a
				    (size_t) (numrows * SIZEOF(JSAMPROW)));
kusano 7d535a
kusano 7d535a
  /* Get the rows themselves (large objects) */
kusano 7d535a
  currow = 0;
kusano 7d535a
  while (currow < numrows) {
kusano 7d535a
    rowsperchunk = MIN(rowsperchunk, numrows - currow);
kusano 7d535a
    workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
kusano 7d535a
	(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
kusano 7d535a
		  * SIZEOF(JSAMPLE)));
kusano 7d535a
    for (i = rowsperchunk; i > 0; i--) {
kusano 7d535a
      result[currow++] = workspace;
kusano 7d535a
      workspace += samplesperrow;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return result;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Creation of 2-D coefficient-block arrays.
kusano 7d535a
 * This is essentially the same as the code for sample arrays, above.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(JBLOCKARRAY)
kusano 7d535a
alloc_barray (j_common_ptr cinfo, int pool_id,
kusano 7d535a
	      JDIMENSION blocksperrow, JDIMENSION numrows)
kusano 7d535a
/* Allocate a 2-D coefficient-block array */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  JBLOCKARRAY result;
kusano 7d535a
  JBLOCKROW workspace;
kusano 7d535a
  JDIMENSION rowsperchunk, currow, i;
kusano 7d535a
  long ltemp;
kusano 7d535a
kusano 7d535a
  /* Calculate max # of rows allowed in one allocation chunk */
kusano 7d535a
  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
kusano 7d535a
	  ((long) blocksperrow * SIZEOF(JBLOCK));
kusano 7d535a
  if (ltemp <= 0)
kusano 7d535a
    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
kusano 7d535a
  if (ltemp < (long) numrows)
kusano 7d535a
    rowsperchunk = (JDIMENSION) ltemp;
kusano 7d535a
  else
kusano 7d535a
    rowsperchunk = numrows;
kusano 7d535a
  mem->last_rowsperchunk = rowsperchunk;
kusano 7d535a
kusano 7d535a
  /* Get space for row pointers (small object) */
kusano 7d535a
  result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
kusano 7d535a
				     (size_t) (numrows * SIZEOF(JBLOCKROW)));
kusano 7d535a
kusano 7d535a
  /* Get the rows themselves (large objects) */
kusano 7d535a
  currow = 0;
kusano 7d535a
  while (currow < numrows) {
kusano 7d535a
    rowsperchunk = MIN(rowsperchunk, numrows - currow);
kusano 7d535a
    workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
kusano 7d535a
	(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
kusano 7d535a
		  * SIZEOF(JBLOCK)));
kusano 7d535a
    for (i = rowsperchunk; i > 0; i--) {
kusano 7d535a
      result[currow++] = workspace;
kusano 7d535a
      workspace += blocksperrow;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return result;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * About virtual array management:
kusano 7d535a
 *
kusano 7d535a
 * The above "normal" array routines are only used to allocate strip buffers
kusano 7d535a
 * (as wide as the image, but just a few rows high).  Full-image-sized buffers
kusano 7d535a
 * are handled as "virtual" arrays.  The array is still accessed a strip at a
kusano 7d535a
 * time, but the memory manager must save the whole array for repeated
kusano 7d535a
 * accesses.  The intended implementation is that there is a strip buffer in
kusano 7d535a
 * memory (as high as is possible given the desired memory limit), plus a
kusano 7d535a
 * backing file that holds the rest of the array.
kusano 7d535a
 *
kusano 7d535a
 * The request_virt_array routines are told the total size of the image and
kusano 7d535a
 * the maximum number of rows that will be accessed at once.  The in-memory
kusano 7d535a
 * buffer must be at least as large as the maxaccess value.
kusano 7d535a
 *
kusano 7d535a
 * The request routines create control blocks but not the in-memory buffers.
kusano 7d535a
 * That is postponed until realize_virt_arrays is called.  At that time the
kusano 7d535a
 * total amount of space needed is known (approximately, anyway), so free
kusano 7d535a
 * memory can be divided up fairly.
kusano 7d535a
 *
kusano 7d535a
 * The access_virt_array routines are responsible for making a specific strip
kusano 7d535a
 * area accessible (after reading or writing the backing file, if necessary).
kusano 7d535a
 * Note that the access routines are told whether the caller intends to modify
kusano 7d535a
 * the accessed strip; during a read-only pass this saves having to rewrite
kusano 7d535a
 * data to disk.  The access routines are also responsible for pre-zeroing
kusano 7d535a
 * any newly accessed rows, if pre-zeroing was requested.
kusano 7d535a
 *
kusano 7d535a
 * In current usage, the access requests are usually for nonoverlapping
kusano 7d535a
 * strips; that is, successive access start_row numbers differ by exactly
kusano 7d535a
 * num_rows = maxaccess.  This means we can get good performance with simple
kusano 7d535a
 * buffer dump/reload logic, by making the in-memory buffer be a multiple
kusano 7d535a
 * of the access height; then there will never be accesses across bufferload
kusano 7d535a
 * boundaries.  The code will still work with overlapping access requests,
kusano 7d535a
 * but it doesn't handle bufferload overlaps very efficiently.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
kusano 7d535a
METHODDEF(jvirt_sarray_ptr)
kusano 7d535a
request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
kusano 7d535a
		     JDIMENSION samplesperrow, JDIMENSION numrows,
kusano 7d535a
		     JDIMENSION maxaccess)
kusano 7d535a
/* Request a virtual 2-D sample array */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  jvirt_sarray_ptr result;
kusano 7d535a
kusano 7d535a
  /* Only IMAGE-lifetime virtual arrays are currently supported */
kusano 7d535a
  if (pool_id != JPOOL_IMAGE)
kusano 7d535a
    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
kusano 7d535a
kusano 7d535a
  /* get control block */
kusano 7d535a
  result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
kusano 7d535a
					  SIZEOF(struct jvirt_sarray_control));
kusano 7d535a
kusano 7d535a
  result->mem_buffer = NULL;	/* marks array not yet realized */
kusano 7d535a
  result->rows_in_array = numrows;
kusano 7d535a
  result->samplesperrow = samplesperrow;
kusano 7d535a
  result->maxaccess = maxaccess;
kusano 7d535a
  result->pre_zero = pre_zero;
kusano 7d535a
  result->b_s_open = FALSE;	/* no associated backing-store object */
kusano 7d535a
  result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
kusano 7d535a
  mem->virt_sarray_list = result;
kusano 7d535a
kusano 7d535a
  return result;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
METHODDEF(jvirt_barray_ptr)
kusano 7d535a
request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
kusano 7d535a
		     JDIMENSION blocksperrow, JDIMENSION numrows,
kusano 7d535a
		     JDIMENSION maxaccess)
kusano 7d535a
/* Request a virtual 2-D coefficient-block array */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  jvirt_barray_ptr result;
kusano 7d535a
kusano 7d535a
  /* Only IMAGE-lifetime virtual arrays are currently supported */
kusano 7d535a
  if (pool_id != JPOOL_IMAGE)
kusano 7d535a
    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
kusano 7d535a
kusano 7d535a
  /* get control block */
kusano 7d535a
  result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
kusano 7d535a
					  SIZEOF(struct jvirt_barray_control));
kusano 7d535a
kusano 7d535a
  result->mem_buffer = NULL;	/* marks array not yet realized */
kusano 7d535a
  result->rows_in_array = numrows;
kusano 7d535a
  result->blocksperrow = blocksperrow;
kusano 7d535a
  result->maxaccess = maxaccess;
kusano 7d535a
  result->pre_zero = pre_zero;
kusano 7d535a
  result->b_s_open = FALSE;	/* no associated backing-store object */
kusano 7d535a
  result->next = mem->virt_barray_list; /* add to list of virtual arrays */
kusano 7d535a
  mem->virt_barray_list = result;
kusano 7d535a
kusano 7d535a
  return result;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
METHODDEF(void)
kusano 7d535a
realize_virt_arrays (j_common_ptr cinfo)
kusano 7d535a
/* Allocate the in-memory buffers for any unrealized virtual arrays */
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  long space_per_minheight, maximum_space, avail_mem;
kusano 7d535a
  long minheights, max_minheights;
kusano 7d535a
  jvirt_sarray_ptr sptr;
kusano 7d535a
  jvirt_barray_ptr bptr;
kusano 7d535a
kusano 7d535a
  /* Compute the minimum space needed (maxaccess rows in each buffer)
kusano 7d535a
   * and the maximum space needed (full image height in each buffer).
kusano 7d535a
   * These may be of use to the system-dependent jpeg_mem_available routine.
kusano 7d535a
   */
kusano 7d535a
  space_per_minheight = 0;
kusano 7d535a
  maximum_space = 0;
kusano 7d535a
  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
kusano 7d535a
    if (sptr->mem_buffer == NULL) { /* if not realized yet */
kusano 7d535a
      space_per_minheight += (long) sptr->maxaccess *
kusano 7d535a
			     (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
kusano 7d535a
      maximum_space += (long) sptr->rows_in_array *
kusano 7d535a
		       (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
kusano 7d535a
    if (bptr->mem_buffer == NULL) { /* if not realized yet */
kusano 7d535a
      space_per_minheight += (long) bptr->maxaccess *
kusano 7d535a
			     (long) bptr->blocksperrow * SIZEOF(JBLOCK);
kusano 7d535a
      maximum_space += (long) bptr->rows_in_array *
kusano 7d535a
		       (long) bptr->blocksperrow * SIZEOF(JBLOCK);
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  if (space_per_minheight <= 0)
kusano 7d535a
    return;			/* no unrealized arrays, no work */
kusano 7d535a
kusano 7d535a
  /* Determine amount of memory to actually use; this is system-dependent. */
kusano 7d535a
  avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
kusano 7d535a
				 mem->total_space_allocated);
kusano 7d535a
kusano 7d535a
  /* If the maximum space needed is available, make all the buffers full
kusano 7d535a
   * height; otherwise parcel it out with the same number of minheights
kusano 7d535a
   * in each buffer.
kusano 7d535a
   */
kusano 7d535a
  if (avail_mem >= maximum_space)
kusano 7d535a
    max_minheights = 1000000000L;
kusano 7d535a
  else {
kusano 7d535a
    max_minheights = avail_mem / space_per_minheight;
kusano 7d535a
    /* If there doesn't seem to be enough space, try to get the minimum
kusano 7d535a
     * anyway.  This allows a "stub" implementation of jpeg_mem_available().
kusano 7d535a
     */
kusano 7d535a
    if (max_minheights <= 0)
kusano 7d535a
      max_minheights = 1;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Allocate the in-memory buffers and initialize backing store as needed. */
kusano 7d535a
kusano 7d535a
  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
kusano 7d535a
    if (sptr->mem_buffer == NULL) { /* if not realized yet */
kusano 7d535a
      minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
kusano 7d535a
      if (minheights <= max_minheights) {
kusano 7d535a
	/* This buffer fits in memory */
kusano 7d535a
	sptr->rows_in_mem = sptr->rows_in_array;
kusano 7d535a
      } else {
kusano 7d535a
	/* It doesn't fit in memory, create backing store. */
kusano 7d535a
	sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
kusano 7d535a
	jpeg_open_backing_store(cinfo, & sptr->b_s_info,
kusano 7d535a
				(long) sptr->rows_in_array *
kusano 7d535a
				(long) sptr->samplesperrow *
kusano 7d535a
				(long) SIZEOF(JSAMPLE));
kusano 7d535a
	sptr->b_s_open = TRUE;
kusano 7d535a
      }
kusano 7d535a
      sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
kusano 7d535a
				      sptr->samplesperrow, sptr->rows_in_mem);
kusano 7d535a
      sptr->rowsperchunk = mem->last_rowsperchunk;
kusano 7d535a
      sptr->cur_start_row = 0;
kusano 7d535a
      sptr->first_undef_row = 0;
kusano 7d535a
      sptr->dirty = FALSE;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
kusano 7d535a
    if (bptr->mem_buffer == NULL) { /* if not realized yet */
kusano 7d535a
      minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
kusano 7d535a
      if (minheights <= max_minheights) {
kusano 7d535a
	/* This buffer fits in memory */
kusano 7d535a
	bptr->rows_in_mem = bptr->rows_in_array;
kusano 7d535a
      } else {
kusano 7d535a
	/* It doesn't fit in memory, create backing store. */
kusano 7d535a
	bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
kusano 7d535a
	jpeg_open_backing_store(cinfo, & bptr->b_s_info,
kusano 7d535a
				(long) bptr->rows_in_array *
kusano 7d535a
				(long) bptr->blocksperrow *
kusano 7d535a
				(long) SIZEOF(JBLOCK));
kusano 7d535a
	bptr->b_s_open = TRUE;
kusano 7d535a
      }
kusano 7d535a
      bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
kusano 7d535a
				      bptr->blocksperrow, bptr->rows_in_mem);
kusano 7d535a
      bptr->rowsperchunk = mem->last_rowsperchunk;
kusano 7d535a
      bptr->cur_start_row = 0;
kusano 7d535a
      bptr->first_undef_row = 0;
kusano 7d535a
      bptr->dirty = FALSE;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
kusano 7d535a
/* Do backing store read or write of a virtual sample array */
kusano 7d535a
{
kusano 7d535a
  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
kusano 7d535a
kusano 7d535a
  bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
kusano 7d535a
  file_offset = ptr->cur_start_row * bytesperrow;
kusano 7d535a
  /* Loop to read or write each allocation chunk in mem_buffer */
kusano 7d535a
  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
kusano 7d535a
    /* One chunk, but check for short chunk at end of buffer */
kusano 7d535a
    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
kusano 7d535a
    /* Transfer no more than is currently defined */
kusano 7d535a
    thisrow = (long) ptr->cur_start_row + i;
kusano 7d535a
    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
kusano 7d535a
    /* Transfer no more than fits in file */
kusano 7d535a
    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
kusano 7d535a
    if (rows <= 0)		/* this chunk might be past end of file! */
kusano 7d535a
      break;
kusano 7d535a
    byte_count = rows * bytesperrow;
kusano 7d535a
    if (writing)
kusano 7d535a
      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
kusano 7d535a
					    (void FAR *) ptr->mem_buffer[i],
kusano 7d535a
					    file_offset, byte_count);
kusano 7d535a
    else
kusano 7d535a
      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
kusano 7d535a
					   (void FAR *) ptr->mem_buffer[i],
kusano 7d535a
					   file_offset, byte_count);
kusano 7d535a
    file_offset += byte_count;
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
kusano 7d535a
/* Do backing store read or write of a virtual coefficient-block array */
kusano 7d535a
{
kusano 7d535a
  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
kusano 7d535a
kusano 7d535a
  bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
kusano 7d535a
  file_offset = ptr->cur_start_row * bytesperrow;
kusano 7d535a
  /* Loop to read or write each allocation chunk in mem_buffer */
kusano 7d535a
  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
kusano 7d535a
    /* One chunk, but check for short chunk at end of buffer */
kusano 7d535a
    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
kusano 7d535a
    /* Transfer no more than is currently defined */
kusano 7d535a
    thisrow = (long) ptr->cur_start_row + i;
kusano 7d535a
    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
kusano 7d535a
    /* Transfer no more than fits in file */
kusano 7d535a
    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
kusano 7d535a
    if (rows <= 0)		/* this chunk might be past end of file! */
kusano 7d535a
      break;
kusano 7d535a
    byte_count = rows * bytesperrow;
kusano 7d535a
    if (writing)
kusano 7d535a
      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
kusano 7d535a
					    (void FAR *) ptr->mem_buffer[i],
kusano 7d535a
					    file_offset, byte_count);
kusano 7d535a
    else
kusano 7d535a
      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
kusano 7d535a
					   (void FAR *) ptr->mem_buffer[i],
kusano 7d535a
					   file_offset, byte_count);
kusano 7d535a
    file_offset += byte_count;
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
METHODDEF(JSAMPARRAY)
kusano 7d535a
access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
kusano 7d535a
		    JDIMENSION start_row, JDIMENSION num_rows,
kusano 7d535a
		    boolean writable)
kusano 7d535a
/* Access the part of a virtual sample array starting at start_row */
kusano 7d535a
/* and extending for num_rows rows.  writable is true if  */
kusano 7d535a
/* caller intends to modify the accessed area. */
kusano 7d535a
{
kusano 7d535a
  JDIMENSION end_row = start_row + num_rows;
kusano 7d535a
  JDIMENSION undef_row;
kusano 7d535a
kusano 7d535a
  /* debugging check */
kusano 7d535a
  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
kusano 7d535a
      ptr->mem_buffer == NULL)
kusano 7d535a
    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
kusano 7d535a
kusano 7d535a
  /* Make the desired part of the virtual array accessible */
kusano 7d535a
  if (start_row < ptr->cur_start_row ||
kusano 7d535a
      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
kusano 7d535a
    if (! ptr->b_s_open)
kusano 7d535a
      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
kusano 7d535a
    /* Flush old buffer contents if necessary */
kusano 7d535a
    if (ptr->dirty) {
kusano 7d535a
      do_sarray_io(cinfo, ptr, TRUE);
kusano 7d535a
      ptr->dirty = FALSE;
kusano 7d535a
    }
kusano 7d535a
    /* Decide what part of virtual array to access.
kusano 7d535a
     * Algorithm: if target address > current window, assume forward scan,
kusano 7d535a
     * load starting at target address.  If target address < current window,
kusano 7d535a
     * assume backward scan, load so that target area is top of window.
kusano 7d535a
     * Note that when switching from forward write to forward read, will have
kusano 7d535a
     * start_row = 0, so the limiting case applies and we load from 0 anyway.
kusano 7d535a
     */
kusano 7d535a
    if (start_row > ptr->cur_start_row) {
kusano 7d535a
      ptr->cur_start_row = start_row;
kusano 7d535a
    } else {
kusano 7d535a
      /* use long arithmetic here to avoid overflow & unsigned problems */
kusano 7d535a
      long ltemp;
kusano 7d535a
kusano 7d535a
      ltemp = (long) end_row - (long) ptr->rows_in_mem;
kusano 7d535a
      if (ltemp < 0)
kusano 7d535a
	ltemp = 0;		/* don't fall off front end of file */
kusano 7d535a
      ptr->cur_start_row = (JDIMENSION) ltemp;
kusano 7d535a
    }
kusano 7d535a
    /* Read in the selected part of the array.
kusano 7d535a
     * During the initial write pass, we will do no actual read
kusano 7d535a
     * because the selected part is all undefined.
kusano 7d535a
     */
kusano 7d535a
    do_sarray_io(cinfo, ptr, FALSE);
kusano 7d535a
  }
kusano 7d535a
  /* Ensure the accessed part of the array is defined; prezero if needed.
kusano 7d535a
   * To improve locality of access, we only prezero the part of the array
kusano 7d535a
   * that the caller is about to access, not the entire in-memory array.
kusano 7d535a
   */
kusano 7d535a
  if (ptr->first_undef_row < end_row) {
kusano 7d535a
    if (ptr->first_undef_row < start_row) {
kusano 7d535a
      if (writable)		/* writer skipped over a section of array */
kusano 7d535a
	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
kusano 7d535a
      undef_row = start_row;	/* but reader is allowed to read ahead */
kusano 7d535a
    } else {
kusano 7d535a
      undef_row = ptr->first_undef_row;
kusano 7d535a
    }
kusano 7d535a
    if (writable)
kusano 7d535a
      ptr->first_undef_row = end_row;
kusano 7d535a
    if (ptr->pre_zero) {
kusano 7d535a
      size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
kusano 7d535a
      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
kusano 7d535a
      end_row -= ptr->cur_start_row;
kusano 7d535a
      while (undef_row < end_row) {
kusano 7d535a
	FMEMZERO((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
kusano 7d535a
	undef_row++;
kusano 7d535a
      }
kusano 7d535a
    } else {
kusano 7d535a
      if (! writable)		/* reader looking at undefined data */
kusano 7d535a
	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
  /* Flag the buffer dirty if caller will write in it */
kusano 7d535a
  if (writable)
kusano 7d535a
    ptr->dirty = TRUE;
kusano 7d535a
  /* Return address of proper part of the buffer */
kusano 7d535a
  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
METHODDEF(JBLOCKARRAY)
kusano 7d535a
access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
kusano 7d535a
		    JDIMENSION start_row, JDIMENSION num_rows,
kusano 7d535a
		    boolean writable)
kusano 7d535a
/* Access the part of a virtual block array starting at start_row */
kusano 7d535a
/* and extending for num_rows rows.  writable is true if  */
kusano 7d535a
/* caller intends to modify the accessed area. */
kusano 7d535a
{
kusano 7d535a
  JDIMENSION end_row = start_row + num_rows;
kusano 7d535a
  JDIMENSION undef_row;
kusano 7d535a
kusano 7d535a
  /* debugging check */
kusano 7d535a
  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
kusano 7d535a
      ptr->mem_buffer == NULL)
kusano 7d535a
    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
kusano 7d535a
kusano 7d535a
  /* Make the desired part of the virtual array accessible */
kusano 7d535a
  if (start_row < ptr->cur_start_row ||
kusano 7d535a
      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
kusano 7d535a
    if (! ptr->b_s_open)
kusano 7d535a
      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
kusano 7d535a
    /* Flush old buffer contents if necessary */
kusano 7d535a
    if (ptr->dirty) {
kusano 7d535a
      do_barray_io(cinfo, ptr, TRUE);
kusano 7d535a
      ptr->dirty = FALSE;
kusano 7d535a
    }
kusano 7d535a
    /* Decide what part of virtual array to access.
kusano 7d535a
     * Algorithm: if target address > current window, assume forward scan,
kusano 7d535a
     * load starting at target address.  If target address < current window,
kusano 7d535a
     * assume backward scan, load so that target area is top of window.
kusano 7d535a
     * Note that when switching from forward write to forward read, will have
kusano 7d535a
     * start_row = 0, so the limiting case applies and we load from 0 anyway.
kusano 7d535a
     */
kusano 7d535a
    if (start_row > ptr->cur_start_row) {
kusano 7d535a
      ptr->cur_start_row = start_row;
kusano 7d535a
    } else {
kusano 7d535a
      /* use long arithmetic here to avoid overflow & unsigned problems */
kusano 7d535a
      long ltemp;
kusano 7d535a
kusano 7d535a
      ltemp = (long) end_row - (long) ptr->rows_in_mem;
kusano 7d535a
      if (ltemp < 0)
kusano 7d535a
	ltemp = 0;		/* don't fall off front end of file */
kusano 7d535a
      ptr->cur_start_row = (JDIMENSION) ltemp;
kusano 7d535a
    }
kusano 7d535a
    /* Read in the selected part of the array.
kusano 7d535a
     * During the initial write pass, we will do no actual read
kusano 7d535a
     * because the selected part is all undefined.
kusano 7d535a
     */
kusano 7d535a
    do_barray_io(cinfo, ptr, FALSE);
kusano 7d535a
  }
kusano 7d535a
  /* Ensure the accessed part of the array is defined; prezero if needed.
kusano 7d535a
   * To improve locality of access, we only prezero the part of the array
kusano 7d535a
   * that the caller is about to access, not the entire in-memory array.
kusano 7d535a
   */
kusano 7d535a
  if (ptr->first_undef_row < end_row) {
kusano 7d535a
    if (ptr->first_undef_row < start_row) {
kusano 7d535a
      if (writable)		/* writer skipped over a section of array */
kusano 7d535a
	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
kusano 7d535a
      undef_row = start_row;	/* but reader is allowed to read ahead */
kusano 7d535a
    } else {
kusano 7d535a
      undef_row = ptr->first_undef_row;
kusano 7d535a
    }
kusano 7d535a
    if (writable)
kusano 7d535a
      ptr->first_undef_row = end_row;
kusano 7d535a
    if (ptr->pre_zero) {
kusano 7d535a
      size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
kusano 7d535a
      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
kusano 7d535a
      end_row -= ptr->cur_start_row;
kusano 7d535a
      while (undef_row < end_row) {
kusano 7d535a
	FMEMZERO((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
kusano 7d535a
	undef_row++;
kusano 7d535a
      }
kusano 7d535a
    } else {
kusano 7d535a
      if (! writable)		/* reader looking at undefined data */
kusano 7d535a
	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
  /* Flag the buffer dirty if caller will write in it */
kusano 7d535a
  if (writable)
kusano 7d535a
    ptr->dirty = TRUE;
kusano 7d535a
  /* Return address of proper part of the buffer */
kusano 7d535a
  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Release all objects belonging to a specified pool.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(void)
kusano 7d535a
free_pool (j_common_ptr cinfo, int pool_id)
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
kusano 7d535a
  small_pool_ptr shdr_ptr;
kusano 7d535a
  large_pool_ptr lhdr_ptr;
kusano 7d535a
  size_t space_freed;
kusano 7d535a
kusano 7d535a
  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
kusano 7d535a
    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
kusano 7d535a
kusano 7d535a
#ifdef MEM_STATS
kusano 7d535a
  if (cinfo->err->trace_level > 1)
kusano 7d535a
    print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
  /* If freeing IMAGE pool, close any virtual arrays first */
kusano 7d535a
  if (pool_id == JPOOL_IMAGE) {
kusano 7d535a
    jvirt_sarray_ptr sptr;
kusano 7d535a
    jvirt_barray_ptr bptr;
kusano 7d535a
kusano 7d535a
    for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
kusano 7d535a
      if (sptr->b_s_open) {	/* there may be no backing store */
kusano 7d535a
	sptr->b_s_open = FALSE;	/* prevent recursive close if error */
kusano 7d535a
	(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
    mem->virt_sarray_list = NULL;
kusano 7d535a
    for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
kusano 7d535a
      if (bptr->b_s_open) {	/* there may be no backing store */
kusano 7d535a
	bptr->b_s_open = FALSE;	/* prevent recursive close if error */
kusano 7d535a
	(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
    mem->virt_barray_list = NULL;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Release large objects */
kusano 7d535a
  lhdr_ptr = mem->large_list[pool_id];
kusano 7d535a
  mem->large_list[pool_id] = NULL;
kusano 7d535a
kusano 7d535a
  while (lhdr_ptr != NULL) {
kusano 7d535a
    large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
kusano 7d535a
    space_freed = lhdr_ptr->hdr.bytes_used +
kusano 7d535a
		  lhdr_ptr->hdr.bytes_left +
kusano 7d535a
		  SIZEOF(large_pool_hdr);
kusano 7d535a
    jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
kusano 7d535a
    mem->total_space_allocated -= space_freed;
kusano 7d535a
    lhdr_ptr = next_lhdr_ptr;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Release small objects */
kusano 7d535a
  shdr_ptr = mem->small_list[pool_id];
kusano 7d535a
  mem->small_list[pool_id] = NULL;
kusano 7d535a
kusano 7d535a
  while (shdr_ptr != NULL) {
kusano 7d535a
    small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
kusano 7d535a
    space_freed = shdr_ptr->hdr.bytes_used +
kusano 7d535a
		  shdr_ptr->hdr.bytes_left +
kusano 7d535a
		  SIZEOF(small_pool_hdr);
kusano 7d535a
    jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
kusano 7d535a
    mem->total_space_allocated -= space_freed;
kusano 7d535a
    shdr_ptr = next_shdr_ptr;
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Close up shop entirely.
kusano 7d535a
 * Note that this cannot be called unless cinfo->mem is non-NULL.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(void)
kusano 7d535a
self_destruct (j_common_ptr cinfo)
kusano 7d535a
{
kusano 7d535a
  int pool;
kusano 7d535a
kusano 7d535a
  /* Close all backing store, release all memory.
kusano 7d535a
   * Releasing pools in reverse order might help avoid fragmentation
kusano 7d535a
   * with some (brain-damaged) malloc libraries.
kusano 7d535a
   */
kusano 7d535a
  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
kusano 7d535a
    free_pool(cinfo, pool);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Release the memory manager control block too. */
kusano 7d535a
  jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
kusano 7d535a
  cinfo->mem = NULL;		/* ensures I will be called only once */
kusano 7d535a
kusano 7d535a
  jpeg_mem_term(cinfo);		/* system-dependent cleanup */
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Memory manager initialization.
kusano 7d535a
 * When this is called, only the error manager pointer is valid in cinfo!
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
GLOBAL(void)
kusano 7d535a
jinit_memory_mgr (j_common_ptr cinfo)
kusano 7d535a
{
kusano 7d535a
  my_mem_ptr mem;
kusano 7d535a
  long max_to_use;
kusano 7d535a
  int pool;
kusano 7d535a
  size_t test_mac;
kusano 7d535a
kusano 7d535a
  cinfo->mem = NULL;		/* for safety if init fails */
kusano 7d535a
kusano 7d535a
  /* Check for configuration errors.
kusano 7d535a
   * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
kusano 7d535a
   * doesn't reflect any real hardware alignment requirement.
kusano 7d535a
   * The test is a little tricky: for X>0, X and X-1 have no one-bits
kusano 7d535a
   * in common if and only if X is a power of 2, ie has only one one-bit.
kusano 7d535a
   * Some compilers may give an "unreachable code" warning here; ignore it.
kusano 7d535a
   */
kusano 7d535a
  if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
kusano 7d535a
    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
kusano 7d535a
  /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
kusano 7d535a
   * a multiple of SIZEOF(ALIGN_TYPE).
kusano 7d535a
   * Again, an "unreachable code" warning may be ignored here.
kusano 7d535a
   * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
kusano 7d535a
   */
kusano 7d535a
  test_mac = (size_t) MAX_ALLOC_CHUNK;
kusano 7d535a
  if ((long) test_mac != MAX_ALLOC_CHUNK ||
kusano 7d535a
      (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
kusano 7d535a
    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
kusano 7d535a
kusano 7d535a
  max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
kusano 7d535a
kusano 7d535a
  /* Attempt to allocate memory manager's control block */
kusano 7d535a
  mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
kusano 7d535a
kusano 7d535a
  if (mem == NULL) {
kusano 7d535a
    jpeg_mem_term(cinfo);	/* system-dependent cleanup */
kusano 7d535a
    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* OK, fill in the method pointers */
kusano 7d535a
  mem->pub.alloc_small = alloc_small;
kusano 7d535a
  mem->pub.alloc_large = alloc_large;
kusano 7d535a
  mem->pub.alloc_sarray = alloc_sarray;
kusano 7d535a
  mem->pub.alloc_barray = alloc_barray;
kusano 7d535a
  mem->pub.request_virt_sarray = request_virt_sarray;
kusano 7d535a
  mem->pub.request_virt_barray = request_virt_barray;
kusano 7d535a
  mem->pub.realize_virt_arrays = realize_virt_arrays;
kusano 7d535a
  mem->pub.access_virt_sarray = access_virt_sarray;
kusano 7d535a
  mem->pub.access_virt_barray = access_virt_barray;
kusano 7d535a
  mem->pub.free_pool = free_pool;
kusano 7d535a
  mem->pub.self_destruct = self_destruct;
kusano 7d535a
kusano 7d535a
  /* Make MAX_ALLOC_CHUNK accessible to other modules */
kusano 7d535a
  mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
kusano 7d535a
kusano 7d535a
  /* Initialize working state */
kusano 7d535a
  mem->pub.max_memory_to_use = max_to_use;
kusano 7d535a
kusano 7d535a
  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
kusano 7d535a
    mem->small_list[pool] = NULL;
kusano 7d535a
    mem->large_list[pool] = NULL;
kusano 7d535a
  }
kusano 7d535a
  mem->virt_sarray_list = NULL;
kusano 7d535a
  mem->virt_barray_list = NULL;
kusano 7d535a
kusano 7d535a
  mem->total_space_allocated = SIZEOF(my_memory_mgr);
kusano 7d535a
kusano 7d535a
  /* Declare ourselves open for business */
kusano 7d535a
  cinfo->mem = & mem->pub;
kusano 7d535a
kusano 7d535a
  /* Check for an environment variable JPEGMEM; if found, override the
kusano 7d535a
   * default max_memory setting from jpeg_mem_init.  Note that the
kusano 7d535a
   * surrounding application may again override this value.
kusano 7d535a
   * If your system doesn't support getenv(), define NO_GETENV to disable
kusano 7d535a
   * this feature.
kusano 7d535a
   */
kusano 7d535a
#ifndef NO_GETENV
kusano 7d535a
  { char * memenv;
kusano 7d535a
kusano 7d535a
    if ((memenv = getenv("JPEGMEM")) != NULL) {
kusano 7d535a
      char ch = 'x';
kusano 7d535a
kusano 7d535a
      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
kusano 7d535a
	if (ch == 'm' || ch == 'M')
kusano 7d535a
	  max_to_use *= 1000L;
kusano 7d535a
	mem->pub.max_memory_to_use = max_to_use * 1000L;
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
}