jpeg.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. Copyright (c) 2001, Loki software, inc.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without modification,
  5. are permitted provided that the following conditions are met:
  6. Redistributions of source code must retain the above copyright notice, this list
  7. of conditions and the following disclaimer.
  8. Redistributions in binary form must reproduce the above copyright notice, this
  9. list of conditions and the following disclaimer in the documentation and/or
  10. other materials provided with the distribution.
  11. Neither the name of Loki software nor the names of its contributors may be used
  12. to endorse or promote products derived from this software without specific prior
  13. written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
  18. DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  21. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. //
  26. // Functions to load JPEG files from a buffer, based on jdatasrc.c
  27. //
  28. // Leonardo Zide (leo@lokigames.com)
  29. //
  30. #include "jpeg.h"
  31. #include <setjmp.h>
  32. #include <stdlib.h>
  33. #include <stdio.h>
  34. #include <string.h>
  35. extern "C" {
  36. #include "radiant_jpeglib.h"
  37. #include "jpeg6/jerror.h"
  38. }
  39. #include "ifilesystem.h"
  40. #include "imagelib.h"
  41. typedef unsigned char byte;
  42. /* Expanded data source object for stdio input */
  43. typedef struct {
  44. struct jpeg_source_mgr pub; /* public fields */
  45. int src_size;
  46. JOCTET * src_buffer;
  47. JOCTET * buffer; /* start of buffer */
  48. boolean start_of_file; /* have we gotten any data yet? */
  49. } my_source_mgr;
  50. typedef my_source_mgr * my_src_ptr;
  51. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  52. /*
  53. * Initialize source --- called by jpeg_read_header
  54. * before any data is actually read.
  55. */
  56. static void my_init_source (j_decompress_ptr cinfo)
  57. {
  58. my_src_ptr src = (my_src_ptr) cinfo->src;
  59. /* We reset the empty-input-file flag for each image,
  60. * but we don't clear the input buffer.
  61. * This is correct behavior for reading a series of images from one source.
  62. */
  63. src->start_of_file = TRUE;
  64. }
  65. /*
  66. * Fill the input buffer --- called whenever buffer is emptied.
  67. *
  68. * In typical applications, this should read fresh data into the buffer
  69. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  70. * reset the pointer & count to the start of the buffer, and return TRUE
  71. * indicating that the buffer has been reloaded. It is not necessary to
  72. * fill the buffer entirely, only to obtain at least one more byte.
  73. *
  74. * There is no such thing as an EOF return. If the end of the file has been
  75. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  76. * the buffer. In most cases, generating a warning message and inserting a
  77. * fake EOI marker is the best course of action --- this will allow the
  78. * decompressor to output however much of the image is there. However,
  79. * the resulting error message is misleading if the real problem is an empty
  80. * input file, so we handle that case specially.
  81. *
  82. * In applications that need to be able to suspend compression due to input
  83. * not being available yet, a FALSE return indicates that no more data can be
  84. * obtained right now, but more may be forthcoming later. In this situation,
  85. * the decompressor will return to its caller (with an indication of the
  86. * number of scanlines it has read, if any). The application should resume
  87. * decompression after it has loaded more data into the input buffer. Note
  88. * that there are substantial restrictions on the use of suspension --- see
  89. * the documentation.
  90. *
  91. * When suspending, the decompressor will back up to a convenient restart point
  92. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  93. * indicate where the restart point will be if the current call returns FALSE.
  94. * Data beyond this point must be rescanned after resumption, so move it to
  95. * the front of the buffer rather than discarding it.
  96. */
  97. static boolean my_fill_input_buffer (j_decompress_ptr cinfo)
  98. {
  99. my_src_ptr src = (my_src_ptr) cinfo->src;
  100. size_t nbytes;
  101. if (src->src_size > INPUT_BUF_SIZE)
  102. nbytes = INPUT_BUF_SIZE;
  103. else
  104. nbytes = src->src_size;
  105. memcpy (src->buffer, src->src_buffer, nbytes);
  106. src->src_buffer += nbytes;
  107. src->src_size -= nbytes;
  108. if (nbytes <= 0) {
  109. if (src->start_of_file) /* Treat empty input file as fatal error */
  110. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  111. WARNMS(cinfo, JWRN_JPEG_EOF);
  112. /* Insert a fake EOI marker */
  113. src->buffer[0] = (JOCTET) 0xFF;
  114. src->buffer[1] = (JOCTET) JPEG_EOI;
  115. nbytes = 2;
  116. }
  117. src->pub.next_input_byte = src->buffer;
  118. src->pub.bytes_in_buffer = nbytes;
  119. src->start_of_file = FALSE;
  120. return TRUE;
  121. }
  122. /*
  123. * Skip data --- used to skip over a potentially large amount of
  124. * uninteresting data (such as an APPn marker).
  125. *
  126. * Writers of suspendable-input applications must note that skip_input_data
  127. * is not granted the right to give a suspension return. If the skip extends
  128. * beyond the data currently in the buffer, the buffer can be marked empty so
  129. * that the next read will cause a fill_input_buffer call that can suspend.
  130. * Arranging for additional bytes to be discarded before reloading the input
  131. * buffer is the application writer's problem.
  132. */
  133. static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  134. {
  135. my_src_ptr src = (my_src_ptr) cinfo->src;
  136. /* Just a dumb implementation for now. Could use fseek() except
  137. * it doesn't work on pipes. Not clear that being smart is worth
  138. * any trouble anyway --- large skips are infrequent.
  139. */
  140. if (num_bytes > 0) {
  141. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  142. num_bytes -= (long) src->pub.bytes_in_buffer;
  143. (void) my_fill_input_buffer(cinfo);
  144. /* note we assume that fill_input_buffer will never return FALSE,
  145. * so suspension need not be handled.
  146. */
  147. }
  148. src->pub.next_input_byte += (size_t) num_bytes;
  149. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  150. }
  151. }
  152. /*
  153. * An additional method that can be provided by data source modules is the
  154. * resync_to_restart method for error recovery in the presence of RST markers.
  155. * For the moment, this source module just uses the default resync method
  156. * provided by the JPEG library. That method assumes that no backtracking
  157. * is possible.
  158. */
  159. /*
  160. * Terminate source --- called by jpeg_finish_decompress
  161. * after all data has been read. Often a no-op.
  162. *
  163. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  164. * application must deal with any cleanup that should happen even
  165. * for error exit.
  166. */
  167. static void my_term_source (j_decompress_ptr cinfo)
  168. {
  169. /* no work necessary here */
  170. }
  171. /*
  172. * Prepare for input from a stdio stream.
  173. * The caller must have already opened the stream, and is responsible
  174. * for closing it after finishing decompression.
  175. */
  176. static void jpeg_buffer_src (j_decompress_ptr cinfo, void* buffer, int bufsize)
  177. {
  178. my_src_ptr src;
  179. /* The source object and input buffer are made permanent so that a series
  180. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  181. * only before the first one. (If we discarded the buffer at the end of
  182. * one image, we'd likely lose the start of the next one.)
  183. * This makes it unsafe to use this manager and a different source
  184. * manager serially with the same JPEG object. Caveat programmer.
  185. */
  186. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  187. cinfo->src = (struct jpeg_source_mgr *)
  188. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  189. sizeof (my_source_mgr));
  190. src = (my_src_ptr) cinfo->src;
  191. src->buffer = (JOCTET *)
  192. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  193. INPUT_BUF_SIZE * sizeof (JOCTET));
  194. }
  195. src = (my_src_ptr) cinfo->src;
  196. src->pub.init_source = my_init_source;
  197. src->pub.fill_input_buffer = my_fill_input_buffer;
  198. src->pub.skip_input_data = my_skip_input_data;
  199. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  200. src->pub.term_source = my_term_source;
  201. src->src_buffer = (JOCTET *)buffer;
  202. src->src_size = bufsize;
  203. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  204. src->pub.next_input_byte = NULL; /* until buffer loaded */
  205. }
  206. // =============================================================================
  207. static char errormsg[JMSG_LENGTH_MAX];
  208. typedef struct my_jpeg_error_mgr
  209. {
  210. struct jpeg_error_mgr pub; // "public" fields
  211. jmp_buf setjmp_buffer; // for return to caller
  212. } bt_jpeg_error_mgr;
  213. static void my_jpeg_error_exit (j_common_ptr cinfo)
  214. {
  215. my_jpeg_error_mgr* myerr = (bt_jpeg_error_mgr*) cinfo->err;
  216. (*cinfo->err->format_message) (cinfo, errormsg);
  217. longjmp (myerr->setjmp_buffer, 1);
  218. }
  219. // stash a scanline
  220. static void j_putRGBScanline (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
  221. {
  222. int offset = row * widthPix * 4;
  223. int count;
  224. for (count = 0; count < widthPix; count++)
  225. {
  226. unsigned char iRed, iBlu, iGrn;
  227. unsigned char *oRed, *oBlu, *oGrn, *oAlp;
  228. iRed = *(jpegline + count * 3 + 0);
  229. iGrn = *(jpegline + count * 3 + 1);
  230. iBlu = *(jpegline + count * 3 + 2);
  231. oRed = outBuf + offset + count * 4 + 0;
  232. oGrn = outBuf + offset + count * 4 + 1;
  233. oBlu = outBuf + offset + count * 4 + 2;
  234. oAlp = outBuf + offset + count * 4 + 3;
  235. *oRed = iRed;
  236. *oGrn = iGrn;
  237. *oBlu = iBlu;
  238. *oAlp = 255;
  239. }
  240. }
  241. // stash a scanline
  242. static void j_putRGBAScanline (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
  243. {
  244. int offset = row * widthPix * 4;
  245. int count;
  246. for (count = 0; count < widthPix; count++)
  247. {
  248. unsigned char iRed, iBlu, iGrn, iAlp;
  249. unsigned char *oRed, *oBlu, *oGrn, *oAlp;
  250. iRed = *(jpegline + count * 4 + 0);
  251. iGrn = *(jpegline + count * 4 + 1);
  252. iBlu = *(jpegline + count * 4 + 2);
  253. iAlp = *(jpegline + count * 4 + 3);
  254. oRed = outBuf + offset + count * 4 + 0;
  255. oGrn = outBuf + offset + count * 4 + 1;
  256. oBlu = outBuf + offset + count * 4 + 2;
  257. oAlp = outBuf + offset + count * 4 + 3;
  258. *oRed = iRed;
  259. *oGrn = iGrn;
  260. *oBlu = iBlu;
  261. //!\todo fix jpeglib, it leaves alpha channel uninitialised
  262. #if 1
  263. *oAlp = 255;
  264. #else
  265. *oAlp = iAlp;
  266. #endif
  267. }
  268. }
  269. // stash a gray scanline
  270. static void j_putGrayScanlineToRGB (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
  271. {
  272. int offset = row * widthPix * 4;
  273. int count;
  274. for (count = 0; count < widthPix; count++)
  275. {
  276. unsigned char iGray;
  277. unsigned char *oRed, *oBlu, *oGrn, *oAlp;
  278. // get our grayscale value
  279. iGray = *(jpegline + count);
  280. oRed = outBuf + offset + count * 4;
  281. oGrn = outBuf + offset + count * 4 + 1;
  282. oBlu = outBuf + offset + count * 4 + 2;
  283. oAlp = outBuf + offset + count * 4 + 3;
  284. *oRed = iGray;
  285. *oGrn = iGray;
  286. *oBlu = iGray;
  287. *oAlp = 255;
  288. }
  289. }
  290. static Image* LoadJPGBuff_(const void *src_buffer, int src_size)
  291. {
  292. struct jpeg_decompress_struct cinfo;
  293. struct my_jpeg_error_mgr jerr;
  294. cinfo.err = jpeg_std_error (&jerr.pub);
  295. jerr.pub.error_exit = my_jpeg_error_exit;
  296. if (setjmp (jerr.setjmp_buffer)) //< TODO: use c++ exceptions instead of setjmp/longjmp to handle errors
  297. {
  298. globalErrorStream() << "WARNING: JPEG library error: " << errormsg << "\n";
  299. jpeg_destroy_decompress (&cinfo);
  300. return 0;
  301. }
  302. jpeg_create_decompress (&cinfo);
  303. jpeg_buffer_src (&cinfo, const_cast<void*>(src_buffer), src_size);
  304. jpeg_read_header (&cinfo, TRUE);
  305. jpeg_start_decompress (&cinfo);
  306. int row_stride = cinfo.output_width * cinfo.output_components;
  307. RGBAImage* image = new RGBAImage(cinfo.output_width, cinfo.output_height);
  308. JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
  309. while (cinfo.output_scanline < cinfo.output_height)
  310. {
  311. jpeg_read_scanlines (&cinfo, buffer, 1);
  312. if (cinfo.out_color_components == 4)
  313. j_putRGBAScanline (buffer[0], cinfo.output_width, image->getRGBAPixels(), cinfo.output_scanline-1);
  314. else if (cinfo.out_color_components == 3)
  315. j_putRGBScanline (buffer[0], cinfo.output_width, image->getRGBAPixels(), cinfo.output_scanline-1);
  316. else if (cinfo.out_color_components == 1)
  317. j_putGrayScanlineToRGB (buffer[0], cinfo.output_width, image->getRGBAPixels(), cinfo.output_scanline-1);
  318. }
  319. jpeg_finish_decompress (&cinfo);
  320. jpeg_destroy_decompress (&cinfo);
  321. return image;
  322. }
  323. Image* LoadJPG(ArchiveFile& file)
  324. {
  325. ScopedArchiveBuffer buffer(file);
  326. return LoadJPGBuff_(buffer.buffer, static_cast<int>(buffer.length));
  327. }