/src/FreeImage/Source/FreeImage/PluginRAW.cpp

https://bitbucket.org/cabalistic/ogredeps/ · C++ · 542 lines · 367 code · 63 blank · 112 comment · 80 complexity · e24cd14a4c012a281abae53e16a24505 MD5 · raw file

  1. // ==========================================================
  2. // RAW camera image loader
  3. //
  4. // Design and implementation by
  5. // - Hervé Drolon (drolon@infonie.fr)
  6. //
  7. // This file is part of FreeImage 3
  8. //
  9. // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
  10. // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
  11. // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
  12. // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
  13. // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
  14. // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
  15. // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
  16. // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  17. // THIS DISCLAIMER.
  18. //
  19. // Use at your own risk!
  20. // ==========================================================
  21. #include "../LibRawLite/libraw/libraw.h"
  22. #include "FreeImage.h"
  23. #include "Utilities.h"
  24. #include "../Metadata/FreeImageTag.h"
  25. // ==========================================================
  26. // Plugin Interface
  27. // ==========================================================
  28. static int s_format_id;
  29. // ==========================================================
  30. // Internal functions
  31. // ==========================================================
  32. // ----------------------------------------------------------
  33. // FreeImage datastream wrapper
  34. // ----------------------------------------------------------
  35. class LibRaw_freeimage_datastream : public LibRaw_abstract_datastream {
  36. private:
  37. FreeImageIO *_io;
  38. fi_handle _handle;
  39. long _eof;
  40. public:
  41. LibRaw_freeimage_datastream(FreeImageIO *io, fi_handle handle) : _io(io), _handle(handle) {
  42. long start_pos = io->tell_proc(handle);
  43. io->seek_proc(handle, 0, SEEK_END);
  44. _eof = io->tell_proc(handle);
  45. io->seek_proc(handle, start_pos, SEEK_SET);
  46. }
  47. ~LibRaw_freeimage_datastream() {
  48. }
  49. virtual void * make_jas_stream() {
  50. return NULL;
  51. }
  52. virtual int valid() {
  53. return (_io && _handle);
  54. }
  55. virtual int read(void *buffer, size_t size, size_t count) {
  56. if(substream) return substream->read(buffer, size, count);
  57. return _io->read_proc(buffer, (unsigned)size, (unsigned)count, _handle);
  58. }
  59. virtual int eof() {
  60. if(substream) return substream->eof();
  61. return (_io->tell_proc(_handle) >= _eof);
  62. }
  63. virtual int seek(INT64 offset, int origin) {
  64. if(substream) return substream->seek(offset, origin);
  65. return _io->seek_proc(_handle, (long)offset, origin);
  66. }
  67. virtual INT64 tell() {
  68. if(substream) return substream->tell();
  69. return _io->tell_proc(_handle);
  70. }
  71. virtual int get_char() {
  72. int c = 0;
  73. if(substream) return substream->get_char();
  74. if(!_io->read_proc(&c, 1, 1, _handle)) return -1;
  75. return c;
  76. }
  77. virtual char* gets(char *buffer, int length) {
  78. if (substream) return substream->gets(buffer, length);
  79. memset(buffer, 0, length);
  80. for(int i = 0; i < length; i++) {
  81. if(!_io->read_proc(&buffer[i], 1, 1, _handle))
  82. return NULL;
  83. if(buffer[i] == 0x0A)
  84. break;
  85. }
  86. return buffer;
  87. }
  88. virtual int scanf_one(const char *fmt, void* val) {
  89. std::string buffer;
  90. char element = 0;
  91. bool bDone = false;
  92. if(substream) return substream->scanf_one(fmt,val);
  93. do {
  94. if(_io->read_proc(&element, 1, 1, _handle) == 1) {
  95. switch(element) {
  96. case '0':
  97. case '\n':
  98. case ' ':
  99. case '\t':
  100. bDone = true;
  101. break;
  102. default:
  103. break;
  104. }
  105. buffer.append(&element, 1);
  106. } else {
  107. return 0;
  108. }
  109. } while(!bDone);
  110. return sscanf(buffer.c_str(), fmt, val);
  111. }
  112. };
  113. // ----------------------------------------------------------
  114. /**
  115. Convert a processed raw data array to a FIBITMAP
  116. @param image Processed raw image
  117. @return Returns the converted dib if successfull, returns NULL otherwise
  118. */
  119. static FIBITMAP *
  120. libraw_ConvertToDib(libraw_processed_image_t *image) {
  121. FIBITMAP *dib = NULL;
  122. try {
  123. unsigned width = image->width;
  124. unsigned height = image->height;
  125. unsigned bpp = image->bits;
  126. if(bpp == 16) {
  127. // allocate output dib
  128. dib = FreeImage_AllocateT(FIT_RGB16, width, height);
  129. if(!dib) {
  130. throw FI_MSG_ERROR_DIB_MEMORY;
  131. }
  132. // write data
  133. WORD *raw_data = (WORD*)image->data;
  134. for(unsigned y = 0; y < height; y++) {
  135. FIRGB16 *output = (FIRGB16*)FreeImage_GetScanLine(dib, height - 1 - y);
  136. for(unsigned x = 0; x < width; x++) {
  137. output[x].red = raw_data[0];
  138. output[x].green = raw_data[1];
  139. output[x].blue = raw_data[2];
  140. raw_data += 3;
  141. }
  142. }
  143. } else if(bpp == 8) {
  144. // allocate output dib
  145. dib = FreeImage_AllocateT(FIT_BITMAP, width, height, 24);
  146. if(!dib) {
  147. throw FI_MSG_ERROR_DIB_MEMORY;
  148. }
  149. // write data
  150. BYTE *raw_data = (BYTE*)image->data;
  151. for(unsigned y = 0; y < height; y++) {
  152. RGBTRIPLE *output = (RGBTRIPLE*)FreeImage_GetScanLine(dib, height - 1 - y);
  153. for(unsigned x = 0; x < width; x++) {
  154. output[x].rgbtRed = raw_data[0];
  155. output[x].rgbtGreen = raw_data[1];
  156. output[x].rgbtBlue = raw_data[2];
  157. raw_data += 3;
  158. }
  159. }
  160. }
  161. } catch(const char *text) {
  162. FreeImage_OutputMessageProc(s_format_id, text);
  163. }
  164. return dib;
  165. }
  166. /**
  167. Get the embedded JPEG preview image from RAW picture with included Exif Data.
  168. @param RawProcessor Libraw handle
  169. @param flags JPEG load flags
  170. @return Returns the loaded dib if successfull, returns NULL otherwise
  171. */
  172. static FIBITMAP *
  173. libraw_LoadEmbeddedPreview(LibRaw& RawProcessor, int flags) {
  174. FIBITMAP *dib = NULL;
  175. libraw_processed_image_t *thumb_image = NULL;
  176. try {
  177. // unpack data
  178. if(RawProcessor.unpack_thumb() != LIBRAW_SUCCESS) {
  179. // run silently "LibRaw : failed to run unpack_thumb"
  180. return NULL;
  181. }
  182. // retrieve thumb image
  183. int error_code = 0;
  184. thumb_image = RawProcessor.dcraw_make_mem_thumb(&error_code);
  185. if(thumb_image) {
  186. if(thumb_image->type != LIBRAW_IMAGE_BITMAP) {
  187. // attach the binary data to a memory stream
  188. FIMEMORY *hmem = FreeImage_OpenMemory((BYTE*)thumb_image->data, (DWORD)thumb_image->data_size);
  189. // get the file type
  190. FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0);
  191. if(fif == FIF_JPEG) {
  192. // rotate according to Exif orientation
  193. flags |= JPEG_EXIFROTATE;
  194. }
  195. // load an image from the memory stream
  196. dib = FreeImage_LoadFromMemory(fif, hmem, flags);
  197. // close the stream
  198. FreeImage_CloseMemory(hmem);
  199. } else {
  200. // convert processed data to output dib
  201. dib = libraw_ConvertToDib(thumb_image);
  202. }
  203. } else {
  204. throw "LibRaw : failed to run dcraw_make_mem_thumb";
  205. }
  206. // clean-up and return
  207. RawProcessor.dcraw_clear_mem(thumb_image);
  208. return dib;
  209. } catch(const char *text) {
  210. // clean-up and return
  211. if(thumb_image) {
  212. RawProcessor.dcraw_clear_mem(thumb_image);
  213. }
  214. if(text != NULL) {
  215. FreeImage_OutputMessageProc(s_format_id, text);
  216. }
  217. }
  218. return NULL;
  219. }
  220. /**
  221. Load raw data and convert to FIBITMAP
  222. @param RawProcessor Libraw handle
  223. @param bitspersample Output bitdepth (8- or 16-bit)
  224. @return Returns the loaded dib if successfull, returns NULL otherwise
  225. */
  226. static FIBITMAP *
  227. libraw_LoadRawData(LibRaw& RawProcessor, int bitspersample) {
  228. FIBITMAP *dib = NULL;
  229. libraw_processed_image_t *processed_image = NULL;
  230. try {
  231. // set decoding parameters
  232. // -----------------------
  233. // (-6) 16-bit or 8-bit
  234. RawProcessor.imgdata.params.output_bps = bitspersample;
  235. // (-g power toe_slope)
  236. if(bitspersample == 16) {
  237. // set -g 1 1 for linear curve
  238. RawProcessor.imgdata.params.gamm[0] = 1;
  239. RawProcessor.imgdata.params.gamm[1] = 1;
  240. } else if(bitspersample == 8) {
  241. // by default settings for rec. BT.709 are used: power 2.222 (i.e. gamm[0]=1/2.222) and slope 4.5
  242. RawProcessor.imgdata.params.gamm[0] = 1/2.222;
  243. RawProcessor.imgdata.params.gamm[1] = 4.5;
  244. }
  245. // (-W) Don't use automatic increase of brightness by histogram
  246. RawProcessor.imgdata.params.no_auto_bright = 1;
  247. // (-a) Use automatic white balance obtained after averaging over the entire image
  248. RawProcessor.imgdata.params.use_auto_wb = 1;
  249. // (-q 3) Adaptive homogeneity-directed demosaicing algorithm (AHD)
  250. RawProcessor.imgdata.params.user_qual = 3;
  251. // -----------------------
  252. // unpack data
  253. if(RawProcessor.unpack() != LIBRAW_SUCCESS) {
  254. throw "LibRaw : failed to unpack data";
  255. }
  256. // process data (... most consuming task ...)
  257. if(RawProcessor.dcraw_process() != LIBRAW_SUCCESS) {
  258. throw "LibRaw : failed to process data";
  259. }
  260. // retrieve processed image
  261. int error_code = 0;
  262. processed_image = RawProcessor.dcraw_make_mem_image(&error_code);
  263. if(processed_image) {
  264. // type SHOULD be LIBRAW_IMAGE_BITMAP, but we'll check
  265. if(processed_image->type != LIBRAW_IMAGE_BITMAP) {
  266. throw "invalid image type";
  267. }
  268. // only 3-color images supported...
  269. if(processed_image->colors != 3) {
  270. throw "only 3-color images supported";
  271. }
  272. } else {
  273. throw "LibRaw : failed to run dcraw_make_mem_image";
  274. }
  275. // convert processed data to output dib
  276. dib = libraw_ConvertToDib(processed_image);
  277. // clean-up and return
  278. RawProcessor.dcraw_clear_mem(processed_image);
  279. return dib;
  280. } catch(const char *text) {
  281. // clean-up and return
  282. if(processed_image) {
  283. RawProcessor.dcraw_clear_mem(processed_image);
  284. }
  285. FreeImage_OutputMessageProc(s_format_id, text);
  286. }
  287. return NULL;
  288. }
  289. // ==========================================================
  290. // Plugin Implementation
  291. // ==========================================================
  292. static const char * DLL_CALLCONV
  293. Format() {
  294. return "RAW";
  295. }
  296. static const char * DLL_CALLCONV
  297. Description() {
  298. return "RAW camera image";
  299. }
  300. static const char * DLL_CALLCONV
  301. Extension() {
  302. /**
  303. Below are known RAW file extensions that you can check using FreeImage_GetFIFFromFormat.
  304. If a file extension is not listed, that doesn't mean that you cannot load it.
  305. Using FreeImage_GetFileType is the best way to know if a RAW file format is supported.
  306. */
  307. static const char *raw_extensions =
  308. "3fr," // Hasselblad Digital Camera Raw Image Format.
  309. "arw," // Sony Digital Camera Raw Image Format for Alpha devices.
  310. "bay," // Casio Digital Camera Raw File Format.
  311. "bmq," // NuCore Raw Image File.
  312. "cap," // Phase One Digital Camera Raw Image Format.
  313. "cine," // Phantom Software Raw Image File.
  314. "cr2," // Canon Digital Camera RAW Image Format version 2.0. These images are based on the TIFF image standard.
  315. "crw," // Canon Digital Camera RAW Image Format version 1.0.
  316. "cs1," // Sinar Capture Shop Raw Image File.
  317. "dc2," // Kodak DC25 Digital Camera File.
  318. "dcr," // Kodak Digital Camera Raw Image Format for these models: Kodak DSC Pro SLR/c, Kodak DSC Pro SLR/n, Kodak DSC Pro 14N, Kodak DSC PRO 14nx.
  319. "drf," // Kodak Digital Camera Raw Image Format.
  320. "dsc," // Kodak Digital Camera Raw Image Format.
  321. "dng," // Adobe Digital Negative: DNG is publicly available archival format for the raw files generated by digital cameras. By addressing the lack of an open standard for the raw files created by individual camera models, DNG helps ensure that photographers will be able to access their files in the future.
  322. "erf," // Epson Digital Camera Raw Image Format.
  323. "fff," // Imacon Digital Camera Raw Image Format.
  324. "ia," // Sinar Raw Image File.
  325. "iiq," // Phase One Digital Camera Raw Image Format.
  326. "k25," // Kodak DC25 Digital Camera Raw Image Format.
  327. "kc2," // Kodak DCS200 Digital Camera Raw Image Format.
  328. "kdc," // Kodak Digital Camera Raw Image Format.
  329. "mdc," // Minolta RD175 Digital Camera Raw Image Format.
  330. "mef," // Mamiya Digital Camera Raw Image Format.
  331. "mos," // Leaf Raw Image File.
  332. "mrw," // Minolta Dimage Digital Camera Raw Image Format.
  333. "nef," // Nikon Digital Camera Raw Image Format.
  334. "nrw," // Nikon Digital Camera Raw Image Format.
  335. "orf," // Olympus Digital Camera Raw Image Format.
  336. "pef," // Pentax Digital Camera Raw Image Format.
  337. "ptx," // Pentax Digital Camera Raw Image Format.
  338. "pxn," // Logitech Digital Camera Raw Image Format.
  339. "qtk," // Apple Quicktake 100/150 Digital Camera Raw Image Format.
  340. "raf," // Fuji Digital Camera Raw Image Format.
  341. "raw," // Panasonic Digital Camera Image Format.
  342. "rdc," // Digital Foto Maker Raw Image File.
  343. "rw2," // Panasonic LX3 Digital Camera Raw Image Format.
  344. "rwl," // Leica Camera Raw Image Format.
  345. "rwz," // Rawzor Digital Camera Raw Image Format.
  346. "sr2," // Sony Digital Camera Raw Image Format.
  347. "srf," // Sony Digital Camera Raw Image Format for DSC-F828 8 megapixel digital camera or Sony DSC-R1.
  348. "srw," // Samsung Raw Image Format.
  349. "sti"; // Sinar Capture Shop Raw Image File.
  350. // "x3f" // Sigma Digital Camera Raw Image Format for devices based on Foveon X3 direct image sensor.
  351. return raw_extensions;
  352. }
  353. static const char * DLL_CALLCONV
  354. RegExpr() {
  355. return NULL;
  356. }
  357. static const char * DLL_CALLCONV
  358. MimeType() {
  359. return "image/x-dcraw";
  360. }
  361. static BOOL DLL_CALLCONV
  362. Validate(FreeImageIO *io, fi_handle handle) {
  363. LibRaw RawProcessor;
  364. BOOL bSuccess = TRUE;
  365. // wrap the input datastream
  366. LibRaw_freeimage_datastream datastream(io, handle);
  367. // open the datastream
  368. if(RawProcessor.open_datastream(&datastream) != LIBRAW_SUCCESS) {
  369. bSuccess = FALSE; // LibRaw : failed to open input stream (unknown format)
  370. }
  371. // clean-up internal memory allocations
  372. RawProcessor.recycle();
  373. return bSuccess;
  374. }
  375. static BOOL DLL_CALLCONV
  376. SupportsExportDepth(int depth) {
  377. return FALSE;
  378. }
  379. static BOOL DLL_CALLCONV
  380. SupportsExportType(FREE_IMAGE_TYPE type) {
  381. return FALSE;
  382. }
  383. static BOOL DLL_CALLCONV
  384. SupportsICCProfiles() {
  385. return TRUE;
  386. }
  387. static BOOL DLL_CALLCONV
  388. SupportsNoPixels() {
  389. return TRUE;
  390. }
  391. // ----------------------------------------------------------
  392. static FIBITMAP * DLL_CALLCONV
  393. Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
  394. FIBITMAP *dib = NULL;
  395. LibRaw RawProcessor;
  396. BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;
  397. try {
  398. // wrap the input datastream
  399. LibRaw_freeimage_datastream datastream(io, handle);
  400. // set decoding parameters
  401. // the following parameters affect data reading
  402. // --------------------------------------------
  403. // (-s [0..N-1]) Select one raw image from input file
  404. RawProcessor.imgdata.params.shot_select = 0;
  405. // (-w) Use camera white balance, if possible (otherwise, fallback to auto_wb)
  406. RawProcessor.imgdata.params.use_camera_wb = 1;
  407. // (-h) outputs the image in 50% size
  408. RawProcessor.imgdata.params.half_size = ((flags & RAW_HALFSIZE) == RAW_HALFSIZE) ? 1 : 0;
  409. // open the datastream
  410. if(RawProcessor.open_datastream(&datastream) != LIBRAW_SUCCESS) {
  411. throw "LibRaw : failed to open input stream (unknown format)";
  412. }
  413. if(header_only) {
  414. // header only mode
  415. dib = FreeImage_AllocateHeaderT(header_only, FIT_RGB16, RawProcessor.imgdata.sizes.width, RawProcessor.imgdata.sizes.height);
  416. }
  417. else if((flags & RAW_PREVIEW) == RAW_PREVIEW) {
  418. // try to get the embedded JPEG
  419. dib = libraw_LoadEmbeddedPreview(RawProcessor, 0);
  420. if(!dib) {
  421. // no JPEG preview: try to load as 8-bit/sample (i.e. RGB 24-bit)
  422. dib = libraw_LoadRawData(RawProcessor, 8);
  423. }
  424. }
  425. else if((flags & RAW_DISPLAY) == RAW_DISPLAY) {
  426. // load raw data as 8-bit/sample (i.e. RGB 24-bit)
  427. dib = libraw_LoadRawData(RawProcessor, 8);
  428. }
  429. else {
  430. // default: load raw data as linear 16-bit/sample (i.e. RGB 48-bit)
  431. dib = libraw_LoadRawData(RawProcessor, 16);
  432. }
  433. // save ICC profile if present
  434. if(dib && (NULL != RawProcessor.imgdata.color.profile)) {
  435. FreeImage_CreateICCProfile(dib, RawProcessor.imgdata.color.profile, RawProcessor.imgdata.color.profile_length);
  436. }
  437. // try to get JPEG embedded Exif metadata
  438. if(dib && !((flags & RAW_PREVIEW) == RAW_PREVIEW)) {
  439. FIBITMAP *metadata_dib = libraw_LoadEmbeddedPreview(RawProcessor, FIF_LOAD_NOPIXELS);
  440. if(metadata_dib) {
  441. FreeImage_CloneMetadata(dib, metadata_dib);
  442. FreeImage_Unload(metadata_dib);
  443. }
  444. }
  445. // clean-up internal memory allocations
  446. RawProcessor.recycle();
  447. return dib;
  448. } catch(const char *text) {
  449. if(dib) {
  450. FreeImage_Unload(dib);
  451. }
  452. RawProcessor.recycle();
  453. FreeImage_OutputMessageProc(s_format_id, text);
  454. }
  455. return NULL;
  456. }
  457. // ==========================================================
  458. // Init
  459. // ==========================================================
  460. void DLL_CALLCONV
  461. InitRAW(Plugin *plugin, int format_id) {
  462. s_format_id = format_id;
  463. plugin->format_proc = Format;
  464. plugin->description_proc = Description;
  465. plugin->extension_proc = Extension;
  466. plugin->regexpr_proc = RegExpr;
  467. plugin->open_proc = NULL;
  468. plugin->close_proc = NULL;
  469. plugin->pagecount_proc = NULL;
  470. plugin->pagecapability_proc = NULL;
  471. plugin->load_proc = Load;
  472. plugin->save_proc = NULL;
  473. plugin->validate_proc = Validate;
  474. plugin->mime_proc = MimeType;
  475. plugin->supports_export_bpp_proc = SupportsExportDepth;
  476. plugin->supports_export_type_proc = SupportsExportType;
  477. plugin->supports_icc_profiles_proc = SupportsICCProfiles;
  478. plugin->supports_no_pixels_proc = SupportsNoPixels;
  479. }