home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume44 / jpeg / part01 next >
Encoding:
Internet Message Format  |  1994-09-26  |  62.9 KB

  1. From: jpeg-info@uunet.uu.net (Independent JPEG Group)
  2. Newsgroups: comp.sources.misc
  3. Subject: v44i098:  jpeg - JPEG image compression, Part01/27
  4. Date: 26 Sep 1994 16:13:31 -0500
  5. Organization: Independent JPEG Group
  6. Sender: kent@sparky.sterling.com
  7. Approved: kent@sparky.sterling.com
  8. Message-ID: <csm-v44i098=jpeg.161317@sparky.sterling.com>
  9. Keywords: JPEG, image compression
  10. X-Md4-Signature: c89975bb92623a934ecf73c78eb0bb50
  11.  
  12. Submitted-by: jpeg-info@uunet.uu.net (Independent JPEG Group)
  13. Posting-number: Volume 44, Issue 98
  14. Archive-name: jpeg/part01
  15. Environment: UNIX, VMS, MS-DOS, Mac, Amiga, Atari, Cray
  16. Supersedes: jpeg: Volume 34, Issue 55-72
  17.  
  18. This package contains C software to implement JPEG image compression and
  19. decompression.  JPEG is a standardized compression method for full-color
  20. and gray-scale images.  JPEG is intended for "real-world" scenes; cartoons
  21. and other non-realistic images are not its strong suit.  JPEG is lossy,
  22. meaning that the output image is not identical to the input image.
  23. The user can trade off output image quality against compressed file size by
  24. adjusting a compression parameter.
  25.  
  26. The IJG code includes a reusable JPEG compression/decompression library,
  27. plus sample applications "cjpeg" and "djpeg", which perform conversion
  28. between JPEG JFIF format and image files in PPM/PGM (PBMPLUS), GIF, BMP,
  29. Utah RLE, and Targa formats.  Two small applications "wrjpgcom" and
  30. "rdjpgcom" insert and extract textual comments in JFIF files.
  31. The package is highly portable; it has been used successfully on many
  32. machines ranging from Apple IIs to Crays.
  33.  
  34. This version 5 supersedes version 4, which was posted in comp.sources.misc
  35. volume 34.  Important user-level improvements over version 4 include:
  36.  
  37. * Automatic configuration simplifies installation for most Unix systems.
  38.  
  39. * A range of speed vs. image quality tradeoffs are supported.
  40.   This includes resizing of an image during decompression: scaling down
  41.   by a factor of 1/2, 1/4, or 1/8 is handled very efficiently.
  42.  
  43. * New programs rdjpgcom and wrjpgcom allow insertion and extraction
  44.   of text comments in a JPEG file.
  45.  
  46. * cjpeg/djpeg support BMP file format.
  47.  
  48. The application programmer's interface to the library has changed completely.
  49. Notable improvements for the programmer include:
  50.  
  51. * We have eliminated the use of callback routines for handling the
  52.   uncompressed image data.  The application now sees the library as a
  53.   set of routines that it calls to read or write image data on a
  54.   scanline-by-scanline basis.
  55.  
  56. * The application image data is represented in a conventional interleaved-
  57.   pixel format, rather than as a separate array for each color channel.
  58.   This can save a copying step in many programs.
  59.  
  60. * The handling of compressed data has been cleaned up: the application can
  61.   supply routines to source or sink the compressed data.
  62.  
  63. * All static state has been eliminated from the library, so that multiple
  64.   instances of compression or decompression can be active concurrently.
  65.  
  66. * JPEG abbreviated datastream formats are supported, ie, quantization and
  67.   Huffman tables can be stored separately from the image data.
  68.  
  69. * And not only that, but the documentation of the library has improved
  70.   considerably!
  71.  
  72. We are releasing this software for both noncommercial and commercial use.
  73. Companies are welcome to use it as the basis for JPEG-related products.
  74. We do not ask a royalty, although we do ask for an acknowledgement in
  75. product literature (see the README file in the distribution for details).
  76. We hope to make this software industrial-quality --- although, as with
  77. anything that's free, we offer no warranty and accept no liability.
  78.  
  79. Please direct any questions about this software to jpeg-info@uunet.uu.net.
  80.  
  81.             Dr. Thomas G. Lane
  82.             organizer, Independent JPEG Group
  83. -------
  84. #! /bin/sh
  85. # This is a shell archive.  Remove anything before this line, then feed it
  86. # into a shell via "sh file" or similar.  To overwrite existing files,
  87. # type "sh file -c".
  88. # Contents:  README jmemmgr.c jversion.h
  89. # Wrapped by kent@sparky on Mon Sep 26 15:00:25 1994
  90. PATH=/bin:/usr/bin:/usr/ucb:/usr/local/bin:/usr/lbin:$PATH ; export PATH
  91. echo If this archive is complete, you will see the following message:
  92. echo '          "shar: End of archive 1 (of 27)."'
  93. if test -f 'README' -a "${1}" != "-c" ; then 
  94.   echo shar: Will not clobber existing file \"'README'\"
  95. else
  96.   echo shar: Extracting \"'README'\" \(17896 characters\)
  97.   sed "s/^X//" >'README' <<'END_OF_FILE'
  98. XThe Independent JPEG Group's JPEG software
  99. X==========================================
  100. X
  101. XREADME for release 5 of 24-Sep-94
  102. X=================================
  103. X
  104. XThis distribution contains the fifth public release of the Independent JPEG
  105. XGroup's free JPEG software.  You are welcome to redistribute this software and
  106. Xto use it for any purpose, subject to the conditions under LEGAL ISSUES, below.
  107. X
  108. XSerious users of this software (particularly those incorporating it into
  109. Xlarger programs) should contact jpeg-info@uunet.uu.net to be added to our
  110. Xelectronic mailing list.  Mailing list members are notified of updates and
  111. Xhave a chance to participate in technical discussions, etc.
  112. X
  113. XThis software is the work of Tom Lane, Philip Gladstone, Luis Ortiz, Jim
  114. XBoucher, Lee Crocker, George Phillips, Davide Rossi, Ge' Weijers, and other
  115. Xmembers of the Independent JPEG Group.
  116. X
  117. XIJG is not associated with the official ISO JPEG standards committee.
  118. X
  119. X
  120. XDOCUMENTATION ROADMAP
  121. X=====================
  122. X
  123. XThis file contains the following sections:
  124. X
  125. XOVERVIEW            General description of JPEG and the IJG software.
  126. XLEGAL ISSUES        Copyright, lack of warranty, terms of distribution.
  127. XREFERENCES          Where to learn more about JPEG.
  128. XARCHIVE LOCATIONS   Where to find newer versions of this software.
  129. XRELATED SOFTWARE    Other stuff you should get.
  130. XFILE FORMAT WARS    Software *not* to get.
  131. XTO DO               Plans for future IJG releases.
  132. X
  133. XOther documentation files in the distribution are:
  134. X
  135. XUser documentation:
  136. X  install.doc       How to configure and install the IJG software.
  137. X  usage.doc         Usage instructions for cjpeg, djpeg, rdjpgcom, wrjpgcom.
  138. X  *.1               Unix-style man pages for programs (same info as usage.doc).
  139. X  change.log        Version-to-version change highlights.
  140. XProgrammer and internal documentation:
  141. X  libjpeg.doc       How to use the JPEG library in your own programs.
  142. X  example.c         Sample code for calling the JPEG library.
  143. X  structure.doc     Overview of the JPEG library's internal structure.
  144. X  filelist.doc      Road map of IJG files.
  145. X  coderules.doc     Coding style rules --- please read if you contribute code.
  146. X
  147. XPlease read at least the files install.doc and usage.doc.  Useful information
  148. Xcan also be found in the JPEG FAQ (Frequently Asked Questions) article.  See
  149. XARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
  150. X
  151. XIf you want to understand how the JPEG code works, we suggest reading one or
  152. Xmore of the REFERENCES, then looking at the documentation files (in roughly
  153. Xthe order listed) before diving into the code.
  154. X
  155. X
  156. XOVERVIEW
  157. X========
  158. X
  159. XThis package contains C software to implement JPEG image compression and
  160. Xdecompression.  JPEG (pronounced "jay-peg") is a standardized compression
  161. Xmethod for full-color and gray-scale images.  JPEG is intended for compressing
  162. X"real-world" scenes; cartoons and other non-realistic images are not its
  163. Xstrong suit.  JPEG is lossy, meaning that the output image is not necessarily
  164. Xidentical to the input image.  Hence you must not use JPEG if you have to have
  165. Xidentical output bits.  However, on typical images of real-world scenes, very
  166. Xgood compression levels can be obtained with no visible change, and amazingly
  167. Xhigh compression levels are possible if you can tolerate a low-quality image.
  168. XFor more details, see the references, or just experiment with various
  169. Xcompression settings.
  170. X
  171. XWe provide a set of library routines for reading and writing JPEG image files,
  172. Xplus two simple applications "cjpeg" and "djpeg", which use the library to
  173. Xperform conversion between JPEG and some other popular image file formats.
  174. XThe library is intended to be reused in other applications.
  175. X
  176. XThis software implements JPEG baseline and extended-sequential compression
  177. Xprocesses.  Provision is made for supporting all variants of these processes,
  178. Xalthough some uncommon parameter settings aren't implemented yet.  For legal
  179. Xreasons, we are not distributing code for the arithmetic-coding process; see
  180. XLEGAL ISSUES.  At present we have made no provision for supporting the
  181. Xprogressive, hierarchical, or lossless processes defined in the standard.
  182. X(Support for progressive mode may be offered in a future release.)
  183. X
  184. XIn order to support file conversion and viewing software, we have included
  185. Xconsiderable functionality beyond the bare JPEG coding/decoding capability;
  186. Xfor example, the color quantization modules are not strictly part of JPEG
  187. Xdecoding, but they are essential for output to colormapped file formats or
  188. Xcolormapped displays.  These extra functions can be compiled out of the
  189. Xlibrary if not required for a particular application.  We have also included
  190. Xtwo simple applications for inserting and extracting textual comments in
  191. XJFIF files.
  192. X
  193. XThe emphasis in designing this software has been on achieving portability and
  194. Xflexibility, while also making it fast enough to be useful.  In particular,
  195. Xthe software is not intended to be read as a tutorial on JPEG.  (See the
  196. XREFERENCES section for introductory material.)  While we hope that the entire
  197. Xpackage will someday be industrial-strength code, much remains to be done in
  198. Xperformance tuning and in improving the capabilities of individual modules.
  199. X
  200. XWe welcome the use of this software as a component of commercial products.
  201. XNo royalty is required, but we do ask for an acknowledgement in product
  202. Xdocumentation, as described under LEGAL ISSUES.
  203. X
  204. X
  205. XLEGAL ISSUES
  206. X============
  207. X
  208. XIn plain English:
  209. X
  210. X1. We don't promise that this software works.  (But if you find any bugs,
  211. X   please let us know!)
  212. X2. You can use this software for whatever you want.  You don't have to pay us.
  213. X3. You may not pretend that you wrote this software.  If you use it in a
  214. X   program, you must acknowledge somewhere in your documentation that
  215. X   you've used the IJG code.
  216. X
  217. XIn legalese:
  218. X
  219. XThe authors make NO WARRANTY or representation, either express or implied,
  220. Xwith respect to this software, its quality, accuracy, merchantability, or
  221. Xfitness for a particular purpose.  This software is provided "AS IS", and you,
  222. Xits user, assume the entire risk as to its quality and accuracy.
  223. X
  224. XThis software is copyright (C) 1991, 1992, 1993, 1994, Thomas G. Lane.
  225. XAll Rights Reserved except as specified below.
  226. X
  227. XPermission is hereby granted to use, copy, modify, and distribute this
  228. Xsoftware (or portions thereof) for any purpose, without fee, subject to these
  229. Xconditions:
  230. X(1) If any part of the source code for this software is distributed, then this
  231. XREADME file must be included, with this copyright and no-warranty notice
  232. Xunaltered; and any additions, deletions, or changes to the original files
  233. Xmust be clearly indicated in accompanying documentation.
  234. X(2) If only executable code is distributed, then the accompanying
  235. Xdocumentation must state that "this software is based in part on the work of
  236. Xthe Independent JPEG Group".
  237. X(3) Permission for use of this software is granted only if the user accepts
  238. Xfull responsibility for any undesirable consequences; the authors accept
  239. XNO LIABILITY for damages of any kind.
  240. X
  241. XThese conditions apply to any software derived from or based on the IJG code,
  242. Xnot just to the unmodified library.  If you use our work, you ought to
  243. Xacknowledge us.
  244. X
  245. XPermission is NOT granted for the use of any IJG author's name or company name
  246. Xin advertising or publicity relating to this software or products derived from
  247. Xit.  This software may be referred to only as "the Independent JPEG Group's
  248. Xsoftware".
  249. X
  250. XWe specifically permit and encourage the use of this software as the basis of
  251. Xcommercial products, provided that all warranty or liability claims are
  252. Xassumed by the product vendor.
  253. X
  254. X
  255. Xansi2knr.c is included in this distribution by permission of L. Peter Deutsch,
  256. Xsole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA.
  257. Xansi2knr.c is NOT covered by the above copyright and conditions, but instead
  258. Xby the usual distribution terms of the Free Software Foundation; principally,
  259. Xthat you must include source code if you redistribute it.  (See the file
  260. Xansi2knr.c for full details.)  However, since ansi2knr.c is not needed as part
  261. Xof any program generated from the IJG code, this does not limit you more than
  262. Xthe foregoing paragraphs do.
  263. X
  264. XThe configuration script "configure" was produced by GNU Autoconf.  Again,
  265. Xthe FSF copyright terms apply only to configure, not to the IJG code; and
  266. Xagain, that does not limit your use of the object code.
  267. X
  268. XIt appears that the arithmetic coding option of the JPEG spec is covered by
  269. Xpatents owned by IBM, AT&T, and Mitsubishi.  Hence arithmetic coding cannot
  270. Xlegally be used without obtaining one or more licenses.  For this reason,
  271. Xsupport for arithmetic coding has been removed from the free JPEG software.
  272. X(Since arithmetic coding provides only a marginal gain over the unpatented
  273. XHuffman mode, it is unlikely that very many implementations will support it.)
  274. XSo far as we are aware, there are no patent restrictions on the remaining
  275. Xcode.
  276. X
  277. XWe are required to state that
  278. X    "The Graphics Interchange Format(c) is the Copyright property of
  279. X    CompuServe Incorporated.  GIF(sm) is a Service Mark property of
  280. X    CompuServe Incorporated."
  281. X
  282. X
  283. XREFERENCES
  284. X==========
  285. X
  286. XWe highly recommend reading one or more of these references before trying to
  287. Xunderstand the innards of the JPEG software.
  288. X
  289. XThe best short technical introduction to the JPEG compression algorithm is
  290. X    Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
  291. X    Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
  292. X(Adjacent articles in that issue discuss MPEG motion picture compression,
  293. Xapplications of JPEG, and related topics.)  If you don't have the CACM issue
  294. Xhandy, a PostScript file containing a revised version of Wallace's article is
  295. Xavailable at ftp.uu.net, graphics/jpeg/wallace.ps.gz.  The file (actually a
  296. Xpreprint for an article to appear in IEEE Trans. Consumer Electronics) omits
  297. Xthe sample images that appeared in CACM, but it includes corrections and some
  298. Xadded material.  Note: the Wallace article is copyright ACM and IEEE, and it
  299. Xmay not be used for commercial purposes.
  300. X
  301. XA somewhat less technical, more leisurely introduction to JPEG can be found in
  302. X"The Data Compression Book" by Mark Nelson, published by M&T Books (Redwood
  303. XCity, CA), 1991, ISBN 1-55851-216-0.  This book provides good explanations and
  304. Xexample C code for a multitude of compression methods including JPEG.  It is
  305. Xan excellent source if you are comfortable reading C code but don't know much
  306. Xabout data compression in general.  The book's JPEG sample code is far from
  307. Xindustrial-strength, but when you are ready to look at a full implementation,
  308. Xyou've got one here...
  309. X
  310. XThe best full description of JPEG is the textbook "JPEG Still Image Data
  311. XCompression Standard" by William B. Pennebaker and Joan L. Mitchell, published
  312. Xby Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.  Price US$59.95, 638 pp.
  313. XThe book includes the complete text of the ISO JPEG standards (DIS 10918-1
  314. Xand draft DIS 10918-2).  This is by far the most complete exposition of JPEG
  315. Xin existence, and we highly recommend it.
  316. X
  317. XThe JPEG standard itself is not available electronically; you must order a
  318. Xpaper copy through ISO.  (Unless you feel a need to own a certified official
  319. Xcopy, we recommend buying the Pennebaker and Mitchell book instead; it's much
  320. Xcheaper and includes a great deal of useful explanatory material.)  In the US,
  321. Xcopies of the standard may be ordered from ANSI Sales at (212) 642-4900, or
  322. Xfrom Global Engineering Documents at (800) 854-7179.  (ANSI doesn't take
  323. Xcredit card orders, but Global does.)  It's not cheap: as of 1992, ANSI was
  324. Xcharging $95 for Part 1 and $47 for Part 2, plus 7% shipping/handling.  The
  325. Xstandard is divided into two parts, Part 1 being the actual specification,
  326. Xwhile Part 2 covers compliance testing methods.  Part 1 is titled "Digital
  327. XCompression and Coding of Continuous-tone Still Images, Part 1: Requirements
  328. Xand guidelines" and has document number ISO/IEC IS 10918-1.  As of mid-1994,
  329. XPart 2 is still at Draft International Standard status.  It is titled "Digital
  330. XCompression and Coding of Continuous-tone Still Images, Part 2: Compliance
  331. Xtesting" and has document number ISO/IEC DIS 10918-2.  (The document number
  332. Xwill change to IS 10918-2 when final approval is obtained.)  A Part 3,
  333. Xcovering extensions, is likely to appear in draft form in late 1994.
  334. X
  335. XThe JPEG standard does not specify all details of an interchangeable file
  336. Xformat.  For the omitted details we follow the "JFIF" conventions, revision
  337. X1.02.  A copy of the JFIF spec is available from:
  338. X    Literature Department
  339. X    C-Cube Microsystems, Inc.
  340. X    1778 McCarthy Blvd.
  341. X    Milpitas, CA 95035
  342. X    phone (408) 944-6300,  fax (408) 944-6314
  343. XA PostScript version of this document is available at ftp.uu.net, file
  344. Xgraphics/jpeg/jfif.ps.gz.  It can also be obtained by e-mail from the C-Cube
  345. Xmail server, netlib@c3.pla.ca.us.  Send the message "send jfif_ps from jpeg"
  346. Xto the server to obtain the JFIF document; send the message "help" if you have
  347. Xtrouble.
  348. X
  349. XThe TIFF 6.0 file format specification can be obtained by FTP from sgi.com
  350. X(192.48.153.1), file graphics/tiff/TIFF6.ps.Z; or you can order a printed copy
  351. Xfrom Aldus Corp. at (206) 628-6593.  It should be noted that the TIFF 6.0 spec
  352. Xof 3-June-92 has a number of serious problems in its JPEG features.  A
  353. Xredesign effort is currently underway to correct these problems; it is
  354. Xexpected to result in a new, incompatible, spec.  IJG intends to support the
  355. Xcorrected version of TIFF when the new spec is issued.
  356. X
  357. X
  358. XARCHIVE LOCATIONS
  359. X=================
  360. X
  361. XThe "official" archive site for this software is ftp.uu.net (Internet
  362. Xaddress 192.48.96.9).  The most recent released version can always be found
  363. Xthere in directory graphics/jpeg.  This particular version will be archived
  364. Xas graphics/jpeg/jpegsrc.v5.tar.gz.  If you are on the Internet, you
  365. Xcan retrieve files from ftp.uu.net by standard anonymous FTP.  If you don't
  366. Xhave FTP access, UUNET's archives are also available via UUCP; contact
  367. Xhelp@uunet.uu.net for information on retrieving files that way.
  368. X
  369. XNumerous Internet sites maintain copies of the UUNET files; in particular,
  370. Xyou can probably find a copy at any site that archives comp.sources.misc
  371. Xsubmissions.  However, only ftp.uu.net is guaranteed to have the latest
  372. Xofficial version.
  373. X
  374. XYou can also obtain this software from CompuServe, in the GRAPHSUPPORT forum
  375. X(GO GRAPHSUP); this version will be file jpsrc5.zip in library 15.  Again,
  376. XCompuServe is not guaranteed to have the very latest version.
  377. X
  378. XThe JPEG FAQ (Frequently Asked Questions) article is a useful source of
  379. Xgeneral information about JPEG.  It is updated constantly and therefore
  380. Xis not included in this distribution.  The FAQ is posted every two weeks
  381. Xto Usenet newsgroups comp.graphics, news.answers, and other groups.  You
  382. Xcan always obtain the latest version from the news.answers archive at
  383. Xrtfm.mit.edu (18.181.0.24).  By FTP, fetch /pub/usenet/news.answers/jpeg-faq.
  384. XIf you don't have FTP, send e-mail to mail-server@rtfm.mit.edu with body
  385. X"send usenet/news.answers/jpeg-faq".
  386. X
  387. X
  388. XRELATED SOFTWARE
  389. X================
  390. X
  391. XNumerous viewing and image manipulation programs now support JPEG.  (Quite a
  392. Xfew of them use this library to do so.)  The JPEG FAQ described above lists
  393. Xsome of the more popular free and shareware viewers, and tells where to
  394. Xobtain them on Internet.
  395. X
  396. XIf you are on a Unix machine, we highly recommend Jef Poskanzer's free
  397. XPBMPLUS image software, which provides many useful operations on PPM-format
  398. Ximage files.  In particular, it can convert PPM images to and from a wide
  399. Xrange of other formats.  You can obtain this package by FTP from ftp.x.org
  400. X(contrib/pbmplus*.tar.Z) or ftp.ee.lbl.gov (pbmplus*.tar.Z).  There is also
  401. Xa newer update of this package called NETPBM, available from
  402. Xwuarchive.wustl.edu under directory /graphics/graphics/packages/NetPBM/.
  403. XUnfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software
  404. Xis; you are likely to have difficulty making it work on any non-Unix machine.
  405. X
  406. XA different free JPEG implementation, written by the PVRG group at Stanford,
  407. Xis available from havefun.stanford.edu in directory pub/jpeg.  This program
  408. Xis designed for research and experimentation rather than production use;
  409. Xit is slower, harder to use, and less portable than the IJG code, but it
  410. Ximplements a larger subset of the JPEG standard.  In particular, it supports
  411. Xlossless JPEG.
  412. X
  413. X
  414. XFILE FORMAT WARS
  415. X================
  416. X
  417. XSome JPEG programs produce files that are not compatible with our library.
  418. XThe root of the problem is that the ISO JPEG committee failed to specify a
  419. Xconcrete file format.  Some vendors "filled in the blanks" on their own,
  420. Xcreating proprietary formats that no one else could read.  (For example, none
  421. Xof the early commercial JPEG implementations for the Macintosh were able to
  422. Xexchange compressed files.)
  423. X
  424. XThe file format we have adopted is called JFIF (see REFERENCES).  This format
  425. Xhas been agreed to by a number of major commercial JPEG vendors, and it has
  426. Xbecome the de facto standard.  JFIF is a minimal or "low end" representation.
  427. XWork is also going forward to incorporate JPEG compression into the TIFF
  428. Xstandard, for use in "high end" applications that need to record a lot of
  429. Xadditional data about an image.  We intend to support TIFF in the future.
  430. XWe hope that these two formats will be sufficient and that other,
  431. Xincompatible JPEG file formats will not proliferate.
  432. X
  433. XIndeed, part of the reason for developing and releasing this free software is
  434. Xto help force rapid convergence to de facto standards for JPEG file formats.
  435. XSUPPORT STANDARD, NON-PROPRIETARY FORMATS: demand JFIF or TIFF/JPEG!
  436. X
  437. X
  438. XTO DO
  439. X=====
  440. X
  441. XIn future versions, we are considering supporting progressive JPEG
  442. Xcompression, the upcoming JPEG Part 3 extensions, and other improvements.
  443. X
  444. XAs always, speeding things up is high on our priority list.
  445. X
  446. XPlease send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net.
  447. END_OF_FILE
  448.   if test 17896 -ne `wc -c <'README'`; then
  449.     echo shar: \"'README'\" unpacked with wrong size!
  450.   fi
  451.   # end of 'README'
  452. fi
  453. if test -f 'jmemmgr.c' -a "${1}" != "-c" ; then 
  454.   echo shar: Will not clobber existing file \"'jmemmgr.c'\"
  455. else
  456.   echo shar: Extracting \"'jmemmgr.c'\" \(38963 characters\)
  457.   sed "s/^X//" >'jmemmgr.c' <<'END_OF_FILE'
  458. X/*
  459. X * jmemmgr.c
  460. X *
  461. X * Copyright (C) 1991-1994, Thomas G. Lane.
  462. X * This file is part of the Independent JPEG Group's software.
  463. X * For conditions of distribution and use, see the accompanying README file.
  464. X *
  465. X * This file contains the JPEG system-independent memory management
  466. X * routines.  This code is usable across a wide variety of machines; most
  467. X * of the system dependencies have been isolated in a separate file.
  468. X * The major functions provided here are:
  469. X *   * pool-based allocation and freeing of memory;
  470. X *   * policy decisions about how to divide available memory among the
  471. X *     virtual arrays;
  472. X *   * control logic for swapping virtual arrays between main memory and
  473. X *     backing storage.
  474. X * The separate system-dependent file provides the actual backing-storage
  475. X * access code, and it contains the policy decision about how much total
  476. X * main memory to use.
  477. X * This file is system-dependent in the sense that some of its functions
  478. X * are unnecessary in some systems.  For example, if there is enough virtual
  479. X * memory so that backing storage will never be used, much of the virtual
  480. X * array control logic could be removed.  (Of course, if you have that much
  481. X * memory then you shouldn't care about a little bit of unused code...)
  482. X */
  483. X
  484. X#define JPEG_INTERNALS
  485. X#define AM_MEMORY_MANAGER    /* we define jvirt_Xarray_control structs */
  486. X#include "jinclude.h"
  487. X#include "jpeglib.h"
  488. X#include "jmemsys.h"        /* import the system-dependent declarations */
  489. X
  490. X#ifndef NO_GETENV
  491. X#ifndef HAVE_STDLIB_H        /* <stdlib.h> should declare getenv() */
  492. Xextern char * getenv JPP((const char * name));
  493. X#endif
  494. X#endif
  495. X
  496. X
  497. X/*
  498. X * Some important notes:
  499. X *   The allocation routines provided here must never return NULL.
  500. X *   They should exit to error_exit if unsuccessful.
  501. X *
  502. X *   It's not a good idea to try to merge the sarray and barray routines,
  503. X *   even though they are textually almost the same, because samples are
  504. X *   usually stored as bytes while coefficients are shorts or ints.  Thus,
  505. X *   in machines where byte pointers have a different representation from
  506. X *   word pointers, the resulting machine code could not be the same.
  507. X */
  508. X
  509. X
  510. X/*
  511. X * Many machines require storage alignment: longs must start on 4-byte
  512. X * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
  513. X * always returns pointers that are multiples of the worst-case alignment
  514. X * requirement, and we had better do so too.
  515. X * There isn't any really portable way to determine the worst-case alignment
  516. X * requirement.  This module assumes that the alignment requirement is
  517. X * multiples of sizeof(ALIGN_TYPE).
  518. X * By default, we define ALIGN_TYPE as double.  This is necessary on some
  519. X * workstations (where doubles really do need 8-byte alignment) and will work
  520. X * fine on nearly everything.  If your machine has lesser alignment needs,
  521. X * you can save a few bytes by making ALIGN_TYPE smaller.
  522. X * The only place I know of where this will NOT work is certain Macintosh
  523. X * 680x0 compilers that define double as a 10-byte IEEE extended float.
  524. X * Doing 10-byte alignment is counterproductive because longwords won't be
  525. X * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
  526. X * such a compiler.
  527. X */
  528. X
  529. X#ifndef ALIGN_TYPE        /* so can override from jconfig.h */
  530. X#define ALIGN_TYPE  double
  531. X#endif
  532. X
  533. X
  534. X/*
  535. X * We allocate objects from "pools", where each pool is gotten with a single
  536. X * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
  537. X * overhead within a pool, except for alignment padding.  Each pool has a
  538. X * header with a link to the next pool of the same class.
  539. X * Small and large pool headers are identical except that the latter's
  540. X * link pointer must be FAR on 80x86 machines.
  541. X * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  542. X * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  543. X * of the alignment requirement of ALIGN_TYPE.
  544. X */
  545. X
  546. Xtypedef union small_pool_struct * small_pool_ptr;
  547. X
  548. Xtypedef union small_pool_struct {
  549. X  struct {
  550. X    small_pool_ptr next;    /* next in list of pools */
  551. X    size_t bytes_used;        /* how many bytes already used within pool */
  552. X    size_t bytes_left;        /* bytes still available in this pool */
  553. X  } hdr;
  554. X  ALIGN_TYPE dummy;        /* included in union to ensure alignment */
  555. X} small_pool_hdr;
  556. X
  557. Xtypedef union large_pool_struct FAR * large_pool_ptr;
  558. X
  559. Xtypedef union large_pool_struct {
  560. X  struct {
  561. X    large_pool_ptr next;    /* next in list of pools */
  562. X    size_t bytes_used;        /* how many bytes already used within pool */
  563. X    size_t bytes_left;        /* bytes still available in this pool */
  564. X  } hdr;
  565. X  ALIGN_TYPE dummy;        /* included in union to ensure alignment */
  566. X} large_pool_hdr;
  567. X
  568. X
  569. X/*
  570. X * Here is the full definition of a memory manager object.
  571. X */
  572. X
  573. Xtypedef struct {
  574. X  struct jpeg_memory_mgr pub;    /* public fields */
  575. X
  576. X  /* Each pool identifier (lifetime class) names a linked list of pools. */
  577. X  small_pool_ptr small_list[JPOOL_NUMPOOLS];
  578. X  large_pool_ptr large_list[JPOOL_NUMPOOLS];
  579. X
  580. X  /* Since we only have one lifetime class of virtual arrays, only one
  581. X   * linked list is necessary (for each datatype).  Note that the virtual
  582. X   * array control blocks being linked together are actually stored somewhere
  583. X   * in the small-pool list.
  584. X   */
  585. X  jvirt_sarray_ptr virt_sarray_list;
  586. X  jvirt_barray_ptr virt_barray_list;
  587. X
  588. X  /* This counts total space obtained from jpeg_get_small/large */
  589. X  long total_space_allocated;
  590. X
  591. X  /* alloc_sarray and alloc_barray set this value for use by virtual
  592. X   * array routines.
  593. X   */
  594. X  JDIMENSION last_rowsperchunk;    /* from most recent alloc_sarray/barray */
  595. X} my_memory_mgr;
  596. X
  597. Xtypedef my_memory_mgr * my_mem_ptr;
  598. X
  599. X
  600. X/*
  601. X * The control blocks for virtual arrays.
  602. X * Note that these blocks are allocated in the "small" pool area.
  603. X * System-dependent info for the associated backing store (if any) is hidden
  604. X * inside the backing_store_info struct.
  605. X */
  606. X
  607. Xstruct jvirt_sarray_control {
  608. X  JSAMPARRAY mem_buffer;    /* => the in-memory buffer */
  609. X  JDIMENSION rows_in_array;    /* total virtual array height */
  610. X  JDIMENSION samplesperrow;    /* width of array (and of memory buffer) */
  611. X  JDIMENSION unitheight;    /* # of rows accessed by access_virt_sarray */
  612. X  JDIMENSION rows_in_mem;    /* height of memory buffer */
  613. X  JDIMENSION rowsperchunk;    /* allocation chunk size in mem_buffer */
  614. X  JDIMENSION cur_start_row;    /* first logical row # in the buffer */
  615. X  boolean dirty;        /* do current buffer contents need written? */
  616. X  boolean b_s_open;        /* is backing-store data valid? */
  617. X  jvirt_sarray_ptr next;    /* link to next virtual sarray control block */
  618. X  backing_store_info b_s_info;    /* System-dependent control info */
  619. X};
  620. X
  621. Xstruct jvirt_barray_control {
  622. X  JBLOCKARRAY mem_buffer;    /* => the in-memory buffer */
  623. X  JDIMENSION rows_in_array;    /* total virtual array height */
  624. X  JDIMENSION blocksperrow;    /* width of array (and of memory buffer) */
  625. X  JDIMENSION unitheight;    /* # of rows accessed by access_virt_barray */
  626. X  JDIMENSION rows_in_mem;    /* height of memory buffer */
  627. X  JDIMENSION rowsperchunk;    /* allocation chunk size in mem_buffer */
  628. X  JDIMENSION cur_start_row;    /* first logical row # in the buffer */
  629. X  boolean dirty;        /* do current buffer contents need written? */
  630. X  boolean b_s_open;        /* is backing-store data valid? */
  631. X  jvirt_barray_ptr next;    /* link to next virtual barray control block */
  632. X  backing_store_info b_s_info;    /* System-dependent control info */
  633. X};
  634. X
  635. X
  636. X#ifdef MEM_STATS        /* optional extra stuff for statistics */
  637. X
  638. XLOCAL void
  639. Xprint_mem_stats (j_common_ptr cinfo, int pool_id)
  640. X{
  641. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  642. X  small_pool_ptr shdr_ptr;
  643. X  large_pool_ptr lhdr_ptr;
  644. X
  645. X  /* Since this is only a debugging stub, we can cheat a little by using
  646. X   * fprintf directly rather than going through the trace message code.
  647. X   * This is helpful because message parm array can't handle longs.
  648. X   */
  649. X  fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  650. X      pool_id, mem->total_space_allocated);
  651. X
  652. X  for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  653. X       lhdr_ptr = lhdr_ptr->hdr.next) {
  654. X    fprintf(stderr, "  Large chunk used %ld\n",
  655. X        (long) lhdr_ptr->hdr.bytes_used);
  656. X  }
  657. X
  658. X  for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  659. X       shdr_ptr = shdr_ptr->hdr.next) {
  660. X    fprintf(stderr, "  Small chunk used %ld free %ld\n",
  661. X        (long) shdr_ptr->hdr.bytes_used,
  662. X        (long) shdr_ptr->hdr.bytes_left);
  663. X  }
  664. X}
  665. X
  666. X#endif /* MEM_STATS */
  667. X
  668. X
  669. XLOCAL void
  670. Xout_of_memory (j_common_ptr cinfo, int which)
  671. X/* Report an out-of-memory error and stop execution */
  672. X/* If we compiled MEM_STATS support, report alloc requests before dying */
  673. X{
  674. X#ifdef MEM_STATS
  675. X  cinfo->err->trace_level = 2;    /* force self_destruct to report stats */
  676. X#endif
  677. X  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  678. X}
  679. X
  680. X
  681. X/*
  682. X * Allocation of "small" objects.
  683. X *
  684. X * For these, we use pooled storage.  When a new pool must be created,
  685. X * we try to get enough space for the current request plus a "slop" factor,
  686. X * where the slop will be the amount of leftover space in the new pool.
  687. X * The speed vs. space tradeoff is largely determined by the slop values.
  688. X * A different slop value is provided for each pool class (lifetime),
  689. X * and we also distinguish the first pool of a class from later ones.
  690. X * NOTE: the values given work fairly well on both 16- and 32-bit-int
  691. X * machines, but may be too small if longs are 64 bits or more.
  692. X */
  693. X
  694. Xstatic const size_t first_pool_slop[JPOOL_NUMPOOLS] = 
  695. X{
  696. X    1600,            /* first PERMANENT pool */
  697. X    16000            /* first IMAGE pool */
  698. X};
  699. X
  700. Xstatic const size_t extra_pool_slop[JPOOL_NUMPOOLS] = 
  701. X{
  702. X    0,            /* additional PERMANENT pools */
  703. X    5000            /* additional IMAGE pools */
  704. X};
  705. X
  706. X#define MIN_SLOP  50        /* greater than 0 to avoid futile looping */
  707. X
  708. X
  709. XMETHODDEF void *
  710. Xalloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  711. X/* Allocate a "small" object */
  712. X{
  713. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  714. X  small_pool_ptr hdr_ptr, prev_hdr_ptr;
  715. X  char * data_ptr;
  716. X  size_t odd_bytes, min_request, slop;
  717. X
  718. X  /* Check for unsatisfiable request (do now to ensure no overflow below) */
  719. X  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  720. X    out_of_memory(cinfo, 1);    /* request exceeds malloc's ability */
  721. X
  722. X  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  723. X  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  724. X  if (odd_bytes > 0)
  725. X    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  726. X
  727. X  /* See if space is available in any existing pool */
  728. X  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  729. X    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);    /* safety check */
  730. X  prev_hdr_ptr = NULL;
  731. X  hdr_ptr = mem->small_list[pool_id];
  732. X  while (hdr_ptr != NULL) {
  733. X    if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  734. X      break;            /* found pool with enough space */
  735. X    prev_hdr_ptr = hdr_ptr;
  736. X    hdr_ptr = hdr_ptr->hdr.next;
  737. X  }
  738. X
  739. X  /* Time to make a new pool? */
  740. X  if (hdr_ptr == NULL) {
  741. X    /* min_request is what we need now, slop is what will be leftover */
  742. X    min_request = sizeofobject + SIZEOF(small_pool_hdr);
  743. X    if (prev_hdr_ptr == NULL)    /* first pool in class? */
  744. X      slop = first_pool_slop[pool_id];
  745. X    else
  746. X      slop = extra_pool_slop[pool_id];
  747. X    /* Don't ask for more than MAX_ALLOC_CHUNK */
  748. X    if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  749. X      slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  750. X    /* Try to get space, if fail reduce slop and try again */
  751. X    for (;;) {
  752. X      hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  753. X      if (hdr_ptr != NULL)
  754. X    break;
  755. X      slop /= 2;
  756. X      if (slop < MIN_SLOP)    /* give up when it gets real small */
  757. X    out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  758. X    }
  759. X    mem->total_space_allocated += min_request + slop;
  760. X    /* Success, initialize the new pool header and add to end of list */
  761. X    hdr_ptr->hdr.next = NULL;
  762. X    hdr_ptr->hdr.bytes_used = 0;
  763. X    hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  764. X    if (prev_hdr_ptr == NULL)    /* first pool in class? */
  765. X      mem->small_list[pool_id] = hdr_ptr;
  766. X    else
  767. X      prev_hdr_ptr->hdr.next = hdr_ptr;
  768. X  }
  769. X
  770. X  /* OK, allocate the object from the current pool */
  771. X  data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  772. X  data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  773. X  hdr_ptr->hdr.bytes_used += sizeofobject;
  774. X  hdr_ptr->hdr.bytes_left -= sizeofobject;
  775. X
  776. X  return (void *) data_ptr;
  777. X}
  778. X
  779. X
  780. X/*
  781. X * Allocation of "large" objects.
  782. X *
  783. X * The external semantics of these are the same as "small" objects,
  784. X * except that FAR pointers are used on 80x86.  However the pool
  785. X * management heuristics are quite different.  We assume that each
  786. X * request is large enough that it may as well be passed directly to
  787. X * jpeg_get_large; the pool management just links everything together
  788. X * so that we can free it all on demand.
  789. X * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  790. X * structures.  The routines that create these structures (see below)
  791. X * deliberately bunch rows together to ensure a large request size.
  792. X */
  793. X
  794. XMETHODDEF void FAR *
  795. Xalloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  796. X/* Allocate a "large" object */
  797. X{
  798. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  799. X  large_pool_ptr hdr_ptr;
  800. X  size_t odd_bytes;
  801. X
  802. X  /* Check for unsatisfiable request (do now to ensure no overflow below) */
  803. X  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  804. X    out_of_memory(cinfo, 3);    /* request exceeds malloc's ability */
  805. X
  806. X  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  807. X  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  808. X  if (odd_bytes > 0)
  809. X    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  810. X
  811. X  /* Always make a new pool */
  812. X  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  813. X    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);    /* safety check */
  814. X
  815. X  hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  816. X                        SIZEOF(large_pool_hdr));
  817. X  if (hdr_ptr == NULL)
  818. X    out_of_memory(cinfo, 4);    /* jpeg_get_large failed */
  819. X  mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  820. X
  821. X  /* Success, initialize the new pool header and add to list */
  822. X  hdr_ptr->hdr.next = mem->large_list[pool_id];
  823. X  /* We maintain space counts in each pool header for statistical purposes,
  824. X   * even though they are not needed for allocation.
  825. X   */
  826. X  hdr_ptr->hdr.bytes_used = sizeofobject;
  827. X  hdr_ptr->hdr.bytes_left = 0;
  828. X  mem->large_list[pool_id] = hdr_ptr;
  829. X
  830. X  return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  831. X}
  832. X
  833. X
  834. X/*
  835. X * Creation of 2-D sample arrays.
  836. X * The pointers are in near heap, the samples themselves in FAR heap.
  837. X *
  838. X * To minimize allocation overhead and to allow I/O of large contiguous
  839. X * blocks, we allocate the sample rows in groups of as many rows as possible
  840. X * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  841. X * NB: the virtual array control routines, later in this file, know about
  842. X * this chunking of rows.  The rowsperchunk value is left in the mem manager
  843. X * object so that it can be saved away if this sarray is the workspace for
  844. X * a virtual array.
  845. X */
  846. X
  847. XMETHODDEF JSAMPARRAY
  848. Xalloc_sarray (j_common_ptr cinfo, int pool_id,
  849. X          JDIMENSION samplesperrow, JDIMENSION numrows)
  850. X/* Allocate a 2-D sample array */
  851. X{
  852. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  853. X  JSAMPARRAY result;
  854. X  JSAMPROW workspace;
  855. X  JDIMENSION rowsperchunk, currow, i;
  856. X  long ltemp;
  857. X
  858. X  /* Calculate max # of rows allowed in one allocation chunk */
  859. X  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  860. X      ((long) samplesperrow * SIZEOF(JSAMPLE));
  861. X  if (ltemp <= 0)
  862. X    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  863. X  if (ltemp < (long) numrows)
  864. X    rowsperchunk = (JDIMENSION) ltemp;
  865. X  else
  866. X    rowsperchunk = numrows;
  867. X  mem->last_rowsperchunk = rowsperchunk;
  868. X
  869. X  /* Get space for row pointers (small object) */
  870. X  result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  871. X                    (size_t) (numrows * SIZEOF(JSAMPROW)));
  872. X
  873. X  /* Get the rows themselves (large objects) */
  874. X  currow = 0;
  875. X  while (currow < numrows) {
  876. X    rowsperchunk = MIN(rowsperchunk, numrows - currow);
  877. X    workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  878. X    (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  879. X          * SIZEOF(JSAMPLE)));
  880. X    for (i = rowsperchunk; i > 0; i--) {
  881. X      result[currow++] = workspace;
  882. X      workspace += samplesperrow;
  883. X    }
  884. X  }
  885. X
  886. X  return result;
  887. X}
  888. X
  889. X
  890. X/*
  891. X * Creation of 2-D coefficient-block arrays.
  892. X * This is essentially the same as the code for sample arrays, above.
  893. X */
  894. X
  895. XMETHODDEF JBLOCKARRAY
  896. Xalloc_barray (j_common_ptr cinfo, int pool_id,
  897. X          JDIMENSION blocksperrow, JDIMENSION numrows)
  898. X/* Allocate a 2-D coefficient-block array */
  899. X{
  900. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  901. X  JBLOCKARRAY result;
  902. X  JBLOCKROW workspace;
  903. X  JDIMENSION rowsperchunk, currow, i;
  904. X  long ltemp;
  905. X
  906. X  /* Calculate max # of rows allowed in one allocation chunk */
  907. X  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  908. X      ((long) blocksperrow * SIZEOF(JBLOCK));
  909. X  if (ltemp <= 0)
  910. X    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  911. X  if (ltemp < (long) numrows)
  912. X    rowsperchunk = (JDIMENSION) ltemp;
  913. X  else
  914. X    rowsperchunk = numrows;
  915. X  mem->last_rowsperchunk = rowsperchunk;
  916. X
  917. X  /* Get space for row pointers (small object) */
  918. X  result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  919. X                     (size_t) (numrows * SIZEOF(JBLOCKROW)));
  920. X
  921. X  /* Get the rows themselves (large objects) */
  922. X  currow = 0;
  923. X  while (currow < numrows) {
  924. X    rowsperchunk = MIN(rowsperchunk, numrows - currow);
  925. X    workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  926. X    (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  927. X          * SIZEOF(JBLOCK)));
  928. X    for (i = rowsperchunk; i > 0; i--) {
  929. X      result[currow++] = workspace;
  930. X      workspace += blocksperrow;
  931. X    }
  932. X  }
  933. X
  934. X  return result;
  935. X}
  936. X
  937. X
  938. X/*
  939. X * About virtual array management:
  940. X *
  941. X * To allow machines with limited memory to handle large images, all
  942. X * processing in the JPEG system is done a few pixel or block rows at a time.
  943. X * The above "normal" array routines are only used to allocate strip buffers
  944. X * (as wide as the image, but just a few rows high).
  945. X * In some cases multiple passes must be made over the data.  In these
  946. X * cases the virtual array routines are used.  The array is still accessed
  947. X * a strip at a time, but the memory manager must save the whole array
  948. X * for repeated accesses.  The intended implementation is that there is
  949. X * a strip buffer in memory (as high as is possible given the desired memory
  950. X * limit), plus a backing file that holds the rest of the array.
  951. X *
  952. X * The request_virt_array routines are told the total size of the image and
  953. X * the unit height, which is the number of rows that will be accessed at once;
  954. X * the in-memory buffer should be made a multiple of this height for best
  955. X * efficiency.
  956. X *
  957. X * The request routines create control blocks but not the in-memory buffers.
  958. X * That is postponed until realize_virt_arrays is called.  At that time the
  959. X * total amount of space needed is known (approximately, anyway), so free
  960. X * memory can be divided up fairly.
  961. X *
  962. X * The access_virt_array routines are responsible for making a specific strip
  963. X * area accessible (after reading or writing the backing file, if necessary).
  964. X * Note that the access routines are told whether the caller intends to modify
  965. X * the accessed strip; during a read-only pass this saves having to rewrite
  966. X * data to disk.
  967. X *
  968. X * The typical access pattern is one top-to-bottom pass to write the data,
  969. X * followed by one or more read-only top-to-bottom passes.  However, other
  970. X * access patterns may occur while reading.  For example, translation of image
  971. X * formats that use bottom-to-top scan order will require bottom-to-top read
  972. X * passes.  The memory manager need not support multiple write passes nor
  973. X * funny write orders (meaning that rearranging rows must be handled while
  974. X * reading data out of the virtual array, not while putting it in).  THIS WILL
  975. X * PROBABLY NEED TO CHANGE ... will need multiple write passes for progressive
  976. X * JPEG decoding.
  977. X *
  978. X * In current usage, the access requests are always for nonoverlapping strips;
  979. X * that is, successive access start_row numbers always differ by exactly the
  980. X * unitheight.  This allows fairly simple buffer dump/reload logic if the
  981. X * in-memory buffer is made a multiple of the unitheight.  The code below
  982. X * would work with overlapping access requests, but not very efficiently.
  983. X */
  984. X
  985. X
  986. XMETHODDEF jvirt_sarray_ptr
  987. Xrequest_virt_sarray (j_common_ptr cinfo, int pool_id,
  988. X             JDIMENSION samplesperrow, JDIMENSION numrows,
  989. X             JDIMENSION unitheight)
  990. X/* Request a virtual 2-D sample array */
  991. X{
  992. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  993. X  jvirt_sarray_ptr result;
  994. X
  995. X  /* Only IMAGE-lifetime virtual arrays are currently supported */
  996. X  if (pool_id != JPOOL_IMAGE)
  997. X    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);    /* safety check */
  998. X
  999. X  /* Round array size up to a multiple of unitheight */
  1000. X  numrows = (JDIMENSION) jround_up((long) numrows, (long) unitheight);
  1001. X
  1002. X  /* get control block */
  1003. X  result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  1004. X                      SIZEOF(struct jvirt_sarray_control));
  1005. X
  1006. X  result->mem_buffer = NULL;    /* marks array not yet realized */
  1007. X  result->rows_in_array = numrows;
  1008. X  result->samplesperrow = samplesperrow;
  1009. X  result->unitheight = unitheight;
  1010. X  result->b_s_open = FALSE;    /* no associated backing-store object */
  1011. X  result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  1012. X  mem->virt_sarray_list = result;
  1013. X
  1014. X  return result;
  1015. X}
  1016. X
  1017. X
  1018. XMETHODDEF jvirt_barray_ptr
  1019. Xrequest_virt_barray (j_common_ptr cinfo, int pool_id,
  1020. X             JDIMENSION blocksperrow, JDIMENSION numrows,
  1021. X             JDIMENSION unitheight)
  1022. X/* Request a virtual 2-D coefficient-block array */
  1023. X{
  1024. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  1025. X  jvirt_barray_ptr result;
  1026. X
  1027. X  /* Only IMAGE-lifetime virtual arrays are currently supported */
  1028. X  if (pool_id != JPOOL_IMAGE)
  1029. X    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);    /* safety check */
  1030. X
  1031. X  /* Round array size up to a multiple of unitheight */
  1032. X  numrows = (JDIMENSION) jround_up((long) numrows, (long) unitheight);
  1033. X
  1034. X  /* get control block */
  1035. X  result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  1036. X                      SIZEOF(struct jvirt_barray_control));
  1037. X
  1038. X  result->mem_buffer = NULL;    /* marks array not yet realized */
  1039. X  result->rows_in_array = numrows;
  1040. X  result->blocksperrow = blocksperrow;
  1041. X  result->unitheight = unitheight;
  1042. X  result->b_s_open = FALSE;    /* no associated backing-store object */
  1043. X  result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  1044. X  mem->virt_barray_list = result;
  1045. X
  1046. X  return result;
  1047. X}
  1048. X
  1049. X
  1050. XMETHODDEF void
  1051. Xrealize_virt_arrays (j_common_ptr cinfo)
  1052. X/* Allocate the in-memory buffers for any unrealized virtual arrays */
  1053. X{
  1054. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  1055. X  long space_per_unitheight, maximum_space, avail_mem;
  1056. X  long unitheights, max_unitheights;
  1057. X  jvirt_sarray_ptr sptr;
  1058. X  jvirt_barray_ptr bptr;
  1059. X
  1060. X  /* Compute the minimum space needed (unitheight rows in each buffer)
  1061. X   * and the maximum space needed (full image height in each buffer).
  1062. X   * These may be of use to the system-dependent jpeg_mem_available routine.
  1063. X   */
  1064. X  space_per_unitheight = 0;
  1065. X  maximum_space = 0;
  1066. X  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  1067. X    if (sptr->mem_buffer == NULL) { /* if not realized yet */
  1068. X      space_per_unitheight += (long) sptr->unitheight *
  1069. X                  (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  1070. X      maximum_space += (long) sptr->rows_in_array *
  1071. X               (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  1072. X    }
  1073. X  }
  1074. X  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  1075. X    if (bptr->mem_buffer == NULL) { /* if not realized yet */
  1076. X      space_per_unitheight += (long) bptr->unitheight *
  1077. X                  (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  1078. X      maximum_space += (long) bptr->rows_in_array *
  1079. X               (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  1080. X    }
  1081. X  }
  1082. X
  1083. X  if (space_per_unitheight <= 0)
  1084. X    return;            /* no unrealized arrays, no work */
  1085. X
  1086. X  /* Determine amount of memory to actually use; this is system-dependent. */
  1087. X  avail_mem = jpeg_mem_available(cinfo, space_per_unitheight, maximum_space,
  1088. X                 mem->total_space_allocated);
  1089. X
  1090. X  /* If the maximum space needed is available, make all the buffers full
  1091. X   * height; otherwise parcel it out with the same number of unitheights
  1092. X   * in each buffer.
  1093. X   */
  1094. X  if (avail_mem >= maximum_space)
  1095. X    max_unitheights = 1000000000L;
  1096. X  else {
  1097. X    max_unitheights = avail_mem / space_per_unitheight;
  1098. X    /* If there doesn't seem to be enough space, try to get the minimum
  1099. X     * anyway.  This allows a "stub" implementation of jpeg_mem_available().
  1100. X     */
  1101. X    if (max_unitheights <= 0)
  1102. X      max_unitheights = 1;
  1103. X  }
  1104. X
  1105. X  /* Allocate the in-memory buffers and initialize backing store as needed. */
  1106. X
  1107. X  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  1108. X    if (sptr->mem_buffer == NULL) { /* if not realized yet */
  1109. X      unitheights = ((long) sptr->rows_in_array - 1L) / sptr->unitheight + 1L;
  1110. X      if (unitheights <= max_unitheights) {
  1111. X    /* This buffer fits in memory */
  1112. X    sptr->rows_in_mem = sptr->rows_in_array;
  1113. X      } else {
  1114. X    /* It doesn't fit in memory, create backing store. */
  1115. X    sptr->rows_in_mem = (JDIMENSION) (max_unitheights * sptr->unitheight);
  1116. X    jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  1117. X                (long) sptr->rows_in_array *
  1118. X                (long) sptr->samplesperrow *
  1119. X                (long) SIZEOF(JSAMPLE));
  1120. X    sptr->b_s_open = TRUE;
  1121. X      }
  1122. X      sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  1123. X                      sptr->samplesperrow, sptr->rows_in_mem);
  1124. X      sptr->rowsperchunk = mem->last_rowsperchunk;
  1125. X      sptr->cur_start_row = 0;
  1126. X      sptr->dirty = FALSE;
  1127. X    }
  1128. X  }
  1129. X
  1130. X  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  1131. X    if (bptr->mem_buffer == NULL) { /* if not realized yet */
  1132. X      unitheights = ((long) bptr->rows_in_array - 1L) / bptr->unitheight + 1L;
  1133. X      if (unitheights <= max_unitheights) {
  1134. X    /* This buffer fits in memory */
  1135. X    bptr->rows_in_mem = bptr->rows_in_array;
  1136. X      } else {
  1137. X    /* It doesn't fit in memory, create backing store. */
  1138. X    bptr->rows_in_mem = (JDIMENSION) (max_unitheights * bptr->unitheight);
  1139. X    jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  1140. X                (long) bptr->rows_in_array *
  1141. X                (long) bptr->blocksperrow *
  1142. X                (long) SIZEOF(JBLOCK));
  1143. X    bptr->b_s_open = TRUE;
  1144. X      }
  1145. X      bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  1146. X                      bptr->blocksperrow, bptr->rows_in_mem);
  1147. X      bptr->rowsperchunk = mem->last_rowsperchunk;
  1148. X      bptr->cur_start_row = 0;
  1149. X      bptr->dirty = FALSE;
  1150. X    }
  1151. X  }
  1152. X}
  1153. X
  1154. X
  1155. XLOCAL void
  1156. Xdo_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  1157. X/* Do backing store read or write of a virtual sample array */
  1158. X{
  1159. X  long bytesperrow, file_offset, byte_count, rows, i;
  1160. X
  1161. X  bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  1162. X  file_offset = ptr->cur_start_row * bytesperrow;
  1163. X  /* Loop to read or write each allocation chunk in mem_buffer */
  1164. X  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  1165. X    /* One chunk, but check for short chunk at end of buffer */
  1166. X    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  1167. X    /* Transfer no more than fits in file */
  1168. X    rows = MIN(rows, (long) ptr->rows_in_array -
  1169. X            ((long) ptr->cur_start_row + i));
  1170. X    if (rows <= 0)        /* this chunk might be past end of file! */
  1171. X      break;
  1172. X    byte_count = rows * bytesperrow;
  1173. X    if (writing)
  1174. X      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  1175. X                        (void FAR *) ptr->mem_buffer[i],
  1176. X                        file_offset, byte_count);
  1177. X    else
  1178. X      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  1179. X                       (void FAR *) ptr->mem_buffer[i],
  1180. X                       file_offset, byte_count);
  1181. X    file_offset += byte_count;
  1182. X  }
  1183. X}
  1184. X
  1185. X
  1186. XLOCAL void
  1187. Xdo_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  1188. X/* Do backing store read or write of a virtual coefficient-block array */
  1189. X{
  1190. X  long bytesperrow, file_offset, byte_count, rows, i;
  1191. X
  1192. X  bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  1193. X  file_offset = ptr->cur_start_row * bytesperrow;
  1194. X  /* Loop to read or write each allocation chunk in mem_buffer */
  1195. X  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  1196. X    /* One chunk, but check for short chunk at end of buffer */
  1197. X    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  1198. X    /* Transfer no more than fits in file */
  1199. X    rows = MIN(rows, (long) ptr->rows_in_array -
  1200. X            ((long) ptr->cur_start_row + i));
  1201. X    if (rows <= 0)        /* this chunk might be past end of file! */
  1202. X      break;
  1203. X    byte_count = rows * bytesperrow;
  1204. X    if (writing)
  1205. X      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  1206. X                        (void FAR *) ptr->mem_buffer[i],
  1207. X                        file_offset, byte_count);
  1208. X    else
  1209. X      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  1210. X                       (void FAR *) ptr->mem_buffer[i],
  1211. X                       file_offset, byte_count);
  1212. X    file_offset += byte_count;
  1213. X  }
  1214. X}
  1215. X
  1216. X
  1217. XMETHODDEF JSAMPARRAY
  1218. Xaccess_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  1219. X            JDIMENSION start_row, boolean writable)
  1220. X/* Access the part of a virtual sample array starting at start_row */
  1221. X/* and extending for ptr->unitheight rows.  writable is true if  */
  1222. X/* caller intends to modify the accessed area. */
  1223. X{
  1224. X  /* debugging check */
  1225. X  if (start_row >= ptr->rows_in_array || ptr->mem_buffer == NULL)
  1226. X    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  1227. X
  1228. X  /* Make the desired part of the virtual array accessible */
  1229. X  if (start_row < ptr->cur_start_row ||
  1230. X      start_row+ptr->unitheight > ptr->cur_start_row+ptr->rows_in_mem) {
  1231. X    if (! ptr->b_s_open)
  1232. X      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  1233. X    /* Flush old buffer contents if necessary */
  1234. X    if (ptr->dirty) {
  1235. X      do_sarray_io(cinfo, ptr, TRUE);
  1236. X      ptr->dirty = FALSE;
  1237. X    }
  1238. X    /* Decide what part of virtual array to access.
  1239. X     * Algorithm: if target address > current window, assume forward scan,
  1240. X     * load starting at target address.  If target address < current window,
  1241. X     * assume backward scan, load so that target area is top of window.
  1242. X     * Note that when switching from forward write to forward read, will have
  1243. X     * start_row = 0, so the limiting case applies and we load from 0 anyway.
  1244. X     */
  1245. X    if (start_row > ptr->cur_start_row) {
  1246. X      ptr->cur_start_row = start_row;
  1247. X    } else {
  1248. X      /* use long arithmetic here to avoid overflow & unsigned problems */
  1249. X      long ltemp;
  1250. X
  1251. X      ltemp = (long) start_row + (long) ptr->unitheight -
  1252. X          (long) ptr->rows_in_mem;
  1253. X      if (ltemp < 0)
  1254. X    ltemp = 0;        /* don't fall off front end of file */
  1255. X      ptr->cur_start_row = (JDIMENSION) ltemp;
  1256. X    }
  1257. X    /* If reading, read in the selected part of the array. 
  1258. X     * If we are writing, we need not pre-read the selected portion,
  1259. X     * since the access sequence constraints ensure it would be garbage.
  1260. X     */
  1261. X    if (! writable) {
  1262. X      do_sarray_io(cinfo, ptr, FALSE);
  1263. X    }
  1264. X  }
  1265. X  /* Flag the buffer dirty if caller will write in it */
  1266. X  if (writable)
  1267. X    ptr->dirty = TRUE;
  1268. X  /* Return address of proper part of the buffer */
  1269. X  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  1270. X}
  1271. X
  1272. X
  1273. XMETHODDEF JBLOCKARRAY
  1274. Xaccess_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  1275. X            JDIMENSION start_row, boolean writable)
  1276. X/* Access the part of a virtual block array starting at start_row */
  1277. X/* and extending for ptr->unitheight rows.  writable is true if  */
  1278. X/* caller intends to modify the accessed area. */
  1279. X{
  1280. X  /* debugging check */
  1281. X  if (start_row >= ptr->rows_in_array || ptr->mem_buffer == NULL)
  1282. X    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  1283. X
  1284. X  /* Make the desired part of the virtual array accessible */
  1285. X  if (start_row < ptr->cur_start_row ||
  1286. X      start_row+ptr->unitheight > ptr->cur_start_row+ptr->rows_in_mem) {
  1287. X    if (! ptr->b_s_open)
  1288. X      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  1289. X    /* Flush old buffer contents if necessary */
  1290. X    if (ptr->dirty) {
  1291. X      do_barray_io(cinfo, ptr, TRUE);
  1292. X      ptr->dirty = FALSE;
  1293. X    }
  1294. X    /* Decide what part of virtual array to access.
  1295. X     * Algorithm: if target address > current window, assume forward scan,
  1296. X     * load starting at target address.  If target address < current window,
  1297. X     * assume backward scan, load so that target area is top of window.
  1298. X     * Note that when switching from forward write to forward read, will have
  1299. X     * start_row = 0, so the limiting case applies and we load from 0 anyway.
  1300. X     */
  1301. X    if (start_row > ptr->cur_start_row) {
  1302. X      ptr->cur_start_row = start_row;
  1303. X    } else {
  1304. X      /* use long arithmetic here to avoid overflow & unsigned problems */
  1305. X      long ltemp;
  1306. X
  1307. X      ltemp = (long) start_row + (long) ptr->unitheight -
  1308. X          (long) ptr->rows_in_mem;
  1309. X      if (ltemp < 0)
  1310. X    ltemp = 0;        /* don't fall off front end of file */
  1311. X      ptr->cur_start_row = (JDIMENSION) ltemp;
  1312. X    }
  1313. X    /* If reading, read in the selected part of the array. 
  1314. X     * If we are writing, we need not pre-read the selected portion,
  1315. X     * since the access sequence constraints ensure it would be garbage.
  1316. X     */
  1317. X    if (! writable) {
  1318. X      do_barray_io(cinfo, ptr, FALSE);
  1319. X    }
  1320. X  }
  1321. X  /* Flag the buffer dirty if caller will write in it */
  1322. X  if (writable)
  1323. X    ptr->dirty = TRUE;
  1324. X  /* Return address of proper part of the buffer */
  1325. X  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  1326. X}
  1327. X
  1328. X
  1329. X/*
  1330. X * Release all objects belonging to a specified pool.
  1331. X */
  1332. X
  1333. XMETHODDEF void
  1334. Xfree_pool (j_common_ptr cinfo, int pool_id)
  1335. X{
  1336. X  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  1337. X  small_pool_ptr shdr_ptr;
  1338. X  large_pool_ptr lhdr_ptr;
  1339. X  size_t space_freed;
  1340. X
  1341. X  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  1342. X    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);    /* safety check */
  1343. X
  1344. X#ifdef MEM_STATS
  1345. X  if (cinfo->err->trace_level > 1)
  1346. X    print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  1347. X#endif
  1348. X
  1349. X  /* If freeing IMAGE pool, close any virtual arrays first */
  1350. X  if (pool_id == JPOOL_IMAGE) {
  1351. X    jvirt_sarray_ptr sptr;
  1352. X    jvirt_barray_ptr bptr;
  1353. X
  1354. X    for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  1355. X      if (sptr->b_s_open) {    /* there may be no backing store */
  1356. X    sptr->b_s_open = FALSE;    /* prevent recursive close if error */
  1357. X    (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  1358. X      }
  1359. X    }
  1360. X    mem->virt_sarray_list = NULL;
  1361. X    for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  1362. X      if (bptr->b_s_open) {    /* there may be no backing store */
  1363. X    bptr->b_s_open = FALSE;    /* prevent recursive close if error */
  1364. X    (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  1365. X      }
  1366. X    }
  1367. X    mem->virt_barray_list = NULL;
  1368. X  }
  1369. X
  1370. X  /* Release large objects */
  1371. X  lhdr_ptr = mem->large_list[pool_id];
  1372. X  mem->large_list[pool_id] = NULL;
  1373. X
  1374. X  while (lhdr_ptr != NULL) {
  1375. X    large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  1376. X    space_freed = lhdr_ptr->hdr.bytes_used +
  1377. X          lhdr_ptr->hdr.bytes_left +
  1378. X          SIZEOF(large_pool_hdr);
  1379. X    jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  1380. X    mem->total_space_allocated -= space_freed;
  1381. X    lhdr_ptr = next_lhdr_ptr;
  1382. X  }
  1383. X
  1384. X  /* Release small objects */
  1385. X  shdr_ptr = mem->small_list[pool_id];
  1386. X  mem->small_list[pool_id] = NULL;
  1387. X
  1388. X  while (shdr_ptr != NULL) {
  1389. X    small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  1390. X    space_freed = shdr_ptr->hdr.bytes_used +
  1391. X          shdr_ptr->hdr.bytes_left +
  1392. X          SIZEOF(small_pool_hdr);
  1393. X    jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  1394. X    mem->total_space_allocated -= space_freed;
  1395. X    shdr_ptr = next_shdr_ptr;
  1396. X  }
  1397. X}
  1398. X
  1399. X
  1400. X/*
  1401. X * Close up shop entirely.
  1402. X * Note that this cannot be called unless cinfo->mem is non-NULL.
  1403. X */
  1404. X
  1405. XMETHODDEF void
  1406. Xself_destruct (j_common_ptr cinfo)
  1407. X{
  1408. X  int pool;
  1409. X
  1410. X  /* Close all backing store, release all memory.
  1411. X   * Releasing pools in reverse order might help avoid fragmentation
  1412. X   * with some (brain-damaged) malloc libraries.
  1413. X   */
  1414. X  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  1415. X    free_pool(cinfo, pool);
  1416. X  }
  1417. X
  1418. X  /* Release the memory manager control block too. */
  1419. X  jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  1420. X  cinfo->mem = NULL;        /* ensures I will be called only once */
  1421. X
  1422. X  jpeg_mem_term(cinfo);        /* system-dependent cleanup */
  1423. X}
  1424. X
  1425. X
  1426. X/*
  1427. X * Memory manager initialization.
  1428. X * When this is called, only the error manager pointer is valid in cinfo!
  1429. X */
  1430. X
  1431. XGLOBAL void
  1432. Xjinit_memory_mgr (j_common_ptr cinfo)
  1433. X{
  1434. X  my_mem_ptr mem;
  1435. X  long max_to_use;
  1436. X  int pool;
  1437. X  size_t test_mac;
  1438. X
  1439. X  cinfo->mem = NULL;        /* for safety if init fails */
  1440. X
  1441. X  /* Check for configuration errors.
  1442. X   * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  1443. X   * doesn't reflect any real hardware alignment requirement.
  1444. X   * The test is a little tricky: for X>0, X and X-1 have no one-bits
  1445. X   * in common if and only if X is a power of 2, ie has only one one-bit.
  1446. X   * Some compilers may give an "unreachable code" warning here; ignore it.
  1447. X   */
  1448. X  if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  1449. X    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  1450. X  /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  1451. X   * a multiple of SIZEOF(ALIGN_TYPE).
  1452. X   * Again, an "unreachable code" warning may be ignored here.
  1453. X   * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  1454. X   */
  1455. X  test_mac = (size_t) MAX_ALLOC_CHUNK;
  1456. X  if ((long) test_mac != MAX_ALLOC_CHUNK ||
  1457. X      (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  1458. X    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  1459. X
  1460. X  max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  1461. X
  1462. X  /* Attempt to allocate memory manager's control block */
  1463. X  mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  1464. X
  1465. X  if (mem == NULL) {
  1466. X    jpeg_mem_term(cinfo);    /* system-dependent cleanup */
  1467. X    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  1468. X  }
  1469. X
  1470. X  /* OK, fill in the method pointers */
  1471. X  mem->pub.alloc_small = alloc_small;
  1472. X  mem->pub.alloc_large = alloc_large;
  1473. X  mem->pub.alloc_sarray = alloc_sarray;
  1474. X  mem->pub.alloc_barray = alloc_barray;
  1475. X  mem->pub.request_virt_sarray = request_virt_sarray;
  1476. X  mem->pub.request_virt_barray = request_virt_barray;
  1477. X  mem->pub.realize_virt_arrays = realize_virt_arrays;
  1478. X  mem->pub.access_virt_sarray = access_virt_sarray;
  1479. X  mem->pub.access_virt_barray = access_virt_barray;
  1480. X  mem->pub.free_pool = free_pool;
  1481. X  mem->pub.self_destruct = self_destruct;
  1482. X
  1483. X  /* Initialize working state */
  1484. X  mem->pub.max_memory_to_use = max_to_use;
  1485. X
  1486. X  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  1487. X    mem->small_list[pool] = NULL;
  1488. X    mem->large_list[pool] = NULL;
  1489. X  }
  1490. X  mem->virt_sarray_list = NULL;
  1491. X  mem->virt_barray_list = NULL;
  1492. X
  1493. X  mem->total_space_allocated = SIZEOF(my_memory_mgr);
  1494. X
  1495. X  /* Declare ourselves open for business */
  1496. X  cinfo->mem = & mem->pub;
  1497. X
  1498. X  /* Check for an environment variable JPEGMEM; if found, override the
  1499. X   * default max_memory setting from jpeg_mem_init.  Note that the
  1500. X   * surrounding application may again override this value.
  1501. X   * If your system doesn't support getenv(), define NO_GETENV to disable
  1502. X   * this feature.
  1503. X   */
  1504. X#ifndef NO_GETENV
  1505. X  { char * memenv;
  1506. X
  1507. X    if ((memenv = getenv("JPEGMEM")) != NULL) {
  1508. X      char ch = 'x';
  1509. X
  1510. X      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  1511. X    if (ch == 'm' || ch == 'M')
  1512. X      max_to_use *= 1000L;
  1513. X    mem->pub.max_memory_to_use = max_to_use * 1000L;
  1514. X      }
  1515. X    }
  1516. X  }
  1517. X#endif
  1518. X
  1519. X}
  1520. END_OF_FILE
  1521.   if test 38963 -ne `wc -c <'jmemmgr.c'`; then
  1522.     echo shar: \"'jmemmgr.c'\" unpacked with wrong size!
  1523.   fi
  1524.   # end of 'jmemmgr.c'
  1525. fi
  1526. if test -f 'jversion.h' -a "${1}" != "-c" ; then 
  1527.   echo shar: Will not clobber existing file \"'jversion.h'\"
  1528. else
  1529.   echo shar: Extracting \"'jversion.h'\" \(357 characters\)
  1530.   sed "s/^X//" >'jversion.h' <<'END_OF_FILE'
  1531. X/*
  1532. X * jversion.h
  1533. X *
  1534. X * Copyright (C) 1991-1994, Thomas G. Lane.
  1535. X * This file is part of the Independent JPEG Group's software.
  1536. X * For conditions of distribution and use, see the accompanying README file.
  1537. X *
  1538. X * This file contains software version identification.
  1539. X */
  1540. X
  1541. X
  1542. X#define JVERSION    "5  24-Sep-94"
  1543. X
  1544. X#define JCOPYRIGHT    "Copyright (C) 1994, Thomas G. Lane"
  1545. END_OF_FILE
  1546.   if test 357 -ne `wc -c <'jversion.h'`; then
  1547.     echo shar: \"'jversion.h'\" unpacked with wrong size!
  1548.   fi
  1549.   # end of 'jversion.h'
  1550. fi
  1551. echo shar: End of archive 1 \(of 27\).
  1552. cp /dev/null ark1isdone
  1553. MISSING=""
  1554. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ; do
  1555.     if test ! -f ark${I}isdone ; then
  1556.     MISSING="${MISSING} ${I}"
  1557.     fi
  1558. done
  1559. if test "${MISSING}" = "" ; then
  1560.     echo You have unpacked all 27 archives.
  1561.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1562. else
  1563.     echo You still must unpack the following archives:
  1564.     echo "        " ${MISSING}
  1565. fi
  1566. exit 0
  1567. exit 0 # Just in case...
  1568.