8 * Copyright (C) 1991-1998, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
12 * This file contains the JPEG system-independent memory management
13 * routines. This code is usable across a wide variety of machines; most
14 * of the system dependencies have been isolated in a separate file.
15 * The major functions provided here are:
16 * * pool-based allocation and freeing of memory;
17 * * policy decisions about how to divide available memory among the
19 * * control logic for swapping virtual arrays between main memory and
21 * The separate system-dependent file provides the actual backing-storage
22 * access code, and it contains the policy decision about how much total
24 * This file is system-dependent in the sense that some of its functions
25 * are unnecessary in some systems. For example, if there is enough virtual
26 * memory so that backing storage will never be used, much of the virtual
27 * array control logic could be removed. (Of course, if you have that much
28 * memory then you shouldn't care about a little bit of unused code...)
31 #define JPEG_INTERNALS
32 #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
35 #include "jmemsys.h" /* import the system-dependent declarations */
38 #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
39 extern char * getenv
JPP((const char * name
));
45 * Some important notes:
46 * The allocation routines provided here must never return NULL.
47 * They should exit to error_exit if unsuccessful.
49 * It's not a good idea to try to merge the sarray, barray and darray
50 * routines, even though they are textually almost the same, because
51 * samples are usually stored as bytes while coefficients and differenced
52 * are shorts or ints. Thus, in machines where byte pointers have a
53 * different representation from word pointers, the resulting machine
54 * code could not be the same.
59 * Many machines require storage alignment: longs must start on 4-byte
60 * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
61 * always returns pointers that are multiples of the worst-case alignment
62 * requirement, and we had better do so too.
63 * There isn't any really portable way to determine the worst-case alignment
64 * requirement. This module assumes that the alignment requirement is
65 * multiples of sizeof(ALIGN_TYPE).
66 * By default, we define ALIGN_TYPE as double. This is necessary on some
67 * workstations (where doubles really do need 8-byte alignment) and will work
68 * fine on nearly everything. If your machine has lesser alignment needs,
69 * you can save a few bytes by making ALIGN_TYPE smaller.
70 * The only place I know of where this will NOT work is certain Macintosh
71 * 680x0 compilers that define double as a 10-byte IEEE extended float.
72 * Doing 10-byte alignment is counterproductive because longwords won't be
73 * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
77 #ifndef ALIGN_TYPE /* so can override from jconfig.h */
78 #define ALIGN_TYPE double
83 * We allocate objects from "pools", where each pool is gotten with a single
84 * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
85 * overhead within a pool, except for alignment padding. Each pool has a
86 * header with a link to the next pool of the same class.
87 * Small and large pool headers are identical except that the latter's
88 * link pointer must be FAR on 80x86 machines.
89 * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
90 * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
91 * of the alignment requirement of ALIGN_TYPE.
94 typedef union small_pool_struct
* small_pool_ptr
;
96 typedef union small_pool_struct
{
98 small_pool_ptr next
; /* next in list of pools */
99 size_t bytes_used
; /* how many bytes already used within pool */
100 size_t bytes_left
; /* bytes still available in this pool */
102 ALIGN_TYPE dummy
; /* included in union to ensure alignment */
105 typedef union large_pool_struct FAR
* large_pool_ptr
;
107 typedef union large_pool_struct
{
109 large_pool_ptr next
; /* next in list of pools */
110 size_t bytes_used
; /* how many bytes already used within pool */
111 size_t bytes_left
; /* bytes still available in this pool */
113 ALIGN_TYPE dummy
; /* included in union to ensure alignment */
118 * Here is the full definition of a memory manager object.
122 struct jpeg_memory_mgr pub
; /* public fields */
124 /* Each pool identifier (lifetime class) names a linked list of pools. */
125 small_pool_ptr small_list
[JPOOL_NUMPOOLS
];
126 large_pool_ptr large_list
[JPOOL_NUMPOOLS
];
128 /* Since we only have one lifetime class of virtual arrays, only one
129 * linked list is necessary (for each datatype). Note that the virtual
130 * array control blocks being linked together are actually stored somewhere
131 * in the small-pool list.
133 jvirt_sarray_ptr virt_sarray_list
;
134 jvirt_barray_ptr virt_barray_list
;
136 /* This counts total space obtained from jpeg_get_small/large */
137 long total_space_allocated
;
139 /* alloc_sarray and alloc_barray set this value for use by virtual
142 JDIMENSION last_rowsperchunk
; /* from most recent alloc_sarray/barray */
145 typedef my_memory_mgr
* my_mem_ptr
;
149 * The control blocks for virtual arrays.
150 * Note that these blocks are allocated in the "small" pool area.
151 * System-dependent info for the associated backing store (if any) is hidden
152 * inside the backing_store_info struct.
155 struct jvirt_sarray_control
{
156 JSAMPARRAY mem_buffer
; /* => the in-memory buffer */
157 JDIMENSION rows_in_array
; /* total virtual array height */
158 JDIMENSION samplesperrow
; /* width of array (and of memory buffer) */
159 JDIMENSION maxaccess
; /* max rows accessed by access_virt_sarray */
160 JDIMENSION rows_in_mem
; /* height of memory buffer */
161 JDIMENSION rowsperchunk
; /* allocation chunk size in mem_buffer */
162 JDIMENSION cur_start_row
; /* first logical row # in the buffer */
163 JDIMENSION first_undef_row
; /* row # of first uninitialized row */
164 boolean pre_zero
; /* pre-zero mode requested? */
165 boolean dirty
; /* do current buffer contents need written? */
166 boolean b_s_open
; /* is backing-store data valid? */
167 jvirt_sarray_ptr next
; /* link to next virtual sarray control block */
168 backing_store_info b_s_info
; /* System-dependent control info */
171 struct jvirt_barray_control
{
172 JBLOCKARRAY mem_buffer
; /* => the in-memory buffer */
173 JDIMENSION rows_in_array
; /* total virtual array height */
174 JDIMENSION blocksperrow
; /* width of array (and of memory buffer) */
175 JDIMENSION maxaccess
; /* max rows accessed by access_virt_barray */
176 JDIMENSION rows_in_mem
; /* height of memory buffer */
177 JDIMENSION rowsperchunk
; /* allocation chunk size in mem_buffer */
178 JDIMENSION cur_start_row
; /* first logical row # in the buffer */
179 JDIMENSION first_undef_row
; /* row # of first uninitialized row */
180 boolean pre_zero
; /* pre-zero mode requested? */
181 boolean dirty
; /* do current buffer contents need written? */
182 boolean b_s_open
; /* is backing-store data valid? */
183 jvirt_barray_ptr next
; /* link to next virtual barray control block */
184 backing_store_info b_s_info
; /* System-dependent control info */
188 #ifdef MEM_STATS /* optional extra stuff for statistics */
191 print_mem_stats (j_common_ptr cinfo
, int pool_id
)
193 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
194 small_pool_ptr shdr_ptr
;
195 large_pool_ptr lhdr_ptr
;
197 /* Since this is only a debugging stub, we can cheat a little by using
198 * fprintf directly rather than going through the trace message code.
199 * This is helpful because message parm array can't handle longs.
201 fprintf(stderr
, "Freeing pool %d, total space = %ld\n",
202 pool_id
, mem
->total_space_allocated
);
204 for (lhdr_ptr
= mem
->large_list
[pool_id
]; lhdr_ptr
!= NULL
;
205 lhdr_ptr
= lhdr_ptr
->hdr
.next
) {
206 fprintf(stderr
, " Large chunk used %ld\n",
207 (long) lhdr_ptr
->hdr
.bytes_used
);
210 for (shdr_ptr
= mem
->small_list
[pool_id
]; shdr_ptr
!= NULL
;
211 shdr_ptr
= shdr_ptr
->hdr
.next
) {
212 fprintf(stderr
, " Small chunk used %ld free %ld\n",
213 (long) shdr_ptr
->hdr
.bytes_used
,
214 (long) shdr_ptr
->hdr
.bytes_left
);
218 #endif /* MEM_STATS */
222 out_of_memory (j_common_ptr cinfo
, int which
)
223 /* Report an out-of-memory error and stop execution */
224 /* If we compiled MEM_STATS support, report alloc requests before dying */
227 cinfo
->err
->trace_level
= 2; /* force self_destruct to report stats */
229 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, which
);
234 * Allocation of "small" objects.
236 * For these, we use pooled storage. When a new pool must be created,
237 * we try to get enough space for the current request plus a "slop" factor,
238 * where the slop will be the amount of leftover space in the new pool.
239 * The speed vs. space tradeoff is largely determined by the slop values.
240 * A different slop value is provided for each pool class (lifetime),
241 * and we also distinguish the first pool of a class from later ones.
242 * NOTE: the values given work fairly well on both 16- and 32-bit-int
243 * machines, but may be too small if longs are 64 bits or more.
246 static const size_t first_pool_slop
[JPOOL_NUMPOOLS
] =
248 1600, /* first PERMANENT pool */
249 16000 /* first IMAGE pool */
252 static const size_t extra_pool_slop
[JPOOL_NUMPOOLS
] =
254 0, /* additional PERMANENT pools */
255 5000 /* additional IMAGE pools */
258 #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
262 alloc_small (j_common_ptr cinfo
, int pool_id
, size_t sizeofobject
)
263 /* Allocate a "small" object */
265 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
266 small_pool_ptr hdr_ptr
, prev_hdr_ptr
;
268 size_t odd_bytes
, min_request
, slop
;
270 /* Check for unsatisfiable request (do now to ensure no overflow below) */
271 if (sizeofobject
> (size_t) (MAX_ALLOC_CHUNK
-SIZEOF(small_pool_hdr
)))
272 out_of_memory(cinfo
, 1); /* request exceeds malloc's ability */
274 /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
275 odd_bytes
= sizeofobject
% SIZEOF(ALIGN_TYPE
);
277 sizeofobject
+= SIZEOF(ALIGN_TYPE
) - odd_bytes
;
279 /* See if space is available in any existing pool */
280 if (pool_id
< 0 || pool_id
>= JPOOL_NUMPOOLS
)
281 ERREXIT1(cinfo
, JERR_BAD_POOL_ID
, pool_id
); /* safety check */
283 hdr_ptr
= mem
->small_list
[pool_id
];
284 while (hdr_ptr
!= NULL
) {
285 if (hdr_ptr
->hdr
.bytes_left
>= sizeofobject
)
286 break; /* found pool with enough space */
287 prev_hdr_ptr
= hdr_ptr
;
288 hdr_ptr
= hdr_ptr
->hdr
.next
;
291 /* Time to make a new pool? */
292 if (hdr_ptr
== NULL
) {
293 /* min_request is what we need now, slop is what will be leftover */
294 min_request
= sizeofobject
+ SIZEOF(small_pool_hdr
);
295 if (prev_hdr_ptr
== NULL
) /* first pool in class? */
296 slop
= first_pool_slop
[pool_id
];
298 slop
= extra_pool_slop
[pool_id
];
299 /* Don't ask for more than MAX_ALLOC_CHUNK */
300 if (slop
> (size_t) (MAX_ALLOC_CHUNK
-min_request
))
301 slop
= (size_t) (MAX_ALLOC_CHUNK
-min_request
);
302 /* Try to get space, if fail reduce slop and try again */
304 hdr_ptr
= (small_pool_ptr
) jpeg_get_small(cinfo
, min_request
+ slop
);
308 if (slop
< MIN_SLOP
) /* give up when it gets real small */
309 out_of_memory(cinfo
, 2); /* jpeg_get_small failed */
311 mem
->total_space_allocated
+= min_request
+ slop
;
312 /* Success, initialize the new pool header and add to end of list */
313 hdr_ptr
->hdr
.next
= NULL
;
314 hdr_ptr
->hdr
.bytes_used
= 0;
315 hdr_ptr
->hdr
.bytes_left
= sizeofobject
+ slop
;
316 if (prev_hdr_ptr
== NULL
) /* first pool in class? */
317 mem
->small_list
[pool_id
] = hdr_ptr
;
319 prev_hdr_ptr
->hdr
.next
= hdr_ptr
;
322 /* OK, allocate the object from the current pool */
323 data_ptr
= (char *) (hdr_ptr
+ 1); /* point to first data byte in pool */
324 data_ptr
+= hdr_ptr
->hdr
.bytes_used
; /* point to place for object */
325 hdr_ptr
->hdr
.bytes_used
+= sizeofobject
;
326 hdr_ptr
->hdr
.bytes_left
-= sizeofobject
;
328 return (void *) data_ptr
;
333 * Allocation of "large" objects.
335 * The external semantics of these are the same as "small" objects,
336 * except that FAR pointers are used on 80x86. However the pool
337 * management heuristics are quite different. We assume that each
338 * request is large enough that it may as well be passed directly to
339 * jpeg_get_large; the pool management just links everything together
340 * so that we can free it all on demand.
341 * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
342 * structures. The routines that create these structures (see below)
343 * deliberately bunch rows together to ensure a large request size.
346 METHODDEF(void FAR
*)
347 alloc_large (j_common_ptr cinfo
, int pool_id
, size_t sizeofobject
)
348 /* Allocate a "large" object */
350 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
351 large_pool_ptr hdr_ptr
;
354 /* Check for unsatisfiable request (do now to ensure no overflow below) */
355 if (sizeofobject
> (size_t) (MAX_ALLOC_CHUNK
-SIZEOF(large_pool_hdr
)))
356 out_of_memory(cinfo
, 3); /* request exceeds malloc's ability */
358 /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
359 odd_bytes
= sizeofobject
% SIZEOF(ALIGN_TYPE
);
361 sizeofobject
+= SIZEOF(ALIGN_TYPE
) - odd_bytes
;
363 /* Always make a new pool */
364 if (pool_id
< 0 || pool_id
>= JPOOL_NUMPOOLS
)
365 ERREXIT1(cinfo
, JERR_BAD_POOL_ID
, pool_id
); /* safety check */
367 hdr_ptr
= (large_pool_ptr
) jpeg_get_large(cinfo
, sizeofobject
+
368 SIZEOF(large_pool_hdr
));
370 out_of_memory(cinfo
, 4); /* jpeg_get_large failed */
371 mem
->total_space_allocated
+= sizeofobject
+ SIZEOF(large_pool_hdr
);
373 /* Success, initialize the new pool header and add to list */
374 hdr_ptr
->hdr
.next
= mem
->large_list
[pool_id
];
375 /* We maintain space counts in each pool header for statistical purposes,
376 * even though they are not needed for allocation.
378 hdr_ptr
->hdr
.bytes_used
= sizeofobject
;
379 hdr_ptr
->hdr
.bytes_left
= 0;
380 mem
->large_list
[pool_id
] = hdr_ptr
;
382 return (void FAR
*) (hdr_ptr
+ 1); /* point to first data byte in pool */
387 * Creation of 2-D sample arrays.
388 * The pointers are in near heap, the samples themselves in FAR heap.
390 * To minimize allocation overhead and to allow I/O of large contiguous
391 * blocks, we allocate the sample rows in groups of as many rows as possible
392 * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
393 * NB: the virtual array control routines, later in this file, know about
394 * this chunking of rows. The rowsperchunk value is left in the mem manager
395 * object so that it can be saved away if this sarray is the workspace for
399 METHODDEF(JSAMPARRAY
)
400 alloc_sarray (j_common_ptr cinfo
, int pool_id
,
401 JDIMENSION samplesperrow
, JDIMENSION numrows
)
402 /* Allocate a 2-D sample array */
404 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
407 JDIMENSION rowsperchunk
, currow
, i
;
410 /* Calculate max # of rows allowed in one allocation chunk */
411 ltemp
= (MAX_ALLOC_CHUNK
-SIZEOF(large_pool_hdr
)) /
412 ((long) samplesperrow
* SIZEOF(JSAMPLE
));
414 ERREXIT(cinfo
, JERR_WIDTH_OVERFLOW
);
415 if (ltemp
< (long) numrows
)
416 rowsperchunk
= (JDIMENSION
) ltemp
;
418 rowsperchunk
= numrows
;
419 mem
->last_rowsperchunk
= rowsperchunk
;
421 /* Get space for row pointers (small object) */
422 result
= (JSAMPARRAY
) alloc_small(cinfo
, pool_id
,
423 (size_t) (numrows
* SIZEOF(JSAMPROW
)));
425 /* Get the rows themselves (large objects) */
427 while (currow
< numrows
) {
428 rowsperchunk
= MIN(rowsperchunk
, numrows
- currow
);
429 workspace
= (JSAMPROW
) alloc_large(cinfo
, pool_id
,
430 (size_t) ((size_t) rowsperchunk
* (size_t) samplesperrow
432 for (i
= rowsperchunk
; i
> 0; i
--) {
433 result
[currow
++] = workspace
;
434 workspace
+= samplesperrow
;
443 * Creation of 2-D coefficient-block arrays.
444 * This is essentially the same as the code for sample arrays, above.
447 METHODDEF(JBLOCKARRAY
)
448 alloc_barray (j_common_ptr cinfo
, int pool_id
,
449 JDIMENSION blocksperrow
, JDIMENSION numrows
)
450 /* Allocate a 2-D coefficient-block array */
452 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
455 JDIMENSION rowsperchunk
, currow
, i
;
458 /* Calculate max # of rows allowed in one allocation chunk */
459 ltemp
= (MAX_ALLOC_CHUNK
-SIZEOF(large_pool_hdr
)) /
460 ((long) blocksperrow
* SIZEOF(JBLOCK
));
462 ERREXIT(cinfo
, JERR_WIDTH_OVERFLOW
);
463 if (ltemp
< (long) numrows
)
464 rowsperchunk
= (JDIMENSION
) ltemp
;
466 rowsperchunk
= numrows
;
467 mem
->last_rowsperchunk
= rowsperchunk
;
469 /* Get space for row pointers (small object) */
470 result
= (JBLOCKARRAY
) alloc_small(cinfo
, pool_id
,
471 (size_t) (numrows
* SIZEOF(JBLOCKROW
)));
473 /* Get the rows themselves (large objects) */
475 while (currow
< numrows
) {
476 rowsperchunk
= MIN(rowsperchunk
, numrows
- currow
);
477 workspace
= (JBLOCKROW
) alloc_large(cinfo
, pool_id
,
478 (size_t) ((size_t) rowsperchunk
* (size_t) blocksperrow
480 for (i
= rowsperchunk
; i
> 0; i
--) {
481 result
[currow
++] = workspace
;
482 workspace
+= blocksperrow
;
493 * Creation of 2-D difference arrays.
494 * This is essentially the same as the code for sample arrays, above.
497 METHODDEF(JDIFFARRAY
)
498 alloc_darray (j_common_ptr cinfo
, int pool_id
,
499 JDIMENSION diffsperrow
, JDIMENSION numrows
)
500 /* Allocate a 2-D difference array */
502 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
505 JDIMENSION rowsperchunk
, currow
, i
;
508 /* Calculate max # of rows allowed in one allocation chunk */
509 ltemp
= (MAX_ALLOC_CHUNK
-SIZEOF(large_pool_hdr
)) /
510 ((long) diffsperrow
* SIZEOF(JDIFF
));
512 ERREXIT(cinfo
, JERR_WIDTH_OVERFLOW
);
513 if (ltemp
< (long) numrows
)
514 rowsperchunk
= (JDIMENSION
) ltemp
;
516 rowsperchunk
= numrows
;
517 mem
->last_rowsperchunk
= rowsperchunk
;
519 /* Get space for row pointers (small object) */
520 result
= (JDIFFARRAY
) alloc_small(cinfo
, pool_id
,
521 (size_t) (numrows
* SIZEOF(JDIFFROW
)));
523 /* Get the rows themselves (large objects) */
525 while (currow
< numrows
) {
526 rowsperchunk
= MIN(rowsperchunk
, numrows
- currow
);
527 workspace
= (JDIFFROW
) alloc_large(cinfo
, pool_id
,
528 (size_t) ((size_t) rowsperchunk
* (size_t) diffsperrow
530 for (i
= rowsperchunk
; i
> 0; i
--) {
531 result
[currow
++] = workspace
;
532 workspace
+= diffsperrow
;
543 * About virtual array management:
545 * The above "normal" array routines are only used to allocate strip buffers
546 * (as wide as the image, but just a few rows high). Full-image-sized buffers
547 * are handled as "virtual" arrays. The array is still accessed a strip at a
548 * time, but the memory manager must save the whole array for repeated
549 * accesses. The intended implementation is that there is a strip buffer in
550 * memory (as high as is possible given the desired memory limit), plus a
551 * backing file that holds the rest of the array.
553 * The request_virt_array routines are told the total size of the image and
554 * the maximum number of rows that will be accessed at once. The in-memory
555 * buffer must be at least as large as the maxaccess value.
557 * The request routines create control blocks but not the in-memory buffers.
558 * That is postponed until realize_virt_arrays is called. At that time the
559 * total amount of space needed is known (approximately, anyway), so free
560 * memory can be divided up fairly.
562 * The access_virt_array routines are responsible for making a specific strip
563 * area accessible (after reading or writing the backing file, if necessary).
564 * Note that the access routines are told whether the caller intends to modify
565 * the accessed strip; during a read-only pass this saves having to rewrite
566 * data to disk. The access routines are also responsible for pre-zeroing
567 * any newly accessed rows, if pre-zeroing was requested.
569 * In current usage, the access requests are usually for nonoverlapping
570 * strips; that is, successive access start_row numbers differ by exactly
571 * num_rows = maxaccess. This means we can get good performance with simple
572 * buffer dump/reload logic, by making the in-memory buffer be a multiple
573 * of the access height; then there will never be accesses across bufferload
574 * boundaries. The code will still work with overlapping access requests,
575 * but it doesn't handle bufferload overlaps very efficiently.
579 METHODDEF(jvirt_sarray_ptr
)
580 request_virt_sarray (j_common_ptr cinfo
, int pool_id
, boolean pre_zero
,
581 JDIMENSION samplesperrow
, JDIMENSION numrows
,
582 JDIMENSION maxaccess
)
583 /* Request a virtual 2-D sample array */
585 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
586 jvirt_sarray_ptr result
;
588 /* Only IMAGE-lifetime virtual arrays are currently supported */
589 if (pool_id
!= JPOOL_IMAGE
)
590 ERREXIT1(cinfo
, JERR_BAD_POOL_ID
, pool_id
); /* safety check */
592 /* get control block */
593 result
= (jvirt_sarray_ptr
) alloc_small(cinfo
, pool_id
,
594 SIZEOF(struct jvirt_sarray_control
));
596 result
->mem_buffer
= NULL
; /* marks array not yet realized */
597 result
->rows_in_array
= numrows
;
598 result
->samplesperrow
= samplesperrow
;
599 result
->maxaccess
= maxaccess
;
600 result
->pre_zero
= pre_zero
;
601 result
->b_s_open
= FALSE
; /* no associated backing-store object */
602 result
->next
= mem
->virt_sarray_list
; /* add to list of virtual arrays */
603 mem
->virt_sarray_list
= result
;
609 METHODDEF(jvirt_barray_ptr
)
610 request_virt_barray (j_common_ptr cinfo
, int pool_id
, boolean pre_zero
,
611 JDIMENSION blocksperrow
, JDIMENSION numrows
,
612 JDIMENSION maxaccess
)
613 /* Request a virtual 2-D coefficient-block array */
615 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
616 jvirt_barray_ptr result
;
618 /* Only IMAGE-lifetime virtual arrays are currently supported */
619 if (pool_id
!= JPOOL_IMAGE
)
620 ERREXIT1(cinfo
, JERR_BAD_POOL_ID
, pool_id
); /* safety check */
622 /* get control block */
623 result
= (jvirt_barray_ptr
) alloc_small(cinfo
, pool_id
,
624 SIZEOF(struct jvirt_barray_control
));
626 result
->mem_buffer
= NULL
; /* marks array not yet realized */
627 result
->rows_in_array
= numrows
;
628 result
->blocksperrow
= blocksperrow
;
629 result
->maxaccess
= maxaccess
;
630 result
->pre_zero
= pre_zero
;
631 result
->b_s_open
= FALSE
; /* no associated backing-store object */
632 result
->next
= mem
->virt_barray_list
; /* add to list of virtual arrays */
633 mem
->virt_barray_list
= result
;
640 realize_virt_arrays (j_common_ptr cinfo
)
641 /* Allocate the in-memory buffers for any unrealized virtual arrays */
643 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
644 long space_per_minheight
, maximum_space
, avail_mem
;
645 long minheights
, max_minheights
;
646 jvirt_sarray_ptr sptr
;
647 jvirt_barray_ptr bptr
;
649 /* Compute the minimum space needed (maxaccess rows in each buffer)
650 * and the maximum space needed (full image height in each buffer).
651 * These may be of use to the system-dependent jpeg_mem_available routine.
653 space_per_minheight
= 0;
655 for (sptr
= mem
->virt_sarray_list
; sptr
!= NULL
; sptr
= sptr
->next
) {
656 if (sptr
->mem_buffer
== NULL
) { /* if not realized yet */
657 space_per_minheight
+= (long) sptr
->maxaccess
*
658 (long) sptr
->samplesperrow
* SIZEOF(JSAMPLE
);
659 maximum_space
+= (long) sptr
->rows_in_array
*
660 (long) sptr
->samplesperrow
* SIZEOF(JSAMPLE
);
663 for (bptr
= mem
->virt_barray_list
; bptr
!= NULL
; bptr
= bptr
->next
) {
664 if (bptr
->mem_buffer
== NULL
) { /* if not realized yet */
665 space_per_minheight
+= (long) bptr
->maxaccess
*
666 (long) bptr
->blocksperrow
* SIZEOF(JBLOCK
);
667 maximum_space
+= (long) bptr
->rows_in_array
*
668 (long) bptr
->blocksperrow
* SIZEOF(JBLOCK
);
672 if (space_per_minheight
<= 0)
673 return; /* no unrealized arrays, no work */
675 /* Determine amount of memory to actually use; this is system-dependent. */
676 avail_mem
= jpeg_mem_available(cinfo
, space_per_minheight
, maximum_space
,
677 mem
->total_space_allocated
);
679 /* If the maximum space needed is available, make all the buffers full
680 * height; otherwise parcel it out with the same number of minheights
683 if (avail_mem
>= maximum_space
)
684 max_minheights
= 1000000000L;
686 max_minheights
= avail_mem
/ space_per_minheight
;
687 /* If there doesn't seem to be enough space, try to get the minimum
688 * anyway. This allows a "stub" implementation of jpeg_mem_available().
690 if (max_minheights
<= 0)
694 /* Allocate the in-memory buffers and initialize backing store as needed. */
696 for (sptr
= mem
->virt_sarray_list
; sptr
!= NULL
; sptr
= sptr
->next
) {
697 if (sptr
->mem_buffer
== NULL
) { /* if not realized yet */
698 minheights
= ((long) sptr
->rows_in_array
- 1L) / sptr
->maxaccess
+ 1L;
699 if (minheights
<= max_minheights
) {
700 /* This buffer fits in memory */
701 sptr
->rows_in_mem
= sptr
->rows_in_array
;
703 /* It doesn't fit in memory, create backing store. */
704 sptr
->rows_in_mem
= (JDIMENSION
) (max_minheights
* sptr
->maxaccess
);
705 jpeg_open_backing_store(cinfo
, & sptr
->b_s_info
,
706 (long) sptr
->rows_in_array
*
707 (long) sptr
->samplesperrow
*
708 (long) SIZEOF(JSAMPLE
));
709 sptr
->b_s_open
= TRUE
;
711 sptr
->mem_buffer
= alloc_sarray(cinfo
, JPOOL_IMAGE
,
712 sptr
->samplesperrow
, sptr
->rows_in_mem
);
713 sptr
->rowsperchunk
= mem
->last_rowsperchunk
;
714 sptr
->cur_start_row
= 0;
715 sptr
->first_undef_row
= 0;
720 for (bptr
= mem
->virt_barray_list
; bptr
!= NULL
; bptr
= bptr
->next
) {
721 if (bptr
->mem_buffer
== NULL
) { /* if not realized yet */
722 minheights
= ((long) bptr
->rows_in_array
- 1L) / bptr
->maxaccess
+ 1L;
723 if (minheights
<= max_minheights
) {
724 /* This buffer fits in memory */
725 bptr
->rows_in_mem
= bptr
->rows_in_array
;
727 /* It doesn't fit in memory, create backing store. */
728 bptr
->rows_in_mem
= (JDIMENSION
) (max_minheights
* bptr
->maxaccess
);
729 jpeg_open_backing_store(cinfo
, & bptr
->b_s_info
,
730 (long) bptr
->rows_in_array
*
731 (long) bptr
->blocksperrow
*
732 (long) SIZEOF(JBLOCK
));
733 bptr
->b_s_open
= TRUE
;
735 bptr
->mem_buffer
= alloc_barray(cinfo
, JPOOL_IMAGE
,
736 bptr
->blocksperrow
, bptr
->rows_in_mem
);
737 bptr
->rowsperchunk
= mem
->last_rowsperchunk
;
738 bptr
->cur_start_row
= 0;
739 bptr
->first_undef_row
= 0;
747 do_sarray_io (j_common_ptr cinfo
, jvirt_sarray_ptr ptr
, boolean writing
)
748 /* Do backing store read or write of a virtual sample array */
750 long bytesperrow
, file_offset
, byte_count
, rows
, thisrow
, i
;
752 bytesperrow
= (long) ptr
->samplesperrow
* SIZEOF(JSAMPLE
);
753 file_offset
= ptr
->cur_start_row
* bytesperrow
;
754 /* Loop to read or write each allocation chunk in mem_buffer */
755 for (i
= 0; i
< (long) ptr
->rows_in_mem
; i
+= ptr
->rowsperchunk
) {
756 /* One chunk, but check for short chunk at end of buffer */
757 rows
= MIN((long) ptr
->rowsperchunk
, (long) ptr
->rows_in_mem
- i
);
758 /* Transfer no more than is currently defined */
759 thisrow
= (long) ptr
->cur_start_row
+ i
;
760 rows
= MIN(rows
, (long) ptr
->first_undef_row
- thisrow
);
761 /* Transfer no more than fits in file */
762 rows
= MIN(rows
, (long) ptr
->rows_in_array
- thisrow
);
763 if (rows
<= 0) /* this chunk might be past end of file! */
765 byte_count
= rows
* bytesperrow
;
767 (*ptr
->b_s_info
.write_backing_store
) (cinfo
, & ptr
->b_s_info
,
768 (void FAR
*) ptr
->mem_buffer
[i
],
769 file_offset
, byte_count
);
771 (*ptr
->b_s_info
.read_backing_store
) (cinfo
, & ptr
->b_s_info
,
772 (void FAR
*) ptr
->mem_buffer
[i
],
773 file_offset
, byte_count
);
774 file_offset
+= byte_count
;
780 do_barray_io (j_common_ptr cinfo
, jvirt_barray_ptr ptr
, boolean writing
)
781 /* Do backing store read or write of a virtual coefficient-block array */
783 long bytesperrow
, file_offset
, byte_count
, rows
, thisrow
, i
;
785 bytesperrow
= (long) ptr
->blocksperrow
* SIZEOF(JBLOCK
);
786 file_offset
= ptr
->cur_start_row
* bytesperrow
;
787 /* Loop to read or write each allocation chunk in mem_buffer */
788 for (i
= 0; i
< (long) ptr
->rows_in_mem
; i
+= ptr
->rowsperchunk
) {
789 /* One chunk, but check for short chunk at end of buffer */
790 rows
= MIN((long) ptr
->rowsperchunk
, (long) ptr
->rows_in_mem
- i
);
791 /* Transfer no more than is currently defined */
792 thisrow
= (long) ptr
->cur_start_row
+ i
;
793 rows
= MIN(rows
, (long) ptr
->first_undef_row
- thisrow
);
794 /* Transfer no more than fits in file */
795 rows
= MIN(rows
, (long) ptr
->rows_in_array
- thisrow
);
796 if (rows
<= 0) /* this chunk might be past end of file! */
798 byte_count
= rows
* bytesperrow
;
800 (*ptr
->b_s_info
.write_backing_store
) (cinfo
, & ptr
->b_s_info
,
801 (void FAR
*) ptr
->mem_buffer
[i
],
802 file_offset
, byte_count
);
804 (*ptr
->b_s_info
.read_backing_store
) (cinfo
, & ptr
->b_s_info
,
805 (void FAR
*) ptr
->mem_buffer
[i
],
806 file_offset
, byte_count
);
807 file_offset
+= byte_count
;
812 METHODDEF(JSAMPARRAY
)
813 access_virt_sarray (j_common_ptr cinfo
, jvirt_sarray_ptr ptr
,
814 JDIMENSION start_row
, JDIMENSION num_rows
,
816 /* Access the part of a virtual sample array starting at start_row */
817 /* and extending for num_rows rows. writable is true if */
818 /* caller intends to modify the accessed area. */
820 JDIMENSION end_row
= start_row
+ num_rows
;
821 JDIMENSION undef_row
;
823 /* debugging check */
824 if (end_row
> ptr
->rows_in_array
|| num_rows
> ptr
->maxaccess
||
825 ptr
->mem_buffer
== NULL
)
826 ERREXIT(cinfo
, JERR_BAD_VIRTUAL_ACCESS
);
828 /* Make the desired part of the virtual array accessible */
829 if (start_row
< ptr
->cur_start_row
||
830 end_row
> ptr
->cur_start_row
+ptr
->rows_in_mem
) {
832 ERREXIT(cinfo
, JERR_VIRTUAL_BUG
);
833 /* Flush old buffer contents if necessary */
835 do_sarray_io(cinfo
, ptr
, TRUE
);
838 /* Decide what part of virtual array to access.
839 * Algorithm: if target address > current window, assume forward scan,
840 * load starting at target address. If target address < current window,
841 * assume backward scan, load so that target area is top of window.
842 * Note that when switching from forward write to forward read, will have
843 * start_row = 0, so the limiting case applies and we load from 0 anyway.
845 if (start_row
> ptr
->cur_start_row
) {
846 ptr
->cur_start_row
= start_row
;
848 /* use long arithmetic here to avoid overflow & unsigned problems */
851 ltemp
= (long) end_row
- (long) ptr
->rows_in_mem
;
853 ltemp
= 0; /* don't fall off front end of file */
854 ptr
->cur_start_row
= (JDIMENSION
) ltemp
;
856 /* Read in the selected part of the array.
857 * During the initial write pass, we will do no actual read
858 * because the selected part is all undefined.
860 do_sarray_io(cinfo
, ptr
, FALSE
);
862 /* Ensure the accessed part of the array is defined; prezero if needed.
863 * To improve locality of access, we only prezero the part of the array
864 * that the caller is about to access, not the entire in-memory array.
866 if (ptr
->first_undef_row
< end_row
) {
867 if (ptr
->first_undef_row
< start_row
) {
868 if (writable
) /* writer skipped over a section of array */
869 ERREXIT(cinfo
, JERR_BAD_VIRTUAL_ACCESS
);
870 undef_row
= start_row
; /* but reader is allowed to read ahead */
872 undef_row
= ptr
->first_undef_row
;
875 ptr
->first_undef_row
= end_row
;
877 size_t bytesperrow
= (size_t) ptr
->samplesperrow
* SIZEOF(JSAMPLE
);
878 undef_row
-= ptr
->cur_start_row
; /* make indexes relative to buffer */
879 end_row
-= ptr
->cur_start_row
;
880 while (undef_row
< end_row
) {
881 jzero_far((void FAR
*) ptr
->mem_buffer
[undef_row
], bytesperrow
);
885 if (! writable
) /* reader looking at undefined data */
886 ERREXIT(cinfo
, JERR_BAD_VIRTUAL_ACCESS
);
889 /* Flag the buffer dirty if caller will write in it */
892 /* Return address of proper part of the buffer */
893 return ptr
->mem_buffer
+ (start_row
- ptr
->cur_start_row
);
897 METHODDEF(JBLOCKARRAY
)
898 access_virt_barray (j_common_ptr cinfo
, jvirt_barray_ptr ptr
,
899 JDIMENSION start_row
, JDIMENSION num_rows
,
901 /* Access the part of a virtual block array starting at start_row */
902 /* and extending for num_rows rows. writable is true if */
903 /* caller intends to modify the accessed area. */
905 JDIMENSION end_row
= start_row
+ num_rows
;
906 JDIMENSION undef_row
;
908 /* debugging check */
909 if (end_row
> ptr
->rows_in_array
|| num_rows
> ptr
->maxaccess
||
910 ptr
->mem_buffer
== NULL
)
911 ERREXIT(cinfo
, JERR_BAD_VIRTUAL_ACCESS
);
913 /* Make the desired part of the virtual array accessible */
914 if (start_row
< ptr
->cur_start_row
||
915 end_row
> ptr
->cur_start_row
+ptr
->rows_in_mem
) {
917 ERREXIT(cinfo
, JERR_VIRTUAL_BUG
);
918 /* Flush old buffer contents if necessary */
920 do_barray_io(cinfo
, ptr
, TRUE
);
923 /* Decide what part of virtual array to access.
924 * Algorithm: if target address > current window, assume forward scan,
925 * load starting at target address. If target address < current window,
926 * assume backward scan, load so that target area is top of window.
927 * Note that when switching from forward write to forward read, will have
928 * start_row = 0, so the limiting case applies and we load from 0 anyway.
930 if (start_row
> ptr
->cur_start_row
) {
931 ptr
->cur_start_row
= start_row
;
933 /* use long arithmetic here to avoid overflow & unsigned problems */
936 ltemp
= (long) end_row
- (long) ptr
->rows_in_mem
;
938 ltemp
= 0; /* don't fall off front end of file */
939 ptr
->cur_start_row
= (JDIMENSION
) ltemp
;
941 /* Read in the selected part of the array.
942 * During the initial write pass, we will do no actual read
943 * because the selected part is all undefined.
945 do_barray_io(cinfo
, ptr
, FALSE
);
947 /* Ensure the accessed part of the array is defined; prezero if needed.
948 * To improve locality of access, we only prezero the part of the array
949 * that the caller is about to access, not the entire in-memory array.
951 if (ptr
->first_undef_row
< end_row
) {
952 if (ptr
->first_undef_row
< start_row
) {
953 if (writable
) /* writer skipped over a section of array */
954 ERREXIT(cinfo
, JERR_BAD_VIRTUAL_ACCESS
);
955 undef_row
= start_row
; /* but reader is allowed to read ahead */
957 undef_row
= ptr
->first_undef_row
;
960 ptr
->first_undef_row
= end_row
;
962 size_t bytesperrow
= (size_t) ptr
->blocksperrow
* SIZEOF(JBLOCK
);
963 undef_row
-= ptr
->cur_start_row
; /* make indexes relative to buffer */
964 end_row
-= ptr
->cur_start_row
;
965 while (undef_row
< end_row
) {
966 jzero_far((void FAR
*) ptr
->mem_buffer
[undef_row
], bytesperrow
);
970 if (! writable
) /* reader looking at undefined data */
971 ERREXIT(cinfo
, JERR_BAD_VIRTUAL_ACCESS
);
974 /* Flag the buffer dirty if caller will write in it */
977 /* Return address of proper part of the buffer */
978 return ptr
->mem_buffer
+ (start_row
- ptr
->cur_start_row
);
983 * Release all objects belonging to a specified pool.
987 free_pool (j_common_ptr cinfo
, int pool_id
)
989 my_mem_ptr mem
= (my_mem_ptr
) cinfo
->mem
;
990 small_pool_ptr shdr_ptr
;
991 large_pool_ptr lhdr_ptr
;
994 if (pool_id
< 0 || pool_id
>= JPOOL_NUMPOOLS
)
995 ERREXIT1(cinfo
, JERR_BAD_POOL_ID
, pool_id
); /* safety check */
998 if (cinfo
->err
->trace_level
> 1)
999 print_mem_stats(cinfo
, pool_id
); /* print pool's memory usage statistics */
1002 /* If freeing IMAGE pool, close any virtual arrays first */
1003 if (pool_id
== JPOOL_IMAGE
) {
1004 jvirt_sarray_ptr sptr
;
1005 jvirt_barray_ptr bptr
;
1007 for (sptr
= mem
->virt_sarray_list
; sptr
!= NULL
; sptr
= sptr
->next
) {
1008 if (sptr
->b_s_open
) { /* there may be no backing store */
1009 sptr
->b_s_open
= FALSE
; /* prevent recursive close if error */
1010 (*sptr
->b_s_info
.close_backing_store
) (cinfo
, & sptr
->b_s_info
);
1013 mem
->virt_sarray_list
= NULL
;
1014 for (bptr
= mem
->virt_barray_list
; bptr
!= NULL
; bptr
= bptr
->next
) {
1015 if (bptr
->b_s_open
) { /* there may be no backing store */
1016 bptr
->b_s_open
= FALSE
; /* prevent recursive close if error */
1017 (*bptr
->b_s_info
.close_backing_store
) (cinfo
, & bptr
->b_s_info
);
1020 mem
->virt_barray_list
= NULL
;
1023 /* Release large objects */
1024 lhdr_ptr
= mem
->large_list
[pool_id
];
1025 mem
->large_list
[pool_id
] = NULL
;
1027 while (lhdr_ptr
!= NULL
) {
1028 large_pool_ptr next_lhdr_ptr
= lhdr_ptr
->hdr
.next
;
1029 space_freed
= lhdr_ptr
->hdr
.bytes_used
+
1030 lhdr_ptr
->hdr
.bytes_left
+
1031 SIZEOF(large_pool_hdr
);
1032 jpeg_free_large(cinfo
, (void FAR
*) lhdr_ptr
, space_freed
);
1033 mem
->total_space_allocated
-= space_freed
;
1034 lhdr_ptr
= next_lhdr_ptr
;
1037 /* Release small objects */
1038 shdr_ptr
= mem
->small_list
[pool_id
];
1039 mem
->small_list
[pool_id
] = NULL
;
1041 while (shdr_ptr
!= NULL
) {
1042 small_pool_ptr next_shdr_ptr
= shdr_ptr
->hdr
.next
;
1043 space_freed
= shdr_ptr
->hdr
.bytes_used
+
1044 shdr_ptr
->hdr
.bytes_left
+
1045 SIZEOF(small_pool_hdr
);
1046 jpeg_free_small(cinfo
, (void *) shdr_ptr
, space_freed
);
1047 mem
->total_space_allocated
-= space_freed
;
1048 shdr_ptr
= next_shdr_ptr
;
1054 * Close up shop entirely.
1055 * Note that this cannot be called unless cinfo->mem is non-NULL.
1059 self_destruct (j_common_ptr cinfo
)
1063 /* Close all backing store, release all memory.
1064 * Releasing pools in reverse order might help avoid fragmentation
1065 * with some (brain-damaged) malloc libraries.
1067 for (pool
= JPOOL_NUMPOOLS
-1; pool
>= JPOOL_PERMANENT
; pool
--) {
1068 free_pool(cinfo
, pool
);
1071 /* Release the memory manager control block too. */
1072 jpeg_free_small(cinfo
, (void *) cinfo
->mem
, SIZEOF(my_memory_mgr
));
1073 cinfo
->mem
= NULL
; /* ensures I will be called only once */
1075 jpeg_mem_term(cinfo
); /* system-dependent cleanup */
1080 * Memory manager initialization.
1081 * When this is called, only the error manager pointer is valid in cinfo!
1085 jinit_memory_mgr (j_common_ptr cinfo
)
1092 cinfo
->mem
= NULL
; /* for safety if init fails */
1094 /* Check for configuration errors.
1095 * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
1096 * doesn't reflect any real hardware alignment requirement.
1097 * The test is a little tricky: for X>0, X and X-1 have no one-bits
1098 * in common if and only if X is a power of 2, ie has only one one-bit.
1099 * Some compilers may give an "unreachable code" warning here; ignore it.
1101 if ((SIZEOF(ALIGN_TYPE
) & (SIZEOF(ALIGN_TYPE
)-1)) != 0)
1102 ERREXIT(cinfo
, JERR_BAD_ALIGN_TYPE
);
1103 /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
1104 * a multiple of SIZEOF(ALIGN_TYPE).
1105 * Again, an "unreachable code" warning may be ignored here.
1106 * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
1108 test_mac
= (size_t) MAX_ALLOC_CHUNK
;
1109 if ((long) test_mac
!= MAX_ALLOC_CHUNK
||
1110 (MAX_ALLOC_CHUNK
% SIZEOF(ALIGN_TYPE
)) != 0)
1111 ERREXIT(cinfo
, JERR_BAD_ALLOC_CHUNK
);
1113 max_to_use
= jpeg_mem_init(cinfo
); /* system-dependent initialization */
1115 /* Attempt to allocate memory manager's control block */
1116 mem
= (my_mem_ptr
) jpeg_get_small(cinfo
, SIZEOF(my_memory_mgr
));
1119 jpeg_mem_term(cinfo
); /* system-dependent cleanup */
1120 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 0);
1123 /* OK, fill in the method pointers */
1124 mem
->pub
.alloc_small
= alloc_small
;
1125 mem
->pub
.alloc_large
= alloc_large
;
1126 mem
->pub
.alloc_sarray
= alloc_sarray
;
1127 mem
->pub
.alloc_barray
= alloc_barray
;
1129 mem
->pub
.alloc_darray
= alloc_darray
;
1131 mem
->pub
.request_virt_sarray
= request_virt_sarray
;
1132 mem
->pub
.request_virt_barray
= request_virt_barray
;
1133 mem
->pub
.realize_virt_arrays
= realize_virt_arrays
;
1134 mem
->pub
.access_virt_sarray
= access_virt_sarray
;
1135 mem
->pub
.access_virt_barray
= access_virt_barray
;
1136 mem
->pub
.free_pool
= free_pool
;
1137 mem
->pub
.self_destruct
= self_destruct
;
1139 /* Make MAX_ALLOC_CHUNK accessible to other modules */
1140 mem
->pub
.max_alloc_chunk
= MAX_ALLOC_CHUNK
;
1142 /* Initialize working state */
1143 mem
->pub
.max_memory_to_use
= max_to_use
;
1145 for (pool
= JPOOL_NUMPOOLS
-1; pool
>= JPOOL_PERMANENT
; pool
--) {
1146 mem
->small_list
[pool
] = NULL
;
1147 mem
->large_list
[pool
] = NULL
;
1149 mem
->virt_sarray_list
= NULL
;
1150 mem
->virt_barray_list
= NULL
;
1152 mem
->total_space_allocated
= SIZEOF(my_memory_mgr
);
1154 /* Declare ourselves open for business */
1155 cinfo
->mem
= & mem
->pub
;
1157 /* Check for an environment variable JPEGMEM; if found, override the
1158 * default max_memory setting from jpeg_mem_init. Note that the
1159 * surrounding application may again override this value.
1160 * If your system doesn't support getenv(), define NO_GETENV to disable
1166 if ((memenv
= getenv("JPEGMEM")) != NULL
) {
1169 if (sscanf(memenv
, "%ld%c", &max_to_use
, &ch
) > 0) {
1170 if (ch
== 'm' || ch
== 'M')
1171 max_to_use
*= 1000L;
1172 mem
->pub
.max_memory_to_use
= max_to_use
* 1000L;