llimagej2c.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /**
  2. * @file llimagej2c.cpp
  3. *
  4. * $LicenseInfo:firstyear=2001&license=viewergpl$
  5. *
  6. * Copyright (c) 2001-2009, Linden Research, Inc.
  7. *
  8. * Second Life Viewer Source Code
  9. * The source code in this file ("Source Code") is provided by Linden Lab
  10. * to you under the terms of the GNU General Public License, version 2.0
  11. * ("GPL"), unless you have obtained a separate licensing agreement
  12. * ("Other License"), formally executed by you and Linden Lab. Terms of
  13. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  14. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  15. *
  16. * There are special exceptions to the terms and conditions of the GPL as
  17. * it is applied to this Source Code. View the full text of the exception
  18. * in the file doc/FLOSS-exception.txt in this software distribution, or
  19. * online at
  20. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  21. *
  22. * By copying, modifying or distributing this software, you acknowledge
  23. * that you have read and understood your obligations described above,
  24. * and agree to abide by those obligations.
  25. *
  26. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  27. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  28. * COMPLETENESS OR PERFORMANCE.
  29. * $/LicenseInfo$
  30. */
  31. #include "linden_common.h"
  32. #include "openjpeg.h"
  33. #include "llimagej2c.h"
  34. #include "lldir.h"
  35. // Helper function
  36. static LL_INLINE int ceildivpow2(int a, int b)
  37. {
  38. // Divide a by b to the power of 2 and round upwards.
  39. return (a + (1 << b) - 1) >> b;
  40. }
  41. LLImageJ2C::LLImageJ2C()
  42. : LLImageFormatted(IMG_CODEC_J2C),
  43. mMaxBytes(0),
  44. mRawDiscardLevel(-1),
  45. mRate(0.f),
  46. mReversible(false)
  47. {
  48. }
  49. //static
  50. std::string LLImageJ2C::getEngineInfo()
  51. {
  52. static std::string version_string = std::string("OpenJPEG: ") +
  53. opj_version();
  54. return version_string.c_str();
  55. }
  56. //virtual
  57. void LLImageJ2C::setLastError(const std::string& message,
  58. const std::string& filename)
  59. {
  60. mLastError = message;
  61. if (!filename.empty())
  62. {
  63. mLastError += std::string(" FILE: ") + filename;
  64. }
  65. }
  66. bool LLImageJ2C::updateData()
  67. {
  68. bool res = true;
  69. resetLastError();
  70. // Check to make sure that this instance has been initialized with data
  71. if (!getData() || getDataSize() < 16)
  72. {
  73. setLastError("LLImageJ2C uninitialized");
  74. res = false;
  75. }
  76. else
  77. {
  78. res = getMetadata();
  79. }
  80. if (res)
  81. {
  82. // SJB: override discard based on mMaxBytes elsewhere
  83. S32 max_bytes = getDataSize(); // mMaxBytes ? mMaxBytes : getDataSize();
  84. S32 discard = calcDiscardLevelBytes(max_bytes);
  85. setDiscardLevel(discard);
  86. }
  87. if (!mLastError.empty())
  88. {
  89. LLImage::setLastError(mLastError);
  90. }
  91. return res;
  92. }
  93. //static
  94. S32 LLImageJ2C::calcDataSizeJ2C(S32 w, S32 h, S32 comp, S32 discard_level,
  95. F32 rate)
  96. {
  97. if (rate <= 0.f)
  98. {
  99. rate = .125f;
  100. }
  101. while (discard_level > 0)
  102. {
  103. if (w < 1 || h < 1)
  104. {
  105. break;
  106. }
  107. w >>= 1;
  108. h >>= 1;
  109. --discard_level;
  110. }
  111. S32 bytes = (S32)((F32)(w * h * comp) * rate);
  112. bytes = llmax(bytes, FIRST_PACKET_SIZE);
  113. return bytes;
  114. }
  115. S32 LLImageJ2C::calcDataSize(S32 discard_level)
  116. {
  117. return calcDataSizeJ2C(getWidth(), getHeight(), getComponents(),
  118. discard_level, mRate);
  119. }
  120. S32 LLImageJ2C::calcDiscardLevelBytes(S32 bytes)
  121. {
  122. if (bytes < 0)
  123. {
  124. llwarns << "Negative bytes amount passed !" << llendl;
  125. llassert(false);
  126. return MAX_DISCARD_LEVEL;
  127. }
  128. else if (bytes == 0)
  129. {
  130. return MAX_DISCARD_LEVEL;
  131. }
  132. S32 discard_level = 0;
  133. while (true)
  134. {
  135. S32 bytes_needed = calcDataSize(discard_level); // virtual
  136. // For J2C, up the res at 75% of the optimal number of bytes:
  137. if (bytes >= bytes_needed - (bytes_needed >> 2))
  138. {
  139. break;
  140. }
  141. if (++discard_level >= MAX_DISCARD_LEVEL)
  142. {
  143. break;
  144. }
  145. }
  146. return discard_level;
  147. }
  148. bool LLImageJ2C::loadAndValidate(const std::string& filename)
  149. {
  150. bool res = true;
  151. resetLastError();
  152. S64 file_size = 0;
  153. LLFile infile(filename, "rb", &file_size);
  154. if (!infile)
  155. {
  156. setLastError("Unable to open file for reading", filename);
  157. res = false;
  158. }
  159. else if (file_size == 0)
  160. {
  161. setLastError("File is empty", filename);
  162. res = false;
  163. }
  164. else
  165. {
  166. U8* data = (U8*)allocate_texture_mem(file_size);
  167. if (!data)
  168. {
  169. setLastError("Out of memory", filename);
  170. return false;
  171. }
  172. S64 bytes_read = infile.read(data, file_size);
  173. if (bytes_read != file_size)
  174. {
  175. free_texture_mem(data);
  176. setLastError("Unable to read entire file");
  177. res = false;
  178. }
  179. else
  180. {
  181. res = validate(data, file_size);
  182. }
  183. }
  184. if (!mLastError.empty())
  185. {
  186. LLImage::setLastError(mLastError);
  187. }
  188. return res;
  189. }
  190. bool LLImageJ2C::validate(U8* data, U32 file_size)
  191. {
  192. if (!data) return false;
  193. resetLastError();
  194. setData(data, file_size);
  195. bool res = updateData();
  196. if (res)
  197. {
  198. // Check to make sure that this instance has been initialized with data
  199. if (!getData() || getDataSize() == 0)
  200. {
  201. setLastError("LLImageJ2C uninitialized");
  202. res = false;
  203. }
  204. else
  205. {
  206. res = getMetadata();
  207. }
  208. }
  209. if (!mLastError.empty())
  210. {
  211. LLImage::setLastError(mLastError);
  212. }
  213. return res;
  214. }
  215. void LLImageJ2C::updateRawDiscardLevel()
  216. {
  217. mRawDiscardLevel = mMaxBytes ? calcDiscardLevelBytes(mMaxBytes)
  218. : mDiscardLevel;
  219. }
  220. // Returns true to mean done, whether successful or not.
  221. bool LLImageJ2C::decodeChannels(LLImageRaw* raw_imagep, S32 first_channel,
  222. S32 max_channel_count)
  223. {
  224. if (!raw_imagep) return false;
  225. resetLastError();
  226. bool res = true;
  227. // Check to make sure that this instance has been initialized with data
  228. if (!getData() || getDataSize() < 16)
  229. {
  230. setLastError("LLImageJ2C uninitialized");
  231. }
  232. #if 1
  233. else if (!LLMemory::hasFailedAllocation())
  234. #else
  235. else
  236. #endif
  237. {
  238. // Update the raw discard level
  239. updateRawDiscardLevel();
  240. mDecoding = true;
  241. res = decodeImpl(*raw_imagep, first_channel, max_channel_count);
  242. }
  243. if (res)
  244. {
  245. if (!mDecoding)
  246. {
  247. // Failed
  248. raw_imagep->deleteData();
  249. }
  250. else
  251. {
  252. mDecoding = false;
  253. }
  254. }
  255. if (!mLastError.empty())
  256. {
  257. LLImage::setLastError(mLastError);
  258. }
  259. return res;
  260. }
  261. bool LLImageJ2C::encode(const LLImageRaw* raw_imagep, const char* comment)
  262. {
  263. if (!raw_imagep) return false;
  264. resetLastError();
  265. bool res = encodeImpl(*raw_imagep, comment);
  266. if (!mLastError.empty())
  267. {
  268. LLImage::setLastError(mLastError);
  269. }
  270. return res;
  271. }
  272. bool LLImageJ2C::getMetadataFast(S32& width, S32& height, S32& comps)
  273. {
  274. constexpr S32 J2K_HEADER_LENGTH = 42;
  275. if (getDataSize() < J2K_HEADER_LENGTH)
  276. {
  277. return false;
  278. }
  279. const U8* rawp = getData();
  280. if (!rawp || *rawp != 0xff || rawp[1] != 0x4f || rawp[2] != 0xff ||
  281. rawp[3] != 0x51)
  282. {
  283. return false;
  284. }
  285. width = (rawp[8] << 24) + (rawp[9] << 16) + (rawp[10] << 8) + rawp[11] -
  286. (rawp[16] << 24) - (rawp[17] << 16) - (rawp[18] << 8) - rawp[19];
  287. height = (rawp[12] << 24) + (rawp[13] << 16) + (rawp[14] << 8) + rawp[15] -
  288. (rawp[20] << 24) - (rawp[21] << 16) - (rawp[22] << 8) - rawp[23];
  289. comps = (rawp[40] << 8) + rawp[41];
  290. return true;
  291. }
  292. // Callback method for OpenJPEG warnings and errors.
  293. //static
  294. void LLImageJ2C::eventMgrCallback(const char* msg, void*)
  295. {
  296. if (msg && *msg)
  297. {
  298. std::string message = msg;
  299. if (message.back() == '\n')
  300. {
  301. message.pop_back();
  302. }
  303. llwarns << message << llendl;
  304. }
  305. }
  306. // Implementation details specific methods
  307. static opj_event_mgr_t sEventMgr; // OpenJPEG event manager
  308. // Event manager initialization.
  309. //static
  310. void LLImageJ2C::initEventManager()
  311. {
  312. static bool event_mgr_initialized = false;
  313. if (!event_mgr_initialized)
  314. {
  315. event_mgr_initialized = true;
  316. // Configure the event callbacks (not required); setting of each
  317. // callback is optional
  318. memset(&sEventMgr, 0, sizeof(opj_event_mgr_t));
  319. sEventMgr.error_handler = LLImageJ2C::eventMgrCallback;
  320. sEventMgr.warning_handler = LLImageJ2C::eventMgrCallback;
  321. #if 0 // INFO messages are not interesting to us
  322. sEventMgr.info_handler = LLImageJ2C::eventMgrCallback;
  323. #endif
  324. }
  325. }
  326. bool LLImageJ2C::getMetadata()
  327. {
  328. // Update the raw discard level
  329. updateRawDiscardLevel();
  330. S32 width = 0;
  331. S32 height = 0;
  332. S32 img_components = 0;
  333. // Try it the fast way first...
  334. if (getMetadataFast(width, height, img_components))
  335. {
  336. setSize(width, height, img_components);
  337. return true;
  338. }
  339. initEventManager();
  340. // *FIXME: We get metadata by decoding the ENTIRE image.
  341. opj_dparameters_t parameters; // decompression parameters
  342. opj_image_t* image = NULL;
  343. opj_dinfo_t* dinfo = NULL; // handle to a decompressor
  344. opj_cio_t* cio = NULL;
  345. // Set decoding parameters to default values
  346. opj_set_default_decoder_parameters(&parameters);
  347. // Only decode what is required to get the size data.
  348. parameters.cp_limit_decoding = LIMIT_TO_MAIN_HEADER;
  349. #if 0
  350. parameters.cp_reduce = mRawDiscardLevel;
  351. #endif
  352. // Get a decoder handle
  353. dinfo = opj_create_decompress(CODEC_J2K);
  354. // Catch events using our callbacks and give a local context
  355. opj_set_event_mgr((opj_common_ptr)dinfo, &sEventMgr, NULL);
  356. // Setup the decoder decoding parameters using user parameters
  357. opj_setup_decoder(dinfo, &parameters);
  358. // Open a byte stream
  359. cio = opj_cio_open((opj_common_ptr)dinfo, getData(), getDataSize());
  360. // Decode the stream and fill the image structure
  361. image = opj_decode(dinfo, cio);
  362. // Close the byte stream
  363. opj_cio_close(cio);
  364. // Free remaining structures
  365. if (dinfo)
  366. {
  367. opj_destroy_decompress(dinfo);
  368. }
  369. if (!image)
  370. {
  371. llwarns << "Failed to decode image !" << llendl;
  372. return false;
  373. }
  374. // Copy image data into our raw image format (instead of the separate
  375. // channel format
  376. img_components = image->numcomps;
  377. width = image->x1 - image->x0;
  378. height = image->y1 - image->y0;
  379. setSize(width, height, img_components);
  380. // Free image data structure
  381. opj_image_destroy(image);
  382. return true;
  383. }
  384. // Decodes the JPEG-2000 code-stream
  385. bool LLImageJ2C::decodeImpl(LLImageRaw& raw_image, S32 first_channel,
  386. S32 max_channel_count)
  387. {
  388. initEventManager();
  389. opj_dparameters_t parameters; // Decompression parameters
  390. opj_image_t* image = NULL;
  391. opj_dinfo_t* dinfo = NULL; // Handle to a decompressor
  392. opj_cio_t* cio = NULL;
  393. // Set decoding parameters to default values
  394. opj_set_default_decoder_parameters(&parameters);
  395. parameters.cp_reduce = getRawDiscardLevel();
  396. // Get a decoder handle
  397. dinfo = opj_create_decompress(CODEC_J2K);
  398. // Catch events using our callbacks and give a local context
  399. opj_set_event_mgr((opj_common_ptr)dinfo, &sEventMgr, NULL);
  400. // Setup the decoder decoding parameters using user parameters
  401. opj_setup_decoder(dinfo, &parameters);
  402. // Open a byte stream
  403. cio = opj_cio_open((opj_common_ptr)dinfo, getData(), getDataSize());
  404. // Decode the stream and fill the image structure
  405. image = opj_decode(dinfo, cio);
  406. // Close the byte stream
  407. opj_cio_close(cio);
  408. // Free remaining structures
  409. if (dinfo)
  410. {
  411. opj_destroy_decompress(dinfo);
  412. }
  413. // The image decode failed if the return was NULL or the component count
  414. // was zero. The latter is just a sanity check before we dereference the
  415. // array.
  416. if (!image || !image->numcomps)
  417. {
  418. llwarns << "Failed to decode image !" << llendl;
  419. if (image)
  420. {
  421. opj_image_destroy(image);
  422. }
  423. mDecoding = false;
  424. return true; // Done
  425. }
  426. // Sometimes we get bad data out of the cache - check to see if the decode
  427. // succeeded
  428. for (S32 i = 0; i < image->numcomps; ++i)
  429. {
  430. if (image->comps[i].factor != getRawDiscardLevel())
  431. {
  432. llwarns << "Expected discard level not reached" << llendl;
  433. // If we did not get the discard level we are expecting, fail
  434. opj_image_destroy(image);
  435. mDecoding = false;
  436. return true;
  437. }
  438. }
  439. if (image->numcomps <= first_channel)
  440. {
  441. llwarns << "Trying to decode more channels than are present in image: numcomps = "
  442. << image->numcomps << " - first_channel = " << first_channel
  443. << llendl;
  444. opj_image_destroy(image);
  445. mDecoding = false;
  446. return true;
  447. }
  448. // Copy image data into our raw image format (instead of the separate
  449. // channel format
  450. S32 img_components = image->numcomps;
  451. S32 channels = img_components - first_channel;
  452. if (channels > max_channel_count)
  453. {
  454. channels = max_channel_count;
  455. }
  456. // Component buffers are allocated in an image width by height buffer.
  457. // The image placed in that buffer is ceil(width/2^factor) by
  458. // ceil(height/2^factor) and if the factor isn't zero it will be at the
  459. // top left of the buffer with black filled in the rest of the pixels.
  460. // It is integer math so the formula is written in ceildivpo2.
  461. // (Assuming all the components have the same width, height and
  462. // factor.)
  463. S32 comp_width = image->comps[0].w;
  464. S32 f = image->comps[0].factor;
  465. S32 width = ceildivpow2(image->x1 - image->x0, f);
  466. S32 height = ceildivpow2(image->y1 - image->y0, f);
  467. raw_image.resize(width, height, channels);
  468. U8* rawp = raw_image.getData();
  469. if (!rawp)
  470. {
  471. setLastError("Could not create raw image");
  472. opj_image_destroy(image);
  473. return true;
  474. }
  475. // First_channel is what channel to start copying from dest is what channel
  476. // to copy to. first_channel comes from the argument, dest always starts
  477. // writing at channel zero.
  478. for (S32 comp = first_channel, dest = 0; comp < first_channel + channels;
  479. ++comp, ++dest)
  480. {
  481. if (image->comps[comp].data)
  482. {
  483. S32 offset = dest;
  484. for (S32 y = height - 1; y >= 0; --y)
  485. {
  486. for (S32 x = 0; x < width; ++x)
  487. {
  488. rawp[offset] = image->comps[comp].data[y * comp_width + x];
  489. offset += channels;
  490. }
  491. }
  492. }
  493. else // Some rare OpenJPEG versions have this bug.
  494. {
  495. llwarns << "Failed to decode image ! (NULL comp data - OpenJPEG bug)"
  496. << llendl;
  497. opj_image_destroy(image);
  498. mDecoding = false;
  499. return true; // Done
  500. }
  501. }
  502. // Free image data structure
  503. opj_image_destroy(image);
  504. return true; // Done
  505. }
  506. // Decodes the JPEG-2000 code-stream
  507. bool LLImageJ2C::encodeImpl(const LLImageRaw& raw_image, const char* comment)
  508. {
  509. initEventManager();
  510. constexpr S32 MAX_COMPS = 5;
  511. opj_cparameters_t parameters; // compression parameters
  512. // Set encoding parameters to default values
  513. opj_set_default_encoder_parameters(&parameters);
  514. parameters.cod_format = 0;
  515. parameters.cp_disto_alloc = 1;
  516. if (mReversible)
  517. {
  518. parameters.tcp_numlayers = 1;
  519. parameters.tcp_rates[0] = 0.f;
  520. }
  521. else
  522. {
  523. parameters.tcp_numlayers = 5;
  524. parameters.tcp_rates[0] = 1920.f;
  525. parameters.tcp_rates[1] = 480.f;
  526. parameters.tcp_rates[2] = 120.f;
  527. parameters.tcp_rates[3] = 30.f;
  528. parameters.tcp_rates[4] = 10.f;
  529. parameters.irreversible = 1;
  530. if (raw_image.getComponents() >= 3)
  531. {
  532. parameters.tcp_mct = 1;
  533. }
  534. }
  535. if (!comment)
  536. {
  537. parameters.cp_comment = (char*)"";
  538. }
  539. else
  540. {
  541. // *HACK: awful cast, too lazy to copy right now.
  542. parameters.cp_comment = (char*)comment;
  543. }
  544. // Fill in the source image from our raw image
  545. OPJ_COLOR_SPACE color_space = CLRSPC_SRGB;
  546. opj_image_cmptparm_t cmptparm[MAX_COMPS];
  547. opj_image_t* image = NULL;
  548. S32 numcomps = llmin((S32)raw_image.getComponents(), MAX_COMPS);
  549. S32 width = raw_image.getWidth();
  550. S32 height = raw_image.getHeight();
  551. memset(&cmptparm[0], 0, MAX_COMPS * sizeof(opj_image_cmptparm_t));
  552. for (S32 c = 0; c < numcomps; ++c)
  553. {
  554. cmptparm[c].prec = 8;
  555. cmptparm[c].bpp = 8;
  556. cmptparm[c].sgnd = 0;
  557. cmptparm[c].dx = parameters.subsampling_dx;
  558. cmptparm[c].dy = parameters.subsampling_dy;
  559. cmptparm[c].w = width;
  560. cmptparm[c].h = height;
  561. }
  562. // Create the image
  563. image = opj_image_create(numcomps, &cmptparm[0], color_space);
  564. if (!image)
  565. {
  566. llwarns << "Could not create image: out of memory ?" << llendl;
  567. // Free user parameters structure
  568. if (parameters.cp_matrice)
  569. {
  570. free(parameters.cp_matrice);
  571. }
  572. return false;
  573. }
  574. image->x1 = width;
  575. image->y1 = height;
  576. S32 i = 0;
  577. const U8* src_datap = raw_image.getData();
  578. for (S32 y = height - 1; y >= 0; --y)
  579. {
  580. for (S32 x = 0; x < width; ++x)
  581. {
  582. const U8* pixel = src_datap + (y * width + x) * numcomps;
  583. for (S32 c = 0; c < numcomps; ++c)
  584. {
  585. image->comps[c].data[i] = *pixel++;
  586. }
  587. ++i;
  588. }
  589. }
  590. // Encode the destination image
  591. int codestream_length;
  592. opj_cio_t* cio = NULL;
  593. // Get a J2K compressor handle
  594. opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
  595. // Catch events using our callbacks and give a local context
  596. opj_set_event_mgr((opj_common_ptr)cinfo, &sEventMgr, NULL);
  597. // Setup the encoder parameters using the current image and using user
  598. // parameters
  599. opj_setup_encoder(cinfo, &parameters, image);
  600. // Allocate memory for all tiles
  601. cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
  602. // Encode the image
  603. if (!opj_encode(cinfo, cio, image, NULL))
  604. {
  605. opj_cio_close(cio);
  606. llwarns << "Failed to encode image." << llendl;
  607. return false;
  608. }
  609. codestream_length = cio_tell(cio);
  610. copyData(cio->buffer, codestream_length);
  611. updateData(); // Set width, height
  612. // Close and free the byte stream
  613. opj_cio_close(cio);
  614. // Free remaining compression structures
  615. opj_destroy_compress(cinfo);
  616. // Free user parameters structure
  617. if (parameters.cp_matrice)
  618. {
  619. free(parameters.cp_matrice);
  620. }
  621. // Free image data
  622. opj_image_destroy(image);
  623. return true;
  624. }