llimagej2coj.cpp
上传用户:king477883
上传日期:2021-03-01
资源大小:9553k
文件大小:13k
源码类别:

游戏引擎

开发平台:

C++ Builder

  1. /** 
  2.  * @file llimagej2coj.cpp
  3.  * @brief This is an implementation of JPEG2000 encode/decode using OpenJPEG.
  4.  *
  5.  * $LicenseInfo:firstyear=2006&license=viewergpl$
  6.  * 
  7.  * Copyright (c) 2006-2010, Linden Research, Inc.
  8.  * 
  9.  * Second Life Viewer Source Code
  10.  * The source code in this file ("Source Code") is provided by Linden Lab
  11.  * to you under the terms of the GNU General Public License, version 2.0
  12.  * ("GPL"), unless you have obtained a separate licensing agreement
  13.  * ("Other License"), formally executed by you and Linden Lab.  Terms of
  14.  * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15.  * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16.  * 
  17.  * There are special exceptions to the terms and conditions of the GPL as
  18.  * it is applied to this Source Code. View the full text of the exception
  19.  * in the file doc/FLOSS-exception.txt in this software distribution, or
  20.  * online at
  21.  * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22.  * 
  23.  * By copying, modifying or distributing this software, you acknowledge
  24.  * that you have read and understood your obligations described above,
  25.  * and agree to abide by those obligations.
  26.  * 
  27.  * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28.  * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29.  * COMPLETENESS OR PERFORMANCE.
  30.  * $/LicenseInfo$
  31.  */
  32. #include "linden_common.h"
  33. #include "llimagej2coj.h"
  34. // this is defined so that we get static linking.
  35. #include "openjpeg.h"
  36. #include "lltimer.h"
  37. //#include "llmemory.h"
  38. const char* fallbackEngineInfoLLImageJ2CImpl()
  39. {
  40. static std::string version_string =
  41. std::string("OpenJPEG: " OPENJPEG_VERSION ", Runtime: ")
  42. + opj_version();
  43. return version_string.c_str();
  44. }
  45. LLImageJ2CImpl* fallbackCreateLLImageJ2CImpl()
  46. {
  47. return new LLImageJ2COJ();
  48. }
  49. void fallbackDestroyLLImageJ2CImpl(LLImageJ2CImpl* impl)
  50. {
  51. delete impl;
  52. impl = NULL;
  53. }
  54. // Return string from message, eliminating final n if present
  55. static std::string chomp(const char* msg)
  56. {
  57. // stomp trailing n
  58. std::string message = msg;
  59. if (!message.empty())
  60. {
  61. size_t last = message.size() - 1;
  62. if (message[last] == 'n')
  63. {
  64. message.resize( last );
  65. }
  66. }
  67. return message;
  68. }
  69. /**
  70. sample error callback expecting a LLFILE* client object
  71. */
  72. void error_callback(const char* msg, void*)
  73. {
  74. lldebugs << "LLImageJ2COJ: " << chomp(msg) << llendl;
  75. }
  76. /**
  77. sample warning callback expecting a LLFILE* client object
  78. */
  79. void warning_callback(const char* msg, void*)
  80. {
  81. lldebugs << "LLImageJ2COJ: " << chomp(msg) << llendl;
  82. }
  83. /**
  84. sample debug callback expecting no client object
  85. */
  86. void info_callback(const char* msg, void*)
  87. {
  88. lldebugs << "LLImageJ2COJ: " << chomp(msg) << llendl;
  89. }
  90. LLImageJ2COJ::LLImageJ2COJ()
  91. : LLImageJ2CImpl()
  92. {
  93. }
  94. LLImageJ2COJ::~LLImageJ2COJ()
  95. {
  96. }
  97. BOOL LLImageJ2COJ::decodeImpl(LLImageJ2C &base, LLImageRaw &raw_image, F32 decode_time, S32 first_channel, S32 max_channel_count)
  98. {
  99. //
  100. // FIXME: Get the comment field out of the texture
  101. //
  102. LLTimer decode_timer;
  103. opj_dparameters_t parameters; /* decompression parameters */
  104. opj_event_mgr_t event_mgr; /* event manager */
  105. opj_image_t *image = NULL;
  106. opj_dinfo_t* dinfo = NULL; /* handle to a decompressor */
  107. opj_cio_t *cio = NULL;
  108. /* configure the event callbacks (not required) */
  109. memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
  110. event_mgr.error_handler = error_callback;
  111. event_mgr.warning_handler = warning_callback;
  112. event_mgr.info_handler = info_callback;
  113. /* set decoding parameters to default values */
  114. opj_set_default_decoder_parameters(&parameters);
  115. parameters.cp_reduce = base.getRawDiscardLevel();
  116. /* decode the code-stream */
  117. /* ---------------------- */
  118. /* JPEG-2000 codestream */
  119. /* get a decoder handle */
  120. dinfo = opj_create_decompress(CODEC_J2K);
  121. /* catch events using our callbacks and give a local context */
  122. opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
  123. /* setup the decoder decoding parameters using user parameters */
  124. opj_setup_decoder(dinfo, &parameters);
  125. /* open a byte stream */
  126. cio = opj_cio_open((opj_common_ptr)dinfo, base.getData(), base.getDataSize());
  127. /* decode the stream and fill the image structure */
  128. image = opj_decode(dinfo, cio);
  129. /* close the byte stream */
  130. opj_cio_close(cio);
  131. /* free remaining structures */
  132. if(dinfo)
  133. {
  134. opj_destroy_decompress(dinfo);
  135. }
  136. // The image decode failed if the return was NULL or the component
  137. // count was zero.  The latter is just a sanity check before we
  138. // dereference the array.
  139. if(!image || !image->numcomps)
  140. {
  141. LL_DEBUGS("Texture") << "ERROR -> decodeImpl: failed to decode image!" << LL_ENDL;
  142. if (image)
  143. {
  144. opj_image_destroy(image);
  145. }
  146. return TRUE; // done
  147. }
  148. // sometimes we get bad data out of the cache - check to see if the decode succeeded
  149. for (S32 i = 0; i < image->numcomps; i++)
  150. {
  151. if (image->comps[i].factor != base.getRawDiscardLevel())
  152. {
  153. // if we didn't get the discard level we're expecting, fail
  154. opj_image_destroy(image);
  155. base.mDecoding = FALSE;
  156. return TRUE;
  157. }
  158. }
  159. if(image->numcomps <= first_channel)
  160. {
  161. llwarns << "trying to decode more channels than are present in image: numcomps: " << image->numcomps << " first_channel: " << first_channel << llendl;
  162. if (image)
  163. {
  164. opj_image_destroy(image);
  165. }
  166. return TRUE;
  167. }
  168. // Copy image data into our raw image format (instead of the separate channel format
  169. S32 img_components = image->numcomps;
  170. S32 channels = img_components - first_channel;
  171. if( channels > max_channel_count )
  172. channels = max_channel_count;
  173. // Component buffers are allocated in an image width by height buffer.
  174. // The image placed in that buffer is ceil(width/2^factor) by
  175. // ceil(height/2^factor) and if the factor isn't zero it will be at the
  176. // top left of the buffer with black filled in the rest of the pixels.
  177. // It is integer math so the formula is written in ceildivpo2.
  178. // (Assuming all the components have the same width, height and
  179. // factor.)
  180. S32 comp_width = image->comps[0].w;
  181. S32 f=image->comps[0].factor;
  182. S32 width = ceildivpow2(image->x1 - image->x0, f);
  183. S32 height = ceildivpow2(image->y1 - image->y0, f);
  184. raw_image.resize(width, height, channels);
  185. U8 *rawp = raw_image.getData();
  186. // first_channel is what channel to start copying from
  187. // dest is what channel to copy to.  first_channel comes from the
  188. // argument, dest always starts writing at channel zero.
  189. for (S32 comp = first_channel, dest=0; comp < first_channel + channels;
  190. comp++, dest++)
  191. {
  192. if (image->comps[comp].data)
  193. {
  194. S32 offset = dest;
  195. for (S32 y = (height - 1); y >= 0; y--)
  196. {
  197. for (S32 x = 0; x < width; x++)
  198. {
  199. rawp[offset] = image->comps[comp].data[y*comp_width + x];
  200. offset += channels;
  201. }
  202. }
  203. }
  204. else // Some rare OpenJPEG versions have this bug.
  205. {
  206. LL_DEBUGS("Texture") << "ERROR -> decodeImpl: failed to decode image! (NULL comp data - OpenJPEG bug)" << LL_ENDL;
  207. opj_image_destroy(image);
  208. return TRUE; // done
  209. }
  210. }
  211. /* free image data structure */
  212. opj_image_destroy(image);
  213. return TRUE; // done
  214. }
  215. BOOL LLImageJ2COJ::encodeImpl(LLImageJ2C &base, const LLImageRaw &raw_image, const char* comment_text, F32 encode_time, BOOL reversible)
  216. {
  217. const S32 MAX_COMPS = 5;
  218. opj_cparameters_t parameters; /* compression parameters */
  219. opj_event_mgr_t event_mgr; /* event manager */
  220. /* 
  221. configure the event callbacks (not required)
  222. setting of each callback is optional 
  223. */
  224. memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
  225. event_mgr.error_handler = error_callback;
  226. event_mgr.warning_handler = warning_callback;
  227. event_mgr.info_handler = info_callback;
  228. /* set encoding parameters to default values */
  229. opj_set_default_encoder_parameters(&parameters);
  230. parameters.cod_format = 0;
  231. parameters.cp_disto_alloc = 1;
  232. if (reversible)
  233. {
  234. parameters.tcp_numlayers = 1;
  235. parameters.tcp_rates[0] = 0.0f;
  236. }
  237. else
  238. {
  239. parameters.tcp_numlayers = 5;
  240.                 parameters.tcp_rates[0] = 1920.0f;
  241.                 parameters.tcp_rates[1] = 480.0f;
  242.                 parameters.tcp_rates[2] = 120.0f;
  243.                 parameters.tcp_rates[3] = 30.0f;
  244. parameters.tcp_rates[4] = 10.0f;
  245. parameters.irreversible = 1;
  246. if (raw_image.getComponents() >= 3)
  247. {
  248. parameters.tcp_mct = 1;
  249. }
  250. }
  251. if (!comment_text)
  252. {
  253. parameters.cp_comment = (char *) "";
  254. }
  255. else
  256. {
  257. // Awful hacky cast, too lazy to copy right now.
  258. parameters.cp_comment = (char *) comment_text;
  259. }
  260. //
  261. // Fill in the source image from our raw image
  262. //
  263. OPJ_COLOR_SPACE color_space = CLRSPC_SRGB;
  264. opj_image_cmptparm_t cmptparm[MAX_COMPS];
  265. opj_image_t * image = NULL;
  266. S32 numcomps = raw_image.getComponents();
  267. S32 width = raw_image.getWidth();
  268. S32 height = raw_image.getHeight();
  269. memset(&cmptparm[0], 0, MAX_COMPS * sizeof(opj_image_cmptparm_t));
  270. for(S32 c = 0; c < numcomps; c++) {
  271. cmptparm[c].prec = 8;
  272. cmptparm[c].bpp = 8;
  273. cmptparm[c].sgnd = 0;
  274. cmptparm[c].dx = parameters.subsampling_dx;
  275. cmptparm[c].dy = parameters.subsampling_dy;
  276. cmptparm[c].w = width;
  277. cmptparm[c].h = height;
  278. }
  279. /* create the image */
  280. image = opj_image_create(numcomps, &cmptparm[0], color_space);
  281. image->x1 = width;
  282. image->y1 = height;
  283. S32 i = 0;
  284. const U8 *src_datap = raw_image.getData();
  285. for (S32 y = height - 1; y >= 0; y--)
  286. {
  287. for (S32 x = 0; x < width; x++)
  288. {
  289. const U8 *pixel = src_datap + (y*width + x) * numcomps;
  290. for (S32 c = 0; c < numcomps; c++)
  291. {
  292. image->comps[c].data[i] = *pixel;
  293. pixel++;
  294. }
  295. i++;
  296. }
  297. }
  298. /* encode the destination image */
  299. /* ---------------------------- */
  300. int codestream_length;
  301. opj_cio_t *cio = NULL;
  302. /* get a J2K compressor handle */
  303. opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
  304. /* catch events using our callbacks and give a local context */
  305. opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
  306. /* setup the encoder parameters using the current image and using user parameters */
  307. opj_setup_encoder(cinfo, &parameters, image);
  308. /* open a byte stream for writing */
  309. /* allocate memory for all tiles */
  310. cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
  311. /* encode the image */
  312. bool bSuccess = opj_encode(cinfo, cio, image, NULL);
  313. if (!bSuccess)
  314. {
  315. opj_cio_close(cio);
  316. LL_DEBUGS("Texture") << "Failed to encode image." << LL_ENDL;
  317. return FALSE;
  318. }
  319. codestream_length = cio_tell(cio);
  320. base.copyData(cio->buffer, codestream_length);
  321. base.updateData(); // set width, height
  322. /* close and free the byte stream */
  323. opj_cio_close(cio);
  324. /* free remaining compression structures */
  325. opj_destroy_compress(cinfo);
  326. /* free user parameters structure */
  327. if(parameters.cp_matrice) free(parameters.cp_matrice);
  328. /* free image data */
  329. opj_image_destroy(image);
  330. return TRUE;
  331. }
  332. BOOL LLImageJ2COJ::getMetadata(LLImageJ2C &base)
  333. {
  334. //
  335. // FIXME: We get metadata by decoding the ENTIRE image.
  336. //
  337. // Update the raw discard level
  338. base.updateRawDiscardLevel();
  339. opj_dparameters_t parameters; /* decompression parameters */
  340. opj_event_mgr_t event_mgr; /* event manager */
  341. opj_image_t *image = NULL;
  342. opj_dinfo_t* dinfo = NULL; /* handle to a decompressor */
  343. opj_cio_t *cio = NULL;
  344. /* configure the event callbacks (not required) */
  345. memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
  346. event_mgr.error_handler = error_callback;
  347. event_mgr.warning_handler = warning_callback;
  348. event_mgr.info_handler = info_callback;
  349. /* set decoding parameters to default values */
  350. opj_set_default_decoder_parameters(&parameters);
  351. // Only decode what's required to get the size data.
  352. parameters.cp_limit_decoding=LIMIT_TO_MAIN_HEADER;
  353. //parameters.cp_reduce = mRawDiscardLevel;
  354. /* decode the code-stream */
  355. /* ---------------------- */
  356. /* JPEG-2000 codestream */
  357. /* get a decoder handle */
  358. dinfo = opj_create_decompress(CODEC_J2K);
  359. /* catch events using our callbacks and give a local context */
  360. opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
  361. /* setup the decoder decoding parameters using user parameters */
  362. opj_setup_decoder(dinfo, &parameters);
  363. /* open a byte stream */
  364. cio = opj_cio_open((opj_common_ptr)dinfo, base.getData(), base.getDataSize());
  365. /* decode the stream and fill the image structure */
  366. image = opj_decode(dinfo, cio);
  367. /* close the byte stream */
  368. opj_cio_close(cio);
  369. /* free remaining structures */
  370. if(dinfo)
  371. {
  372. opj_destroy_decompress(dinfo);
  373. }
  374. if(!image)
  375. {
  376. llwarns << "ERROR -> getMetadata: failed to decode image!" << llendl;
  377. return FALSE;
  378. }
  379. // Copy image data into our raw image format (instead of the separate channel format
  380. S32 width = 0;
  381. S32 height = 0;
  382. S32 img_components = image->numcomps;
  383. width = image->x1 - image->x0;
  384. height = image->y1 - image->y0;
  385. base.setSize(width, height, img_components);
  386. /* free image data structure */
  387. opj_image_destroy(image);
  388. return TRUE;
  389. }