vrshoot

diff libs/libjpeg/jmemmgr.c @ 0:b2f14e535253

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 01 Feb 2014 19:58:19 +0200
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/libs/libjpeg/jmemmgr.c	Sat Feb 01 19:58:19 2014 +0200
     1.3 @@ -0,0 +1,1118 @@
     1.4 +/*
     1.5 + * jmemmgr.c
     1.6 + *
     1.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
     1.8 + * This file is part of the Independent JPEG Group's software.
     1.9 + * For conditions of distribution and use, see the accompanying README file.
    1.10 + *
    1.11 + * This file contains the JPEG system-independent memory management
    1.12 + * routines.  This code is usable across a wide variety of machines; most
    1.13 + * of the system dependencies have been isolated in a separate file.
    1.14 + * The major functions provided here are:
    1.15 + *   * pool-based allocation and freeing of memory;
    1.16 + *   * policy decisions about how to divide available memory among the
    1.17 + *     virtual arrays;
    1.18 + *   * control logic for swapping virtual arrays between main memory and
    1.19 + *     backing storage.
    1.20 + * The separate system-dependent file provides the actual backing-storage
    1.21 + * access code, and it contains the policy decision about how much total
    1.22 + * main memory to use.
    1.23 + * This file is system-dependent in the sense that some of its functions
    1.24 + * are unnecessary in some systems.  For example, if there is enough virtual
    1.25 + * memory so that backing storage will never be used, much of the virtual
    1.26 + * array control logic could be removed.  (Of course, if you have that much
    1.27 + * memory then you shouldn't care about a little bit of unused code...)
    1.28 + */
    1.29 +
    1.30 +#define JPEG_INTERNALS
    1.31 +#define AM_MEMORY_MANAGER	/* we define jvirt_Xarray_control structs */
    1.32 +#include "jinclude.h"
    1.33 +#include "jpeglib.h"
    1.34 +#include "jmemsys.h"		/* import the system-dependent declarations */
    1.35 +
    1.36 +#ifndef NO_GETENV
    1.37 +#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare getenv() */
    1.38 +extern char * getenv JPP((const char * name));
    1.39 +#endif
    1.40 +#endif
    1.41 +
    1.42 +
    1.43 +/*
    1.44 + * Some important notes:
    1.45 + *   The allocation routines provided here must never return NULL.
    1.46 + *   They should exit to error_exit if unsuccessful.
    1.47 + *
    1.48 + *   It's not a good idea to try to merge the sarray and barray routines,
    1.49 + *   even though they are textually almost the same, because samples are
    1.50 + *   usually stored as bytes while coefficients are shorts or ints.  Thus,
    1.51 + *   in machines where byte pointers have a different representation from
    1.52 + *   word pointers, the resulting machine code could not be the same.
    1.53 + */
    1.54 +
    1.55 +
    1.56 +/*
    1.57 + * Many machines require storage alignment: longs must start on 4-byte
    1.58 + * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
    1.59 + * always returns pointers that are multiples of the worst-case alignment
    1.60 + * requirement, and we had better do so too.
    1.61 + * There isn't any really portable way to determine the worst-case alignment
    1.62 + * requirement.  This module assumes that the alignment requirement is
    1.63 + * multiples of sizeof(ALIGN_TYPE).
    1.64 + * By default, we define ALIGN_TYPE as double.  This is necessary on some
    1.65 + * workstations (where doubles really do need 8-byte alignment) and will work
    1.66 + * fine on nearly everything.  If your machine has lesser alignment needs,
    1.67 + * you can save a few bytes by making ALIGN_TYPE smaller.
    1.68 + * The only place I know of where this will NOT work is certain Macintosh
    1.69 + * 680x0 compilers that define double as a 10-byte IEEE extended float.
    1.70 + * Doing 10-byte alignment is counterproductive because longwords won't be
    1.71 + * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
    1.72 + * such a compiler.
    1.73 + */
    1.74 +
    1.75 +#ifndef ALIGN_TYPE		/* so can override from jconfig.h */
    1.76 +#define ALIGN_TYPE  double
    1.77 +#endif
    1.78 +
    1.79 +
    1.80 +/*
    1.81 + * We allocate objects from "pools", where each pool is gotten with a single
    1.82 + * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
    1.83 + * overhead within a pool, except for alignment padding.  Each pool has a
    1.84 + * header with a link to the next pool of the same class.
    1.85 + * Small and large pool headers are identical except that the latter's
    1.86 + * link pointer must be FAR on 80x86 machines.
    1.87 + * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
    1.88 + * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
    1.89 + * of the alignment requirement of ALIGN_TYPE.
    1.90 + */
    1.91 +
    1.92 +typedef union small_pool_struct * small_pool_ptr;
    1.93 +
    1.94 +typedef union small_pool_struct {
    1.95 +  struct {
    1.96 +    small_pool_ptr next;	/* next in list of pools */
    1.97 +    size_t bytes_used;		/* how many bytes already used within pool */
    1.98 +    size_t bytes_left;		/* bytes still available in this pool */
    1.99 +  } hdr;
   1.100 +  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
   1.101 +} small_pool_hdr;
   1.102 +
   1.103 +typedef union large_pool_struct FAR * large_pool_ptr;
   1.104 +
   1.105 +typedef union large_pool_struct {
   1.106 +  struct {
   1.107 +    large_pool_ptr next;	/* next in list of pools */
   1.108 +    size_t bytes_used;		/* how many bytes already used within pool */
   1.109 +    size_t bytes_left;		/* bytes still available in this pool */
   1.110 +  } hdr;
   1.111 +  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
   1.112 +} large_pool_hdr;
   1.113 +
   1.114 +
   1.115 +/*
   1.116 + * Here is the full definition of a memory manager object.
   1.117 + */
   1.118 +
   1.119 +typedef struct {
   1.120 +  struct jpeg_memory_mgr pub;	/* public fields */
   1.121 +
   1.122 +  /* Each pool identifier (lifetime class) names a linked list of pools. */
   1.123 +  small_pool_ptr small_list[JPOOL_NUMPOOLS];
   1.124 +  large_pool_ptr large_list[JPOOL_NUMPOOLS];
   1.125 +
   1.126 +  /* Since we only have one lifetime class of virtual arrays, only one
   1.127 +   * linked list is necessary (for each datatype).  Note that the virtual
   1.128 +   * array control blocks being linked together are actually stored somewhere
   1.129 +   * in the small-pool list.
   1.130 +   */
   1.131 +  jvirt_sarray_ptr virt_sarray_list;
   1.132 +  jvirt_barray_ptr virt_barray_list;
   1.133 +
   1.134 +  /* This counts total space obtained from jpeg_get_small/large */
   1.135 +  long total_space_allocated;
   1.136 +
   1.137 +  /* alloc_sarray and alloc_barray set this value for use by virtual
   1.138 +   * array routines.
   1.139 +   */
   1.140 +  JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
   1.141 +} my_memory_mgr;
   1.142 +
   1.143 +typedef my_memory_mgr * my_mem_ptr;
   1.144 +
   1.145 +
   1.146 +/*
   1.147 + * The control blocks for virtual arrays.
   1.148 + * Note that these blocks are allocated in the "small" pool area.
   1.149 + * System-dependent info for the associated backing store (if any) is hidden
   1.150 + * inside the backing_store_info struct.
   1.151 + */
   1.152 +
   1.153 +struct jvirt_sarray_control {
   1.154 +  JSAMPARRAY mem_buffer;	/* => the in-memory buffer */
   1.155 +  JDIMENSION rows_in_array;	/* total virtual array height */
   1.156 +  JDIMENSION samplesperrow;	/* width of array (and of memory buffer) */
   1.157 +  JDIMENSION maxaccess;		/* max rows accessed by access_virt_sarray */
   1.158 +  JDIMENSION rows_in_mem;	/* height of memory buffer */
   1.159 +  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
   1.160 +  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
   1.161 +  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
   1.162 +  boolean pre_zero;		/* pre-zero mode requested? */
   1.163 +  boolean dirty;		/* do current buffer contents need written? */
   1.164 +  boolean b_s_open;		/* is backing-store data valid? */
   1.165 +  jvirt_sarray_ptr next;	/* link to next virtual sarray control block */
   1.166 +  backing_store_info b_s_info;	/* System-dependent control info */
   1.167 +};
   1.168 +
   1.169 +struct jvirt_barray_control {
   1.170 +  JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
   1.171 +  JDIMENSION rows_in_array;	/* total virtual array height */
   1.172 +  JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
   1.173 +  JDIMENSION maxaccess;		/* max rows accessed by access_virt_barray */
   1.174 +  JDIMENSION rows_in_mem;	/* height of memory buffer */
   1.175 +  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
   1.176 +  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
   1.177 +  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
   1.178 +  boolean pre_zero;		/* pre-zero mode requested? */
   1.179 +  boolean dirty;		/* do current buffer contents need written? */
   1.180 +  boolean b_s_open;		/* is backing-store data valid? */
   1.181 +  jvirt_barray_ptr next;	/* link to next virtual barray control block */
   1.182 +  backing_store_info b_s_info;	/* System-dependent control info */
   1.183 +};
   1.184 +
   1.185 +
   1.186 +#ifdef MEM_STATS		/* optional extra stuff for statistics */
   1.187 +
   1.188 +LOCAL(void)
   1.189 +print_mem_stats (j_common_ptr cinfo, int pool_id)
   1.190 +{
   1.191 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.192 +  small_pool_ptr shdr_ptr;
   1.193 +  large_pool_ptr lhdr_ptr;
   1.194 +
   1.195 +  /* Since this is only a debugging stub, we can cheat a little by using
   1.196 +   * fprintf directly rather than going through the trace message code.
   1.197 +   * This is helpful because message parm array can't handle longs.
   1.198 +   */
   1.199 +  fprintf(stderr, "Freeing pool %d, total space = %ld\n",
   1.200 +	  pool_id, mem->total_space_allocated);
   1.201 +
   1.202 +  for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
   1.203 +       lhdr_ptr = lhdr_ptr->hdr.next) {
   1.204 +    fprintf(stderr, "  Large chunk used %ld\n",
   1.205 +	    (long) lhdr_ptr->hdr.bytes_used);
   1.206 +  }
   1.207 +
   1.208 +  for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
   1.209 +       shdr_ptr = shdr_ptr->hdr.next) {
   1.210 +    fprintf(stderr, "  Small chunk used %ld free %ld\n",
   1.211 +	    (long) shdr_ptr->hdr.bytes_used,
   1.212 +	    (long) shdr_ptr->hdr.bytes_left);
   1.213 +  }
   1.214 +}
   1.215 +
   1.216 +#endif /* MEM_STATS */
   1.217 +
   1.218 +
   1.219 +LOCAL(void)
   1.220 +out_of_memory (j_common_ptr cinfo, int which)
   1.221 +/* Report an out-of-memory error and stop execution */
   1.222 +/* If we compiled MEM_STATS support, report alloc requests before dying */
   1.223 +{
   1.224 +#ifdef MEM_STATS
   1.225 +  cinfo->err->trace_level = 2;	/* force self_destruct to report stats */
   1.226 +#endif
   1.227 +  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
   1.228 +}
   1.229 +
   1.230 +
   1.231 +/*
   1.232 + * Allocation of "small" objects.
   1.233 + *
   1.234 + * For these, we use pooled storage.  When a new pool must be created,
   1.235 + * we try to get enough space for the current request plus a "slop" factor,
   1.236 + * where the slop will be the amount of leftover space in the new pool.
   1.237 + * The speed vs. space tradeoff is largely determined by the slop values.
   1.238 + * A different slop value is provided for each pool class (lifetime),
   1.239 + * and we also distinguish the first pool of a class from later ones.
   1.240 + * NOTE: the values given work fairly well on both 16- and 32-bit-int
   1.241 + * machines, but may be too small if longs are 64 bits or more.
   1.242 + */
   1.243 +
   1.244 +static const size_t first_pool_slop[JPOOL_NUMPOOLS] = 
   1.245 +{
   1.246 +	1600,			/* first PERMANENT pool */
   1.247 +	16000			/* first IMAGE pool */
   1.248 +};
   1.249 +
   1.250 +static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = 
   1.251 +{
   1.252 +	0,			/* additional PERMANENT pools */
   1.253 +	5000			/* additional IMAGE pools */
   1.254 +};
   1.255 +
   1.256 +#define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
   1.257 +
   1.258 +
   1.259 +METHODDEF(void *)
   1.260 +alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
   1.261 +/* Allocate a "small" object */
   1.262 +{
   1.263 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.264 +  small_pool_ptr hdr_ptr, prev_hdr_ptr;
   1.265 +  char * data_ptr;
   1.266 +  size_t odd_bytes, min_request, slop;
   1.267 +
   1.268 +  /* Check for unsatisfiable request (do now to ensure no overflow below) */
   1.269 +  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
   1.270 +    out_of_memory(cinfo, 1);	/* request exceeds malloc's ability */
   1.271 +
   1.272 +  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
   1.273 +  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
   1.274 +  if (odd_bytes > 0)
   1.275 +    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
   1.276 +
   1.277 +  /* See if space is available in any existing pool */
   1.278 +  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
   1.279 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
   1.280 +  prev_hdr_ptr = NULL;
   1.281 +  hdr_ptr = mem->small_list[pool_id];
   1.282 +  while (hdr_ptr != NULL) {
   1.283 +    if (hdr_ptr->hdr.bytes_left >= sizeofobject)
   1.284 +      break;			/* found pool with enough space */
   1.285 +    prev_hdr_ptr = hdr_ptr;
   1.286 +    hdr_ptr = hdr_ptr->hdr.next;
   1.287 +  }
   1.288 +
   1.289 +  /* Time to make a new pool? */
   1.290 +  if (hdr_ptr == NULL) {
   1.291 +    /* min_request is what we need now, slop is what will be leftover */
   1.292 +    min_request = sizeofobject + SIZEOF(small_pool_hdr);
   1.293 +    if (prev_hdr_ptr == NULL)	/* first pool in class? */
   1.294 +      slop = first_pool_slop[pool_id];
   1.295 +    else
   1.296 +      slop = extra_pool_slop[pool_id];
   1.297 +    /* Don't ask for more than MAX_ALLOC_CHUNK */
   1.298 +    if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
   1.299 +      slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
   1.300 +    /* Try to get space, if fail reduce slop and try again */
   1.301 +    for (;;) {
   1.302 +      hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
   1.303 +      if (hdr_ptr != NULL)
   1.304 +	break;
   1.305 +      slop /= 2;
   1.306 +      if (slop < MIN_SLOP)	/* give up when it gets real small */
   1.307 +	out_of_memory(cinfo, 2); /* jpeg_get_small failed */
   1.308 +    }
   1.309 +    mem->total_space_allocated += min_request + slop;
   1.310 +    /* Success, initialize the new pool header and add to end of list */
   1.311 +    hdr_ptr->hdr.next = NULL;
   1.312 +    hdr_ptr->hdr.bytes_used = 0;
   1.313 +    hdr_ptr->hdr.bytes_left = sizeofobject + slop;
   1.314 +    if (prev_hdr_ptr == NULL)	/* first pool in class? */
   1.315 +      mem->small_list[pool_id] = hdr_ptr;
   1.316 +    else
   1.317 +      prev_hdr_ptr->hdr.next = hdr_ptr;
   1.318 +  }
   1.319 +
   1.320 +  /* OK, allocate the object from the current pool */
   1.321 +  data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
   1.322 +  data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
   1.323 +  hdr_ptr->hdr.bytes_used += sizeofobject;
   1.324 +  hdr_ptr->hdr.bytes_left -= sizeofobject;
   1.325 +
   1.326 +  return (void *) data_ptr;
   1.327 +}
   1.328 +
   1.329 +
   1.330 +/*
   1.331 + * Allocation of "large" objects.
   1.332 + *
   1.333 + * The external semantics of these are the same as "small" objects,
   1.334 + * except that FAR pointers are used on 80x86.  However the pool
   1.335 + * management heuristics are quite different.  We assume that each
   1.336 + * request is large enough that it may as well be passed directly to
   1.337 + * jpeg_get_large; the pool management just links everything together
   1.338 + * so that we can free it all on demand.
   1.339 + * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
   1.340 + * structures.  The routines that create these structures (see below)
   1.341 + * deliberately bunch rows together to ensure a large request size.
   1.342 + */
   1.343 +
   1.344 +METHODDEF(void FAR *)
   1.345 +alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
   1.346 +/* Allocate a "large" object */
   1.347 +{
   1.348 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.349 +  large_pool_ptr hdr_ptr;
   1.350 +  size_t odd_bytes;
   1.351 +
   1.352 +  /* Check for unsatisfiable request (do now to ensure no overflow below) */
   1.353 +  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
   1.354 +    out_of_memory(cinfo, 3);	/* request exceeds malloc's ability */
   1.355 +
   1.356 +  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
   1.357 +  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
   1.358 +  if (odd_bytes > 0)
   1.359 +    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
   1.360 +
   1.361 +  /* Always make a new pool */
   1.362 +  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
   1.363 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
   1.364 +
   1.365 +  hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
   1.366 +					    SIZEOF(large_pool_hdr));
   1.367 +  if (hdr_ptr == NULL)
   1.368 +    out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
   1.369 +  mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
   1.370 +
   1.371 +  /* Success, initialize the new pool header and add to list */
   1.372 +  hdr_ptr->hdr.next = mem->large_list[pool_id];
   1.373 +  /* We maintain space counts in each pool header for statistical purposes,
   1.374 +   * even though they are not needed for allocation.
   1.375 +   */
   1.376 +  hdr_ptr->hdr.bytes_used = sizeofobject;
   1.377 +  hdr_ptr->hdr.bytes_left = 0;
   1.378 +  mem->large_list[pool_id] = hdr_ptr;
   1.379 +
   1.380 +  return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
   1.381 +}
   1.382 +
   1.383 +
   1.384 +/*
   1.385 + * Creation of 2-D sample arrays.
   1.386 + * The pointers are in near heap, the samples themselves in FAR heap.
   1.387 + *
   1.388 + * To minimize allocation overhead and to allow I/O of large contiguous
   1.389 + * blocks, we allocate the sample rows in groups of as many rows as possible
   1.390 + * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
   1.391 + * NB: the virtual array control routines, later in this file, know about
   1.392 + * this chunking of rows.  The rowsperchunk value is left in the mem manager
   1.393 + * object so that it can be saved away if this sarray is the workspace for
   1.394 + * a virtual array.
   1.395 + */
   1.396 +
   1.397 +METHODDEF(JSAMPARRAY)
   1.398 +alloc_sarray (j_common_ptr cinfo, int pool_id,
   1.399 +	      JDIMENSION samplesperrow, JDIMENSION numrows)
   1.400 +/* Allocate a 2-D sample array */
   1.401 +{
   1.402 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.403 +  JSAMPARRAY result;
   1.404 +  JSAMPROW workspace;
   1.405 +  JDIMENSION rowsperchunk, currow, i;
   1.406 +  long ltemp;
   1.407 +
   1.408 +  /* Calculate max # of rows allowed in one allocation chunk */
   1.409 +  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
   1.410 +	  ((long) samplesperrow * SIZEOF(JSAMPLE));
   1.411 +  if (ltemp <= 0)
   1.412 +    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
   1.413 +  if (ltemp < (long) numrows)
   1.414 +    rowsperchunk = (JDIMENSION) ltemp;
   1.415 +  else
   1.416 +    rowsperchunk = numrows;
   1.417 +  mem->last_rowsperchunk = rowsperchunk;
   1.418 +
   1.419 +  /* Get space for row pointers (small object) */
   1.420 +  result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
   1.421 +				    (size_t) (numrows * SIZEOF(JSAMPROW)));
   1.422 +
   1.423 +  /* Get the rows themselves (large objects) */
   1.424 +  currow = 0;
   1.425 +  while (currow < numrows) {
   1.426 +    rowsperchunk = MIN(rowsperchunk, numrows - currow);
   1.427 +    workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
   1.428 +	(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
   1.429 +		  * SIZEOF(JSAMPLE)));
   1.430 +    for (i = rowsperchunk; i > 0; i--) {
   1.431 +      result[currow++] = workspace;
   1.432 +      workspace += samplesperrow;
   1.433 +    }
   1.434 +  }
   1.435 +
   1.436 +  return result;
   1.437 +}
   1.438 +
   1.439 +
   1.440 +/*
   1.441 + * Creation of 2-D coefficient-block arrays.
   1.442 + * This is essentially the same as the code for sample arrays, above.
   1.443 + */
   1.444 +
   1.445 +METHODDEF(JBLOCKARRAY)
   1.446 +alloc_barray (j_common_ptr cinfo, int pool_id,
   1.447 +	      JDIMENSION blocksperrow, JDIMENSION numrows)
   1.448 +/* Allocate a 2-D coefficient-block array */
   1.449 +{
   1.450 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.451 +  JBLOCKARRAY result;
   1.452 +  JBLOCKROW workspace;
   1.453 +  JDIMENSION rowsperchunk, currow, i;
   1.454 +  long ltemp;
   1.455 +
   1.456 +  /* Calculate max # of rows allowed in one allocation chunk */
   1.457 +  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
   1.458 +	  ((long) blocksperrow * SIZEOF(JBLOCK));
   1.459 +  if (ltemp <= 0)
   1.460 +    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
   1.461 +  if (ltemp < (long) numrows)
   1.462 +    rowsperchunk = (JDIMENSION) ltemp;
   1.463 +  else
   1.464 +    rowsperchunk = numrows;
   1.465 +  mem->last_rowsperchunk = rowsperchunk;
   1.466 +
   1.467 +  /* Get space for row pointers (small object) */
   1.468 +  result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
   1.469 +				     (size_t) (numrows * SIZEOF(JBLOCKROW)));
   1.470 +
   1.471 +  /* Get the rows themselves (large objects) */
   1.472 +  currow = 0;
   1.473 +  while (currow < numrows) {
   1.474 +    rowsperchunk = MIN(rowsperchunk, numrows - currow);
   1.475 +    workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
   1.476 +	(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
   1.477 +		  * SIZEOF(JBLOCK)));
   1.478 +    for (i = rowsperchunk; i > 0; i--) {
   1.479 +      result[currow++] = workspace;
   1.480 +      workspace += blocksperrow;
   1.481 +    }
   1.482 +  }
   1.483 +
   1.484 +  return result;
   1.485 +}
   1.486 +
   1.487 +
   1.488 +/*
   1.489 + * About virtual array management:
   1.490 + *
   1.491 + * The above "normal" array routines are only used to allocate strip buffers
   1.492 + * (as wide as the image, but just a few rows high).  Full-image-sized buffers
   1.493 + * are handled as "virtual" arrays.  The array is still accessed a strip at a
   1.494 + * time, but the memory manager must save the whole array for repeated
   1.495 + * accesses.  The intended implementation is that there is a strip buffer in
   1.496 + * memory (as high as is possible given the desired memory limit), plus a
   1.497 + * backing file that holds the rest of the array.
   1.498 + *
   1.499 + * The request_virt_array routines are told the total size of the image and
   1.500 + * the maximum number of rows that will be accessed at once.  The in-memory
   1.501 + * buffer must be at least as large as the maxaccess value.
   1.502 + *
   1.503 + * The request routines create control blocks but not the in-memory buffers.
   1.504 + * That is postponed until realize_virt_arrays is called.  At that time the
   1.505 + * total amount of space needed is known (approximately, anyway), so free
   1.506 + * memory can be divided up fairly.
   1.507 + *
   1.508 + * The access_virt_array routines are responsible for making a specific strip
   1.509 + * area accessible (after reading or writing the backing file, if necessary).
   1.510 + * Note that the access routines are told whether the caller intends to modify
   1.511 + * the accessed strip; during a read-only pass this saves having to rewrite
   1.512 + * data to disk.  The access routines are also responsible for pre-zeroing
   1.513 + * any newly accessed rows, if pre-zeroing was requested.
   1.514 + *
   1.515 + * In current usage, the access requests are usually for nonoverlapping
   1.516 + * strips; that is, successive access start_row numbers differ by exactly
   1.517 + * num_rows = maxaccess.  This means we can get good performance with simple
   1.518 + * buffer dump/reload logic, by making the in-memory buffer be a multiple
   1.519 + * of the access height; then there will never be accesses across bufferload
   1.520 + * boundaries.  The code will still work with overlapping access requests,
   1.521 + * but it doesn't handle bufferload overlaps very efficiently.
   1.522 + */
   1.523 +
   1.524 +
   1.525 +METHODDEF(jvirt_sarray_ptr)
   1.526 +request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
   1.527 +		     JDIMENSION samplesperrow, JDIMENSION numrows,
   1.528 +		     JDIMENSION maxaccess)
   1.529 +/* Request a virtual 2-D sample array */
   1.530 +{
   1.531 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.532 +  jvirt_sarray_ptr result;
   1.533 +
   1.534 +  /* Only IMAGE-lifetime virtual arrays are currently supported */
   1.535 +  if (pool_id != JPOOL_IMAGE)
   1.536 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
   1.537 +
   1.538 +  /* get control block */
   1.539 +  result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
   1.540 +					  SIZEOF(struct jvirt_sarray_control));
   1.541 +
   1.542 +  result->mem_buffer = NULL;	/* marks array not yet realized */
   1.543 +  result->rows_in_array = numrows;
   1.544 +  result->samplesperrow = samplesperrow;
   1.545 +  result->maxaccess = maxaccess;
   1.546 +  result->pre_zero = pre_zero;
   1.547 +  result->b_s_open = FALSE;	/* no associated backing-store object */
   1.548 +  result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
   1.549 +  mem->virt_sarray_list = result;
   1.550 +
   1.551 +  return result;
   1.552 +}
   1.553 +
   1.554 +
   1.555 +METHODDEF(jvirt_barray_ptr)
   1.556 +request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
   1.557 +		     JDIMENSION blocksperrow, JDIMENSION numrows,
   1.558 +		     JDIMENSION maxaccess)
   1.559 +/* Request a virtual 2-D coefficient-block array */
   1.560 +{
   1.561 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.562 +  jvirt_barray_ptr result;
   1.563 +
   1.564 +  /* Only IMAGE-lifetime virtual arrays are currently supported */
   1.565 +  if (pool_id != JPOOL_IMAGE)
   1.566 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
   1.567 +
   1.568 +  /* get control block */
   1.569 +  result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
   1.570 +					  SIZEOF(struct jvirt_barray_control));
   1.571 +
   1.572 +  result->mem_buffer = NULL;	/* marks array not yet realized */
   1.573 +  result->rows_in_array = numrows;
   1.574 +  result->blocksperrow = blocksperrow;
   1.575 +  result->maxaccess = maxaccess;
   1.576 +  result->pre_zero = pre_zero;
   1.577 +  result->b_s_open = FALSE;	/* no associated backing-store object */
   1.578 +  result->next = mem->virt_barray_list; /* add to list of virtual arrays */
   1.579 +  mem->virt_barray_list = result;
   1.580 +
   1.581 +  return result;
   1.582 +}
   1.583 +
   1.584 +
   1.585 +METHODDEF(void)
   1.586 +realize_virt_arrays (j_common_ptr cinfo)
   1.587 +/* Allocate the in-memory buffers for any unrealized virtual arrays */
   1.588 +{
   1.589 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.590 +  long space_per_minheight, maximum_space, avail_mem;
   1.591 +  long minheights, max_minheights;
   1.592 +  jvirt_sarray_ptr sptr;
   1.593 +  jvirt_barray_ptr bptr;
   1.594 +
   1.595 +  /* Compute the minimum space needed (maxaccess rows in each buffer)
   1.596 +   * and the maximum space needed (full image height in each buffer).
   1.597 +   * These may be of use to the system-dependent jpeg_mem_available routine.
   1.598 +   */
   1.599 +  space_per_minheight = 0;
   1.600 +  maximum_space = 0;
   1.601 +  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
   1.602 +    if (sptr->mem_buffer == NULL) { /* if not realized yet */
   1.603 +      space_per_minheight += (long) sptr->maxaccess *
   1.604 +			     (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
   1.605 +      maximum_space += (long) sptr->rows_in_array *
   1.606 +		       (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
   1.607 +    }
   1.608 +  }
   1.609 +  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
   1.610 +    if (bptr->mem_buffer == NULL) { /* if not realized yet */
   1.611 +      space_per_minheight += (long) bptr->maxaccess *
   1.612 +			     (long) bptr->blocksperrow * SIZEOF(JBLOCK);
   1.613 +      maximum_space += (long) bptr->rows_in_array *
   1.614 +		       (long) bptr->blocksperrow * SIZEOF(JBLOCK);
   1.615 +    }
   1.616 +  }
   1.617 +
   1.618 +  if (space_per_minheight <= 0)
   1.619 +    return;			/* no unrealized arrays, no work */
   1.620 +
   1.621 +  /* Determine amount of memory to actually use; this is system-dependent. */
   1.622 +  avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
   1.623 +				 mem->total_space_allocated);
   1.624 +
   1.625 +  /* If the maximum space needed is available, make all the buffers full
   1.626 +   * height; otherwise parcel it out with the same number of minheights
   1.627 +   * in each buffer.
   1.628 +   */
   1.629 +  if (avail_mem >= maximum_space)
   1.630 +    max_minheights = 1000000000L;
   1.631 +  else {
   1.632 +    max_minheights = avail_mem / space_per_minheight;
   1.633 +    /* If there doesn't seem to be enough space, try to get the minimum
   1.634 +     * anyway.  This allows a "stub" implementation of jpeg_mem_available().
   1.635 +     */
   1.636 +    if (max_minheights <= 0)
   1.637 +      max_minheights = 1;
   1.638 +  }
   1.639 +
   1.640 +  /* Allocate the in-memory buffers and initialize backing store as needed. */
   1.641 +
   1.642 +  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
   1.643 +    if (sptr->mem_buffer == NULL) { /* if not realized yet */
   1.644 +      minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
   1.645 +      if (minheights <= max_minheights) {
   1.646 +	/* This buffer fits in memory */
   1.647 +	sptr->rows_in_mem = sptr->rows_in_array;
   1.648 +      } else {
   1.649 +	/* It doesn't fit in memory, create backing store. */
   1.650 +	sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
   1.651 +	jpeg_open_backing_store(cinfo, & sptr->b_s_info,
   1.652 +				(long) sptr->rows_in_array *
   1.653 +				(long) sptr->samplesperrow *
   1.654 +				(long) SIZEOF(JSAMPLE));
   1.655 +	sptr->b_s_open = TRUE;
   1.656 +      }
   1.657 +      sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
   1.658 +				      sptr->samplesperrow, sptr->rows_in_mem);
   1.659 +      sptr->rowsperchunk = mem->last_rowsperchunk;
   1.660 +      sptr->cur_start_row = 0;
   1.661 +      sptr->first_undef_row = 0;
   1.662 +      sptr->dirty = FALSE;
   1.663 +    }
   1.664 +  }
   1.665 +
   1.666 +  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
   1.667 +    if (bptr->mem_buffer == NULL) { /* if not realized yet */
   1.668 +      minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
   1.669 +      if (minheights <= max_minheights) {
   1.670 +	/* This buffer fits in memory */
   1.671 +	bptr->rows_in_mem = bptr->rows_in_array;
   1.672 +      } else {
   1.673 +	/* It doesn't fit in memory, create backing store. */
   1.674 +	bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
   1.675 +	jpeg_open_backing_store(cinfo, & bptr->b_s_info,
   1.676 +				(long) bptr->rows_in_array *
   1.677 +				(long) bptr->blocksperrow *
   1.678 +				(long) SIZEOF(JBLOCK));
   1.679 +	bptr->b_s_open = TRUE;
   1.680 +      }
   1.681 +      bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
   1.682 +				      bptr->blocksperrow, bptr->rows_in_mem);
   1.683 +      bptr->rowsperchunk = mem->last_rowsperchunk;
   1.684 +      bptr->cur_start_row = 0;
   1.685 +      bptr->first_undef_row = 0;
   1.686 +      bptr->dirty = FALSE;
   1.687 +    }
   1.688 +  }
   1.689 +}
   1.690 +
   1.691 +
   1.692 +LOCAL(void)
   1.693 +do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
   1.694 +/* Do backing store read or write of a virtual sample array */
   1.695 +{
   1.696 +  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
   1.697 +
   1.698 +  bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
   1.699 +  file_offset = ptr->cur_start_row * bytesperrow;
   1.700 +  /* Loop to read or write each allocation chunk in mem_buffer */
   1.701 +  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
   1.702 +    /* One chunk, but check for short chunk at end of buffer */
   1.703 +    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
   1.704 +    /* Transfer no more than is currently defined */
   1.705 +    thisrow = (long) ptr->cur_start_row + i;
   1.706 +    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
   1.707 +    /* Transfer no more than fits in file */
   1.708 +    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
   1.709 +    if (rows <= 0)		/* this chunk might be past end of file! */
   1.710 +      break;
   1.711 +    byte_count = rows * bytesperrow;
   1.712 +    if (writing)
   1.713 +      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
   1.714 +					    (void FAR *) ptr->mem_buffer[i],
   1.715 +					    file_offset, byte_count);
   1.716 +    else
   1.717 +      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
   1.718 +					   (void FAR *) ptr->mem_buffer[i],
   1.719 +					   file_offset, byte_count);
   1.720 +    file_offset += byte_count;
   1.721 +  }
   1.722 +}
   1.723 +
   1.724 +
   1.725 +LOCAL(void)
   1.726 +do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
   1.727 +/* Do backing store read or write of a virtual coefficient-block array */
   1.728 +{
   1.729 +  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
   1.730 +
   1.731 +  bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
   1.732 +  file_offset = ptr->cur_start_row * bytesperrow;
   1.733 +  /* Loop to read or write each allocation chunk in mem_buffer */
   1.734 +  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
   1.735 +    /* One chunk, but check for short chunk at end of buffer */
   1.736 +    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
   1.737 +    /* Transfer no more than is currently defined */
   1.738 +    thisrow = (long) ptr->cur_start_row + i;
   1.739 +    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
   1.740 +    /* Transfer no more than fits in file */
   1.741 +    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
   1.742 +    if (rows <= 0)		/* this chunk might be past end of file! */
   1.743 +      break;
   1.744 +    byte_count = rows * bytesperrow;
   1.745 +    if (writing)
   1.746 +      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
   1.747 +					    (void FAR *) ptr->mem_buffer[i],
   1.748 +					    file_offset, byte_count);
   1.749 +    else
   1.750 +      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
   1.751 +					   (void FAR *) ptr->mem_buffer[i],
   1.752 +					   file_offset, byte_count);
   1.753 +    file_offset += byte_count;
   1.754 +  }
   1.755 +}
   1.756 +
   1.757 +
   1.758 +METHODDEF(JSAMPARRAY)
   1.759 +access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
   1.760 +		    JDIMENSION start_row, JDIMENSION num_rows,
   1.761 +		    boolean writable)
   1.762 +/* Access the part of a virtual sample array starting at start_row */
   1.763 +/* and extending for num_rows rows.  writable is true if  */
   1.764 +/* caller intends to modify the accessed area. */
   1.765 +{
   1.766 +  JDIMENSION end_row = start_row + num_rows;
   1.767 +  JDIMENSION undef_row;
   1.768 +
   1.769 +  /* debugging check */
   1.770 +  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
   1.771 +      ptr->mem_buffer == NULL)
   1.772 +    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
   1.773 +
   1.774 +  /* Make the desired part of the virtual array accessible */
   1.775 +  if (start_row < ptr->cur_start_row ||
   1.776 +      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
   1.777 +    if (! ptr->b_s_open)
   1.778 +      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
   1.779 +    /* Flush old buffer contents if necessary */
   1.780 +    if (ptr->dirty) {
   1.781 +      do_sarray_io(cinfo, ptr, TRUE);
   1.782 +      ptr->dirty = FALSE;
   1.783 +    }
   1.784 +    /* Decide what part of virtual array to access.
   1.785 +     * Algorithm: if target address > current window, assume forward scan,
   1.786 +     * load starting at target address.  If target address < current window,
   1.787 +     * assume backward scan, load so that target area is top of window.
   1.788 +     * Note that when switching from forward write to forward read, will have
   1.789 +     * start_row = 0, so the limiting case applies and we load from 0 anyway.
   1.790 +     */
   1.791 +    if (start_row > ptr->cur_start_row) {
   1.792 +      ptr->cur_start_row = start_row;
   1.793 +    } else {
   1.794 +      /* use long arithmetic here to avoid overflow & unsigned problems */
   1.795 +      long ltemp;
   1.796 +
   1.797 +      ltemp = (long) end_row - (long) ptr->rows_in_mem;
   1.798 +      if (ltemp < 0)
   1.799 +	ltemp = 0;		/* don't fall off front end of file */
   1.800 +      ptr->cur_start_row = (JDIMENSION) ltemp;
   1.801 +    }
   1.802 +    /* Read in the selected part of the array.
   1.803 +     * During the initial write pass, we will do no actual read
   1.804 +     * because the selected part is all undefined.
   1.805 +     */
   1.806 +    do_sarray_io(cinfo, ptr, FALSE);
   1.807 +  }
   1.808 +  /* Ensure the accessed part of the array is defined; prezero if needed.
   1.809 +   * To improve locality of access, we only prezero the part of the array
   1.810 +   * that the caller is about to access, not the entire in-memory array.
   1.811 +   */
   1.812 +  if (ptr->first_undef_row < end_row) {
   1.813 +    if (ptr->first_undef_row < start_row) {
   1.814 +      if (writable)		/* writer skipped over a section of array */
   1.815 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
   1.816 +      undef_row = start_row;	/* but reader is allowed to read ahead */
   1.817 +    } else {
   1.818 +      undef_row = ptr->first_undef_row;
   1.819 +    }
   1.820 +    if (writable)
   1.821 +      ptr->first_undef_row = end_row;
   1.822 +    if (ptr->pre_zero) {
   1.823 +      size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
   1.824 +      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
   1.825 +      end_row -= ptr->cur_start_row;
   1.826 +      while (undef_row < end_row) {
   1.827 +	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
   1.828 +	undef_row++;
   1.829 +      }
   1.830 +    } else {
   1.831 +      if (! writable)		/* reader looking at undefined data */
   1.832 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
   1.833 +    }
   1.834 +  }
   1.835 +  /* Flag the buffer dirty if caller will write in it */
   1.836 +  if (writable)
   1.837 +    ptr->dirty = TRUE;
   1.838 +  /* Return address of proper part of the buffer */
   1.839 +  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
   1.840 +}
   1.841 +
   1.842 +
   1.843 +METHODDEF(JBLOCKARRAY)
   1.844 +access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
   1.845 +		    JDIMENSION start_row, JDIMENSION num_rows,
   1.846 +		    boolean writable)
   1.847 +/* Access the part of a virtual block array starting at start_row */
   1.848 +/* and extending for num_rows rows.  writable is true if  */
   1.849 +/* caller intends to modify the accessed area. */
   1.850 +{
   1.851 +  JDIMENSION end_row = start_row + num_rows;
   1.852 +  JDIMENSION undef_row;
   1.853 +
   1.854 +  /* debugging check */
   1.855 +  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
   1.856 +      ptr->mem_buffer == NULL)
   1.857 +    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
   1.858 +
   1.859 +  /* Make the desired part of the virtual array accessible */
   1.860 +  if (start_row < ptr->cur_start_row ||
   1.861 +      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
   1.862 +    if (! ptr->b_s_open)
   1.863 +      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
   1.864 +    /* Flush old buffer contents if necessary */
   1.865 +    if (ptr->dirty) {
   1.866 +      do_barray_io(cinfo, ptr, TRUE);
   1.867 +      ptr->dirty = FALSE;
   1.868 +    }
   1.869 +    /* Decide what part of virtual array to access.
   1.870 +     * Algorithm: if target address > current window, assume forward scan,
   1.871 +     * load starting at target address.  If target address < current window,
   1.872 +     * assume backward scan, load so that target area is top of window.
   1.873 +     * Note that when switching from forward write to forward read, will have
   1.874 +     * start_row = 0, so the limiting case applies and we load from 0 anyway.
   1.875 +     */
   1.876 +    if (start_row > ptr->cur_start_row) {
   1.877 +      ptr->cur_start_row = start_row;
   1.878 +    } else {
   1.879 +      /* use long arithmetic here to avoid overflow & unsigned problems */
   1.880 +      long ltemp;
   1.881 +
   1.882 +      ltemp = (long) end_row - (long) ptr->rows_in_mem;
   1.883 +      if (ltemp < 0)
   1.884 +	ltemp = 0;		/* don't fall off front end of file */
   1.885 +      ptr->cur_start_row = (JDIMENSION) ltemp;
   1.886 +    }
   1.887 +    /* Read in the selected part of the array.
   1.888 +     * During the initial write pass, we will do no actual read
   1.889 +     * because the selected part is all undefined.
   1.890 +     */
   1.891 +    do_barray_io(cinfo, ptr, FALSE);
   1.892 +  }
   1.893 +  /* Ensure the accessed part of the array is defined; prezero if needed.
   1.894 +   * To improve locality of access, we only prezero the part of the array
   1.895 +   * that the caller is about to access, not the entire in-memory array.
   1.896 +   */
   1.897 +  if (ptr->first_undef_row < end_row) {
   1.898 +    if (ptr->first_undef_row < start_row) {
   1.899 +      if (writable)		/* writer skipped over a section of array */
   1.900 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
   1.901 +      undef_row = start_row;	/* but reader is allowed to read ahead */
   1.902 +    } else {
   1.903 +      undef_row = ptr->first_undef_row;
   1.904 +    }
   1.905 +    if (writable)
   1.906 +      ptr->first_undef_row = end_row;
   1.907 +    if (ptr->pre_zero) {
   1.908 +      size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
   1.909 +      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
   1.910 +      end_row -= ptr->cur_start_row;
   1.911 +      while (undef_row < end_row) {
   1.912 +	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
   1.913 +	undef_row++;
   1.914 +      }
   1.915 +    } else {
   1.916 +      if (! writable)		/* reader looking at undefined data */
   1.917 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
   1.918 +    }
   1.919 +  }
   1.920 +  /* Flag the buffer dirty if caller will write in it */
   1.921 +  if (writable)
   1.922 +    ptr->dirty = TRUE;
   1.923 +  /* Return address of proper part of the buffer */
   1.924 +  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
   1.925 +}
   1.926 +
   1.927 +
   1.928 +/*
   1.929 + * Release all objects belonging to a specified pool.
   1.930 + */
   1.931 +
   1.932 +METHODDEF(void)
   1.933 +free_pool (j_common_ptr cinfo, int pool_id)
   1.934 +{
   1.935 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
   1.936 +  small_pool_ptr shdr_ptr;
   1.937 +  large_pool_ptr lhdr_ptr;
   1.938 +  size_t space_freed;
   1.939 +
   1.940 +  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
   1.941 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
   1.942 +
   1.943 +#ifdef MEM_STATS
   1.944 +  if (cinfo->err->trace_level > 1)
   1.945 +    print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
   1.946 +#endif
   1.947 +
   1.948 +  /* If freeing IMAGE pool, close any virtual arrays first */
   1.949 +  if (pool_id == JPOOL_IMAGE) {
   1.950 +    jvirt_sarray_ptr sptr;
   1.951 +    jvirt_barray_ptr bptr;
   1.952 +
   1.953 +    for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
   1.954 +      if (sptr->b_s_open) {	/* there may be no backing store */
   1.955 +	sptr->b_s_open = FALSE;	/* prevent recursive close if error */
   1.956 +	(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
   1.957 +      }
   1.958 +    }
   1.959 +    mem->virt_sarray_list = NULL;
   1.960 +    for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
   1.961 +      if (bptr->b_s_open) {	/* there may be no backing store */
   1.962 +	bptr->b_s_open = FALSE;	/* prevent recursive close if error */
   1.963 +	(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
   1.964 +      }
   1.965 +    }
   1.966 +    mem->virt_barray_list = NULL;
   1.967 +  }
   1.968 +
   1.969 +  /* Release large objects */
   1.970 +  lhdr_ptr = mem->large_list[pool_id];
   1.971 +  mem->large_list[pool_id] = NULL;
   1.972 +
   1.973 +  while (lhdr_ptr != NULL) {
   1.974 +    large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
   1.975 +    space_freed = lhdr_ptr->hdr.bytes_used +
   1.976 +		  lhdr_ptr->hdr.bytes_left +
   1.977 +		  SIZEOF(large_pool_hdr);
   1.978 +    jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
   1.979 +    mem->total_space_allocated -= space_freed;
   1.980 +    lhdr_ptr = next_lhdr_ptr;
   1.981 +  }
   1.982 +
   1.983 +  /* Release small objects */
   1.984 +  shdr_ptr = mem->small_list[pool_id];
   1.985 +  mem->small_list[pool_id] = NULL;
   1.986 +
   1.987 +  while (shdr_ptr != NULL) {
   1.988 +    small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
   1.989 +    space_freed = shdr_ptr->hdr.bytes_used +
   1.990 +		  shdr_ptr->hdr.bytes_left +
   1.991 +		  SIZEOF(small_pool_hdr);
   1.992 +    jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
   1.993 +    mem->total_space_allocated -= space_freed;
   1.994 +    shdr_ptr = next_shdr_ptr;
   1.995 +  }
   1.996 +}
   1.997 +
   1.998 +
   1.999 +/*
  1.1000 + * Close up shop entirely.
  1.1001 + * Note that this cannot be called unless cinfo->mem is non-NULL.
  1.1002 + */
  1.1003 +
  1.1004 +METHODDEF(void)
  1.1005 +self_destruct (j_common_ptr cinfo)
  1.1006 +{
  1.1007 +  int pool;
  1.1008 +
  1.1009 +  /* Close all backing store, release all memory.
  1.1010 +   * Releasing pools in reverse order might help avoid fragmentation
  1.1011 +   * with some (brain-damaged) malloc libraries.
  1.1012 +   */
  1.1013 +  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  1.1014 +    free_pool(cinfo, pool);
  1.1015 +  }
  1.1016 +
  1.1017 +  /* Release the memory manager control block too. */
  1.1018 +  jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  1.1019 +  cinfo->mem = NULL;		/* ensures I will be called only once */
  1.1020 +
  1.1021 +  jpeg_mem_term(cinfo);		/* system-dependent cleanup */
  1.1022 +}
  1.1023 +
  1.1024 +
  1.1025 +/*
  1.1026 + * Memory manager initialization.
  1.1027 + * When this is called, only the error manager pointer is valid in cinfo!
  1.1028 + */
  1.1029 +
  1.1030 +GLOBAL(void)
  1.1031 +jinit_memory_mgr (j_common_ptr cinfo)
  1.1032 +{
  1.1033 +  my_mem_ptr mem;
  1.1034 +  long max_to_use;
  1.1035 +  int pool;
  1.1036 +  size_t test_mac;
  1.1037 +
  1.1038 +  cinfo->mem = NULL;		/* for safety if init fails */
  1.1039 +
  1.1040 +  /* Check for configuration errors.
  1.1041 +   * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  1.1042 +   * doesn't reflect any real hardware alignment requirement.
  1.1043 +   * The test is a little tricky: for X>0, X and X-1 have no one-bits
  1.1044 +   * in common if and only if X is a power of 2, ie has only one one-bit.
  1.1045 +   * Some compilers may give an "unreachable code" warning here; ignore it.
  1.1046 +   */
  1.1047 +  if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  1.1048 +    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  1.1049 +  /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  1.1050 +   * a multiple of SIZEOF(ALIGN_TYPE).
  1.1051 +   * Again, an "unreachable code" warning may be ignored here.
  1.1052 +   * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  1.1053 +   */
  1.1054 +  test_mac = (size_t) MAX_ALLOC_CHUNK;
  1.1055 +  if ((long) test_mac != MAX_ALLOC_CHUNK ||
  1.1056 +      (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  1.1057 +    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  1.1058 +
  1.1059 +  max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  1.1060 +
  1.1061 +  /* Attempt to allocate memory manager's control block */
  1.1062 +  mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  1.1063 +
  1.1064 +  if (mem == NULL) {
  1.1065 +    jpeg_mem_term(cinfo);	/* system-dependent cleanup */
  1.1066 +    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  1.1067 +  }
  1.1068 +
  1.1069 +  /* OK, fill in the method pointers */
  1.1070 +  mem->pub.alloc_small = alloc_small;
  1.1071 +  mem->pub.alloc_large = alloc_large;
  1.1072 +  mem->pub.alloc_sarray = alloc_sarray;
  1.1073 +  mem->pub.alloc_barray = alloc_barray;
  1.1074 +  mem->pub.request_virt_sarray = request_virt_sarray;
  1.1075 +  mem->pub.request_virt_barray = request_virt_barray;
  1.1076 +  mem->pub.realize_virt_arrays = realize_virt_arrays;
  1.1077 +  mem->pub.access_virt_sarray = access_virt_sarray;
  1.1078 +  mem->pub.access_virt_barray = access_virt_barray;
  1.1079 +  mem->pub.free_pool = free_pool;
  1.1080 +  mem->pub.self_destruct = self_destruct;
  1.1081 +
  1.1082 +  /* Make MAX_ALLOC_CHUNK accessible to other modules */
  1.1083 +  mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  1.1084 +
  1.1085 +  /* Initialize working state */
  1.1086 +  mem->pub.max_memory_to_use = max_to_use;
  1.1087 +
  1.1088 +  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  1.1089 +    mem->small_list[pool] = NULL;
  1.1090 +    mem->large_list[pool] = NULL;
  1.1091 +  }
  1.1092 +  mem->virt_sarray_list = NULL;
  1.1093 +  mem->virt_barray_list = NULL;
  1.1094 +
  1.1095 +  mem->total_space_allocated = SIZEOF(my_memory_mgr);
  1.1096 +
  1.1097 +  /* Declare ourselves open for business */
  1.1098 +  cinfo->mem = & mem->pub;
  1.1099 +
  1.1100 +  /* Check for an environment variable JPEGMEM; if found, override the
  1.1101 +   * default max_memory setting from jpeg_mem_init.  Note that the
  1.1102 +   * surrounding application may again override this value.
  1.1103 +   * If your system doesn't support getenv(), define NO_GETENV to disable
  1.1104 +   * this feature.
  1.1105 +   */
  1.1106 +#ifndef NO_GETENV
  1.1107 +  { char * memenv;
  1.1108 +
  1.1109 +    if ((memenv = getenv("JPEGMEM")) != NULL) {
  1.1110 +      char ch = 'x';
  1.1111 +
  1.1112 +      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  1.1113 +	if (ch == 'm' || ch == 'M')
  1.1114 +	  max_to_use *= 1000L;
  1.1115 +	mem->pub.max_memory_to_use = max_to_use * 1000L;
  1.1116 +      }
  1.1117 +    }
  1.1118 +  }
  1.1119 +#endif
  1.1120 +
  1.1121 +}