/src/FreeImage/Source/FreeImage/PluginPCX.cpp

https://bitbucket.org/cabalistic/ogredeps/ · C++ · 659 lines · 338 code · 123 blank · 198 comment · 86 complexity · db57a5407fa3bf7c59b2a5aa15cf386c MD5 · raw file

  1. // ==========================================================
  2. // PCX Loader
  3. //
  4. // Design and implementation by
  5. // - Floris van den Berg (flvdberg@wxs.nl)
  6. // - Jani Kajala (janik@remedy.fi)
  7. // - Markus Loibl (markus.loibl@epost.de)
  8. // - Hervé Drolon (drolon@infonie.fr)
  9. // - Juergen Riecker (j.riecker@gmx.de)
  10. //
  11. // This file is part of FreeImage 3
  12. //
  13. // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
  14. // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
  15. // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
  16. // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
  17. // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
  18. // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
  19. // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
  20. // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  21. // THIS DISCLAIMER.
  22. //
  23. // Use at your own risk!
  24. // ==========================================================
  25. #include "FreeImage.h"
  26. #include "Utilities.h"
  27. // ----------------------------------------------------------
  28. // Constants + headers
  29. // ----------------------------------------------------------
  30. #define IO_BUF_SIZE 2048
  31. // ----------------------------------------------------------
  32. #ifdef _WIN32
  33. #pragma pack(push, 1)
  34. #else
  35. #pragma pack(1)
  36. #endif
  37. typedef struct tagPCXHEADER {
  38. BYTE manufacturer; // Magic number (0x0A = ZSoft Z)
  39. BYTE version; // Version 0 == 2.5
  40. // 2 == 2.8 with palette info
  41. // 3 == 2.8 without palette info
  42. // 5 == 3.0 with palette info
  43. BYTE encoding; // Encoding: 0 = uncompressed, 1 = PCX rle compressed
  44. BYTE bpp; // Bits per pixel per plane (only 1 or 8)
  45. WORD window[4]; // left, upper, right,lower pixel coord.
  46. WORD hdpi; // Horizontal resolution
  47. WORD vdpi; // Vertical resolution
  48. BYTE color_map[48]; // Colormap for 16-color images
  49. BYTE reserved;
  50. BYTE planes; // Number of planes (1, 3 or 4)
  51. WORD bytes_per_line; // Bytes per row (always even)
  52. WORD palette_info; // Palette information (1 = color or b&w; 2 = gray scale)
  53. WORD h_screen_size;
  54. WORD v_screen_size;
  55. BYTE filler[54]; // Reserved filler
  56. } PCXHEADER;
  57. #ifdef _WIN32
  58. #pragma pack(pop)
  59. #else
  60. #pragma pack()
  61. #endif
  62. // ==========================================================
  63. // Internal functions
  64. // ==========================================================
  65. static BOOL
  66. pcx_validate(FreeImageIO *io, fi_handle handle) {
  67. BYTE pcx_signature = 0x0A;
  68. BYTE signature[4] = { 0, 0, 0, 0 };
  69. if(io->read_proc(&signature, 1, 4, handle) != 4) {
  70. return FALSE;
  71. }
  72. // magic number (0x0A = ZSoft Z)
  73. if(signature[0] == pcx_signature) {
  74. // version
  75. if(signature[1] <= 5) {
  76. // encoding
  77. if((signature[2] == 0) || (signature[2] == 1)) {
  78. // bits per pixel per plane
  79. if((signature[3] == 1) || (signature[3] == 8)) {
  80. return TRUE;
  81. }
  82. }
  83. }
  84. }
  85. return FALSE;
  86. }
  87. static unsigned
  88. readline(FreeImageIO &io, fi_handle handle, BYTE *buffer, unsigned length, BOOL rle, BYTE * ReadBuf, int * ReadPos) {
  89. // -----------------------------------------------------------//
  90. // Read either run-length encoded or normal image data //
  91. // //
  92. // THIS IS HOW RUNTIME LENGTH ENCODING WORKS IN PCX: //
  93. // //
  94. // 1) If the upper 2 bits of a byte are set, //
  95. // the lower 6 bits specify the count for the next byte //
  96. // //
  97. // 2) If the upper 2 bits of the byte are clear, //
  98. // the byte is actual data with a count of 1 //
  99. // //
  100. // Note that a scanline always has an even number of bytes //
  101. // -------------------------------------------------------------
  102. BYTE count = 0, value = 0;
  103. unsigned written = 0;
  104. if (rle) {
  105. // run-length encoded read
  106. while (length--) {
  107. if (count == 0) {
  108. if (*ReadPos >= IO_BUF_SIZE - 1 ) {
  109. if (*ReadPos == IO_BUF_SIZE - 1) {
  110. // we still have one BYTE, copy it to the start pos
  111. *ReadBuf = ReadBuf[IO_BUF_SIZE - 1];
  112. io.read_proc(ReadBuf + 1, 1, IO_BUF_SIZE - 1, handle);
  113. } else {
  114. // read the complete buffer
  115. io.read_proc(ReadBuf, 1, IO_BUF_SIZE, handle);
  116. }
  117. *ReadPos = 0;
  118. }
  119. value = *(ReadBuf + (*ReadPos)++);
  120. if ((value & 0xC0) == 0xC0) {
  121. count = value & 0x3F;
  122. value = *(ReadBuf + (*ReadPos)++);
  123. } else {
  124. count = 1;
  125. }
  126. }
  127. count--;
  128. *(buffer + written++) = value;
  129. }
  130. } else {
  131. // normal read
  132. written = io.read_proc(buffer, length, 1, handle);
  133. }
  134. return written;
  135. }
  136. #ifdef FREEIMAGE_BIGENDIAN
  137. static void
  138. SwapHeader(PCXHEADER *header) {
  139. SwapShort(&header->window[0]);
  140. SwapShort(&header->window[1]);
  141. SwapShort(&header->window[2]);
  142. SwapShort(&header->window[3]);
  143. SwapShort(&header->hdpi);
  144. SwapShort(&header->vdpi);
  145. SwapShort(&header->bytes_per_line);
  146. SwapShort(&header->palette_info);
  147. SwapShort(&header->h_screen_size);
  148. SwapShort(&header->v_screen_size);
  149. }
  150. #endif
  151. // ==========================================================
  152. // Plugin Interface
  153. // ==========================================================
  154. static int s_format_id;
  155. // ==========================================================
  156. // Plugin Implementation
  157. // ==========================================================
  158. /*!
  159. Returns the format string for the plugin. Each plugin,
  160. both internal in the DLL and external in a .fip file, must have
  161. a unique format string to be addressable.
  162. */
  163. static const char * DLL_CALLCONV
  164. Format() {
  165. return "PCX";
  166. }
  167. /*!
  168. Returns a description string for the plugin. Though a
  169. description is not necessary per-se,
  170. it is advised to return an unique string in order to tell the
  171. user what type of bitmaps this plugin will read and/or write.
  172. */
  173. static const char * DLL_CALLCONV
  174. Description() {
  175. return "Zsoft Paintbrush";
  176. }
  177. /*!
  178. Returns a comma separated list of file
  179. extensions indicating what files this plugin can open. The
  180. list, being used by FreeImage_GetFIFFromFilename, is usually
  181. used as a last resort in finding the type of the bitmap we
  182. are dealing with. Best is to check the first few bytes on
  183. the low-level bits level first and compare them with a known
  184. signature . If this fails, FreeImage_GetFIFFromFilename can be
  185. used.
  186. */
  187. static const char * DLL_CALLCONV
  188. Extension() {
  189. return "pcx";
  190. }
  191. /*!
  192. Returns an (optional) regular expression to help
  193. software identifying a bitmap type. The
  194. expression can be applied to the first few bytes (header) of
  195. the bitmap. FreeImage is not capable of processing regular expression itself,
  196. but FreeImageQt, the FreeImage Trolltech support library, can. If RegExpr
  197. returns NULL, FreeImageQt will automatically bypass Trolltech's regular
  198. expression support and use its internal functions to find the bitmap type.
  199. */
  200. static const char * DLL_CALLCONV
  201. RegExpr() {
  202. return NULL;
  203. }
  204. static const char * DLL_CALLCONV
  205. MimeType() {
  206. return "image/x-pcx";
  207. }
  208. /*!
  209. Validates a bitmap by reading the first few bytes
  210. and comparing them with a known bitmap signature.
  211. TRUE is returned if the bytes match the signature, FALSE otherwise.
  212. The Validate function is used by using FreeImage_GetFileType.
  213. Note: a plugin can safely read data any data from the bitmap without seeking back
  214. to the original entry point; the entry point is stored prior to calling this
  215. function and restored after.
  216. Note: because of FreeImage's io redirection support, the header for the bitmap
  217. must be on the start of the bitmap or at least on a known part in the bitmap. It is
  218. forbidden to seek to the end of the bitmap or to a point relative to the end of a bitmap,
  219. because the end of the bitmap is not always known.
  220. */
  221. static BOOL DLL_CALLCONV
  222. Validate(FreeImageIO *io, fi_handle handle) {
  223. return pcx_validate(io, handle);
  224. }
  225. /*!
  226. This function is used to 'ask' the plugin if it can write
  227. a bitmap in a certain bitdepth. Different bitmap types have different
  228. capabilities, for example not all formats allow writing in palettized mode.
  229. This function is there provide an uniform interface to the plugin's
  230. capabilities. SupportsExportDepth returns TRUE if the plugin support writing
  231. in the asked bitdepth, or FALSE if it doesn't. The function also
  232. returns FALSE if bitmap saving is not supported by the plugin at all.
  233. */
  234. static BOOL DLL_CALLCONV
  235. SupportsExportDepth(int depth) {
  236. return FALSE;
  237. }
  238. static BOOL DLL_CALLCONV
  239. SupportsExportType(FREE_IMAGE_TYPE type) {
  240. return FALSE;
  241. }
  242. static BOOL DLL_CALLCONV
  243. SupportsNoPixels() {
  244. return TRUE;
  245. }
  246. // ----------------------------------------------------------
  247. /*!
  248. Loads a bitmap into memory. On entry it is assumed that
  249. the bitmap to be loaded is of the correct type. If the bitmap
  250. is of an incorrect type, the plugin might not gracefully fail but
  251. crash or enter an endless loop. It is also assumed that all
  252. the bitmap data is available at one time. If the bitmap is not complete,
  253. for example because it is being downloaded while loaded, the plugin
  254. might also not gracefully fail.
  255. The Load function has the following parameters:
  256. The first parameter (FreeImageIO *io) is a structure providing
  257. function pointers in order to make use of FreeImage's IO redirection. Using
  258. FreeImage's file i/o functions instead of standard ones it is garantueed
  259. that all bitmap types, both current and future ones, can be loaded from
  260. memory, file cabinets, the internet and more. The second parameter (fi_handle handle)
  261. is a companion of FreeImageIO and can be best compared with the standard FILE* type,
  262. in a generalized form.
  263. The third parameter (int page) indicates wether we will be loading a certain page
  264. in the bitmap or if we will load the default one. This parameter is only used if
  265. the plugin supports multi-paged bitmaps, e.g. cabinet bitmaps that contain a series
  266. of images or pages. If the plugin does support multi-paging, the page parameter
  267. can contain either a number higher or equal to 0 to load a certain page, or -1 to
  268. load the default page. If the plugin does not support multi-paging,
  269. the page parameter is always -1.
  270. The fourth parameter (int flags) manipulates the load function to load a bitmap
  271. in a certain way. Every plugin has a different flag parameter with different meanings.
  272. The last parameter (void *data) can contain a special data block used when
  273. the file is read multi-paged. Because not every plugin supports multi-paging
  274. not every plugin will use the data parameter and it will be set to NULL.However,
  275. when the plugin does support multi-paging the parameter contains a pointer to a
  276. block of data allocated by the Open function.
  277. */
  278. static FIBITMAP * DLL_CALLCONV
  279. Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
  280. FIBITMAP *dib = NULL;
  281. BYTE *bits; // Pointer to dib data
  282. RGBQUAD *pal; // Pointer to dib palette
  283. BYTE *line = NULL; // PCX raster line
  284. BYTE *ReadBuf = NULL; // buffer;
  285. BOOL bIsRLE; // True if the file is run-length encoded
  286. if(!handle) {
  287. return NULL;
  288. }
  289. BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;
  290. try {
  291. // check PCX identifier
  292. long start_pos = io->tell_proc(handle);
  293. BOOL validated = pcx_validate(io, handle);
  294. io->seek_proc(handle, start_pos, SEEK_SET);
  295. if(!validated) {
  296. throw FI_MSG_ERROR_MAGIC_NUMBER;
  297. }
  298. // process the header
  299. PCXHEADER header;
  300. if(io->read_proc(&header, sizeof(PCXHEADER), 1, handle) != 1) {
  301. throw FI_MSG_ERROR_PARSING;
  302. }
  303. #ifdef FREEIMAGE_BIGENDIAN
  304. SwapHeader(&header);
  305. #endif
  306. // allocate a new DIB
  307. unsigned width = header.window[2] - header.window[0] + 1;
  308. unsigned height = header.window[3] - header.window[1] + 1;
  309. unsigned bitcount = header.bpp * header.planes;
  310. if (bitcount == 24) {
  311. dib = FreeImage_AllocateHeader(header_only, width, height, bitcount, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
  312. } else {
  313. dib = FreeImage_AllocateHeader(header_only, width, height, bitcount);
  314. }
  315. // if the dib couldn't be allocated, throw an error
  316. if (!dib) {
  317. throw FI_MSG_ERROR_DIB_MEMORY;
  318. }
  319. // metrics handling code
  320. FreeImage_SetDotsPerMeterX(dib, (unsigned) (((float)header.hdpi) / 0.0254000 + 0.5));
  321. FreeImage_SetDotsPerMeterY(dib, (unsigned) (((float)header.vdpi) / 0.0254000 + 0.5));
  322. // Set up the palette if needed
  323. // ----------------------------
  324. switch(bitcount) {
  325. case 1:
  326. {
  327. pal = FreeImage_GetPalette(dib);
  328. pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 0;
  329. pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255;
  330. break;
  331. }
  332. case 4:
  333. {
  334. pal = FreeImage_GetPalette(dib);
  335. BYTE *pColormap = &header.color_map[0];
  336. for (int i = 0; i < 16; i++) {
  337. pal[i].rgbRed = pColormap[0];
  338. pal[i].rgbGreen = pColormap[1];
  339. pal[i].rgbBlue = pColormap[2];
  340. pColormap += 3;
  341. }
  342. break;
  343. }
  344. case 8:
  345. {
  346. BYTE palette_id;
  347. io->seek_proc(handle, -769L, SEEK_END);
  348. io->read_proc(&palette_id, 1, 1, handle);
  349. if (palette_id == 0x0C) {
  350. BYTE *cmap = (BYTE*)malloc(768 * sizeof(BYTE));
  351. io->read_proc(cmap, 768, 1, handle);
  352. pal = FreeImage_GetPalette(dib);
  353. BYTE *pColormap = &cmap[0];
  354. for(int i = 0; i < 256; i++) {
  355. pal[i].rgbRed = pColormap[0];
  356. pal[i].rgbGreen = pColormap[1];
  357. pal[i].rgbBlue = pColormap[2];
  358. pColormap += 3;
  359. }
  360. free(cmap);
  361. }
  362. // wrong palette ID, perhaps a gray scale is needed ?
  363. else if (header.palette_info == 2) {
  364. pal = FreeImage_GetPalette(dib);
  365. for(int i = 0; i < 256; i++) {
  366. pal[i].rgbRed = (BYTE)i;
  367. pal[i].rgbGreen = (BYTE)i;
  368. pal[i].rgbBlue = (BYTE)i;
  369. }
  370. }
  371. io->seek_proc(handle, (long)sizeof(PCXHEADER), SEEK_SET);
  372. }
  373. break;
  374. }
  375. if(header_only) {
  376. // header only mode
  377. return dib;
  378. }
  379. // calculate the line length for the PCX and the DIB
  380. // length of raster line in bytes
  381. unsigned linelength = header.bytes_per_line * header.planes;
  382. // length of DIB line (rounded to DWORD) in bytes
  383. unsigned pitch = FreeImage_GetPitch(dib);
  384. // run-length encoding ?
  385. bIsRLE = (header.encoding == 1) ? TRUE : FALSE;
  386. // load image data
  387. // ---------------
  388. line = (BYTE*)malloc(linelength * sizeof(BYTE));
  389. if(!line) throw FI_MSG_ERROR_MEMORY;
  390. ReadBuf = (BYTE*)malloc(IO_BUF_SIZE * sizeof(BYTE));
  391. if(!ReadBuf) throw FI_MSG_ERROR_MEMORY;
  392. bits = FreeImage_GetScanLine(dib, height - 1);
  393. int ReadPos = IO_BUF_SIZE;
  394. if ((header.planes == 1) && ((header.bpp == 1) || (header.bpp == 8))) {
  395. BYTE skip;
  396. unsigned written;
  397. for (unsigned y = 0; y < height; y++) {
  398. written = readline(*io, handle, bits, linelength, bIsRLE, ReadBuf, &ReadPos);
  399. // skip trailing garbage at the end of the scanline
  400. for (unsigned count = written; count < linelength; count++) {
  401. if (ReadPos < IO_BUF_SIZE) {
  402. ReadPos++;
  403. } else {
  404. io->read_proc(&skip, sizeof(BYTE), 1, handle);
  405. }
  406. }
  407. bits -= pitch;
  408. }
  409. } else if ((header.planes == 4) && (header.bpp == 1)) {
  410. BYTE bit, mask, skip;
  411. unsigned index;
  412. BYTE *buffer;
  413. unsigned x, y, written;
  414. buffer = (BYTE*)malloc(width * sizeof(BYTE));
  415. if(!buffer) throw FI_MSG_ERROR_MEMORY;
  416. for (y = 0; y < height; y++) {
  417. written = readline(*io, handle, line, linelength, bIsRLE, ReadBuf, &ReadPos);
  418. // build a nibble using the 4 planes
  419. memset(buffer, 0, width * sizeof(BYTE));
  420. for(int plane = 0; plane < 4; plane++) {
  421. bit = (BYTE)(1 << plane);
  422. for (x = 0; x < width; x++) {
  423. index = (unsigned)((x / 8) + plane * header.bytes_per_line);
  424. mask = (BYTE)(0x80 >> (x & 0x07));
  425. buffer[x] |= (line[index] & mask) ? bit : 0;
  426. }
  427. }
  428. // then write the DIB row
  429. for (x = 0; x < width / 2; x++) {
  430. bits[x] = (buffer[2*x] << 4) | buffer[2*x+1];
  431. }
  432. // skip trailing garbage at the end of the scanline
  433. for (unsigned count = written; count < linelength; count++) {
  434. if (ReadPos < IO_BUF_SIZE) {
  435. ReadPos++;
  436. } else {
  437. io->read_proc(&skip, sizeof(BYTE), 1, handle);
  438. }
  439. }
  440. bits -= pitch;
  441. }
  442. free(buffer);
  443. } else if((header.planes == 3) && (header.bpp == 8)) {
  444. BYTE *pline;
  445. for (unsigned y = 0; y < height; y++) {
  446. readline(*io, handle, line, linelength, bIsRLE, ReadBuf, &ReadPos);
  447. // convert the plane stream to BGR (RRRRGGGGBBBB -> BGRBGRBGRBGR)
  448. // well, now with the FI_RGBA_x macros, on BIGENDIAN we convert to RGB
  449. pline = line;
  450. unsigned x;
  451. for (x = 0; x < width; x++) {
  452. bits[x * 3 + FI_RGBA_RED] = pline[x];
  453. }
  454. pline += header.bytes_per_line;
  455. for (x = 0; x < width; x++) {
  456. bits[x * 3 + FI_RGBA_GREEN] = pline[x];
  457. }
  458. pline += header.bytes_per_line;
  459. for (x = 0; x < width; x++) {
  460. bits[x * 3 + FI_RGBA_BLUE] = pline[x];
  461. }
  462. pline += header.bytes_per_line;
  463. bits -= pitch;
  464. }
  465. } else {
  466. throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
  467. }
  468. free(line);
  469. free(ReadBuf);
  470. return dib;
  471. } catch (const char *text) {
  472. // free allocated memory
  473. if (dib != NULL) {
  474. FreeImage_Unload(dib);
  475. }
  476. if (line != NULL) {
  477. free(line);
  478. }
  479. if (ReadBuf != NULL) {
  480. free(ReadBuf);
  481. }
  482. FreeImage_OutputMessageProc(s_format_id, text);
  483. }
  484. return NULL;
  485. }
  486. // ==========================================================
  487. // Init
  488. // ==========================================================
  489. /*!
  490. Initialises the plugin. The first parameter (Plugin *plugin)
  491. contains a pointer to a pre-allocated Plugin structure
  492. wherein pointers to the available plugin functions
  493. has to be stored. The second parameter (int format_id) is an identification
  494. number that the plugin may use to show plugin specific warning messages
  495. or other information to the user. The plugin number
  496. is generated by FreeImage and can differ everytime the plugin is
  497. initialised.
  498. If you want to create your own plugin you have to take some
  499. rules into account. Plugin functions have to be compiled
  500. __stdcall using the multithreaded c runtime libraries. Throwing
  501. exceptions in plugin functions is allowed, as long as those exceptions
  502. are being caught inside the same plugin. It is forbidden for a plugin
  503. function to directly call FreeImage functions or to allocate memory
  504. and pass it to the main DLL. Exception to this rule is the special file data
  505. block that may be allocated the Open function. Allocating a FIBITMAP inside a
  506. plugin can be using the function allocate_proc in the FreeImage structure,
  507. which will allocate the memory using the DLL's c runtime library.
  508. */
  509. void DLL_CALLCONV
  510. InitPCX(Plugin *plugin, int format_id) {
  511. s_format_id = format_id;
  512. plugin->format_proc = Format;
  513. plugin->description_proc = Description;
  514. plugin->extension_proc = Extension;
  515. plugin->regexpr_proc = RegExpr;
  516. plugin->open_proc = NULL;
  517. plugin->close_proc = NULL;
  518. plugin->pagecount_proc = NULL;
  519. plugin->pagecapability_proc = NULL;
  520. plugin->load_proc = Load;
  521. plugin->save_proc = NULL;
  522. plugin->validate_proc = Validate;
  523. plugin->mime_proc = MimeType;
  524. plugin->supports_export_bpp_proc = SupportsExportDepth;
  525. plugin->supports_export_type_proc = SupportsExportType;
  526. plugin->supports_icc_profiles_proc = NULL;
  527. plugin->supports_no_pixels_proc = SupportsNoPixels;
  528. }