PageRenderTime 89ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/indra/llkdu/llimagej2ckdu.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 1156 lines | 888 code | 129 blank | 139 comment | 126 complexity | 4b00bea675ffa7dbaf6d17ee3eb77c36 MD5 | raw file
Possible License(s): LGPL-2.1
  1. /**
  2. * @file llimagej2ckdu.cpp
  3. * @brief This is an implementation of JPEG2000 encode/decode using Kakadu
  4. *
  5. * $LicenseInfo:firstyear=2010&license=viewerlgpl$
  6. * Second Life Viewer Source Code
  7. * Copyright (C) 2010, Linden Research, Inc.
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation;
  12. * version 2.1 of the License only.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. *
  23. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  24. * $/LicenseInfo$
  25. */
  26. #include "linden_common.h"
  27. #include "llimagej2ckdu.h"
  28. #include "lltimer.h"
  29. #include "llpointer.h"
  30. #include "llmath.h"
  31. #include "llkdumem.h"
  32. class kdc_flow_control {
  33. public:
  34. kdc_flow_control(kdu_image_in_base *img_in, kdu_codestream codestream);
  35. ~kdc_flow_control();
  36. bool advance_components();
  37. void process_components();
  38. private:
  39. struct kdc_component_flow_control {
  40. public:
  41. kdu_image_in_base *reader;
  42. int vert_subsampling;
  43. int ratio_counter; /* Initialized to 0, decremented by `count_delta';
  44. when < 0, a new line must be processed, after
  45. which it is incremented by `vert_subsampling'. */
  46. int initial_lines;
  47. int remaining_lines;
  48. kdu_line_buf *line;
  49. };
  50. kdu_codestream codestream;
  51. kdu_dims valid_tile_indices;
  52. kdu_coords tile_idx;
  53. kdu_tile tile;
  54. int num_components;
  55. kdc_component_flow_control *components;
  56. int count_delta; // Holds the minimum of the `vert_subsampling' fields
  57. kdu_multi_analysis engine;
  58. kdu_long max_buffer_memory;
  59. };
  60. //
  61. // Kakadu specific implementation
  62. //
  63. void set_default_colour_weights(kdu_params *siz);
  64. const char* engineInfoLLImageJ2CKDU()
  65. {
  66. static std::string version = llformat("KDU %s", KDU_CORE_VERSION);
  67. return version.c_str();
  68. }
  69. LLImageJ2CKDU* createLLImageJ2CKDU()
  70. {
  71. return new LLImageJ2CKDU();
  72. }
  73. void destroyLLImageJ2CKDU(LLImageJ2CKDU* kdu)
  74. {
  75. delete kdu;
  76. kdu = NULL;
  77. }
  78. LLImageJ2CImpl* fallbackCreateLLImageJ2CImpl()
  79. {
  80. return new LLImageJ2CKDU();
  81. }
  82. void fallbackDestroyLLImageJ2CImpl(LLImageJ2CImpl* impl)
  83. {
  84. delete impl;
  85. impl = NULL;
  86. }
  87. const char* fallbackEngineInfoLLImageJ2CImpl()
  88. {
  89. return engineInfoLLImageJ2CKDU();
  90. }
  91. class LLKDUDecodeState
  92. {
  93. public:
  94. LLKDUDecodeState(kdu_tile tile, kdu_byte *buf, S32 row_gap);
  95. ~LLKDUDecodeState();
  96. BOOL processTileDecode(F32 decode_time, BOOL limit_time = TRUE);
  97. private:
  98. S32 mNumComponents;
  99. BOOL mUseYCC;
  100. kdu_dims mDims;
  101. kdu_sample_allocator mAllocator;
  102. kdu_tile_comp mComps[4];
  103. kdu_line_buf mLines[4];
  104. kdu_pull_ifc mEngines[4];
  105. bool mReversible[4]; // Some components may be reversible and others not
  106. int mBitDepths[4]; // Original bit-depth may be quite different from 8
  107. kdu_tile mTile;
  108. kdu_byte *mBuf;
  109. S32 mRowGap;
  110. };
  111. void ll_kdu_error( void )
  112. {
  113. // *FIX: This exception is bad, bad, bad. It gets thrown from a
  114. // destructor which can lead to immediate program termination!
  115. throw "ll_kdu_error() throwing an exception";
  116. }
  117. // Stuff for new kdu error handling
  118. class LLKDUMessageWarning : public kdu_message
  119. {
  120. public:
  121. /*virtual*/ void put_text(const char *s);
  122. /*virtual*/ void put_text(const kdu_uint16 *s);
  123. static LLKDUMessageWarning sDefaultMessage;
  124. };
  125. class LLKDUMessageError : public kdu_message
  126. {
  127. public:
  128. /*virtual*/ void put_text(const char *s);
  129. /*virtual*/ void put_text(const kdu_uint16 *s);
  130. /*virtual*/ void flush(bool end_of_message = false);
  131. static LLKDUMessageError sDefaultMessage;
  132. };
  133. void LLKDUMessageWarning::put_text(const char *s)
  134. {
  135. llinfos << "KDU Warning: " << s << llendl;
  136. }
  137. void LLKDUMessageWarning::put_text(const kdu_uint16 *s)
  138. {
  139. llinfos << "KDU Warning: " << s << llendl;
  140. }
  141. void LLKDUMessageError::put_text(const char *s)
  142. {
  143. llinfos << "KDU Error: " << s << llendl;
  144. }
  145. void LLKDUMessageError::put_text(const kdu_uint16 *s)
  146. {
  147. llinfos << "KDU Error: " << s << llendl;
  148. }
  149. void LLKDUMessageError::flush(bool end_of_message)
  150. {
  151. if (end_of_message)
  152. {
  153. throw "KDU throwing an exception";
  154. }
  155. }
  156. LLKDUMessageWarning LLKDUMessageWarning::sDefaultMessage;
  157. LLKDUMessageError LLKDUMessageError::sDefaultMessage;
  158. static bool kdu_message_initialized = false;
  159. LLImageJ2CKDU::LLImageJ2CKDU() : LLImageJ2CImpl(),
  160. mInputp(NULL),
  161. mCodeStreamp(NULL),
  162. mTPosp(NULL),
  163. mTileIndicesp(NULL),
  164. mRawImagep(NULL),
  165. mDecodeState(NULL),
  166. mBlocksSize(-1),
  167. mPrecinctsSize(-1),
  168. mLevels(0)
  169. {
  170. }
  171. LLImageJ2CKDU::~LLImageJ2CKDU()
  172. {
  173. cleanupCodeStream(); // in case destroyed before decode completed
  174. }
  175. // Stuff for new simple decode
  176. void transfer_bytes(kdu_byte *dest, kdu_line_buf &src, int gap, int precision);
  177. void LLImageJ2CKDU::setupCodeStream(LLImageJ2C &base, BOOL keep_codestream, ECodeStreamMode mode)
  178. {
  179. S32 data_size = base.getDataSize();
  180. S32 max_bytes = (base.getMaxBytes() ? base.getMaxBytes() : data_size);
  181. //
  182. // Initialization
  183. //
  184. if (!kdu_message_initialized)
  185. {
  186. kdu_message_initialized = true;
  187. kdu_customize_errors(&LLKDUMessageError::sDefaultMessage);
  188. kdu_customize_warnings(&LLKDUMessageWarning::sDefaultMessage);
  189. }
  190. if (mCodeStreamp)
  191. {
  192. mCodeStreamp->destroy();
  193. delete mCodeStreamp;
  194. mCodeStreamp = NULL;
  195. }
  196. if (!mInputp && base.getData())
  197. {
  198. // The compressed data has been loaded
  199. // Setup the source for the codestream
  200. mInputp = new LLKDUMemSource(base.getData(), data_size);
  201. }
  202. if (mInputp)
  203. {
  204. mInputp->reset();
  205. }
  206. mCodeStreamp = new kdu_codestream;
  207. mCodeStreamp->create(mInputp);
  208. // Set the maximum number of bytes to use from the codestream
  209. mCodeStreamp->set_max_bytes(max_bytes);
  210. // If you want to flip or rotate the image for some reason, change
  211. // the resolution, or identify a restricted region of interest, this is
  212. // the place to do it. You may use "kdu_codestream::change_appearance"
  213. // and "kdu_codestream::apply_input_restrictions" for this purpose.
  214. // If you wish to truncate the code-stream prior to decompression, you
  215. // may use "kdu_codestream::set_max_bytes".
  216. // If you wish to retain all compressed data so that the material
  217. // can be decompressed multiple times, possibly with different appearance
  218. // parameters, you should call "kdu_codestream::set_persistent" here.
  219. // There are a variety of other features which must be enabled at
  220. // this point if you want to take advantage of them. See the
  221. // descriptions appearing with the "kdu_codestream" interface functions
  222. // in "kdu_compressed.h" for an itemized account of these capabilities.
  223. switch (mode)
  224. {
  225. case MODE_FAST:
  226. mCodeStreamp->set_fast();
  227. break;
  228. case MODE_RESILIENT:
  229. mCodeStreamp->set_resilient();
  230. break;
  231. case MODE_FUSSY:
  232. mCodeStreamp->set_fussy();
  233. break;
  234. default:
  235. llassert(0);
  236. mCodeStreamp->set_fast();
  237. }
  238. kdu_dims dims;
  239. mCodeStreamp->get_dims(0,dims);
  240. S32 components = mCodeStreamp->get_num_components();
  241. if (components >= 3)
  242. { // Check that components have consistent dimensions (for PPM file)
  243. kdu_dims dims1; mCodeStreamp->get_dims(1,dims1);
  244. kdu_dims dims2; mCodeStreamp->get_dims(2,dims2);
  245. if ((dims1 != dims) || (dims2 != dims))
  246. {
  247. llerrs << "Components don't have matching dimensions!" << llendl;
  248. }
  249. }
  250. base.setSize(dims.size.x, dims.size.y, components);
  251. if (!keep_codestream)
  252. {
  253. mCodeStreamp->destroy();
  254. delete mCodeStreamp;
  255. mCodeStreamp = NULL;
  256. delete mInputp;
  257. mInputp = NULL;
  258. }
  259. }
  260. void LLImageJ2CKDU::cleanupCodeStream()
  261. {
  262. delete mInputp;
  263. mInputp = NULL;
  264. delete mDecodeState;
  265. mDecodeState = NULL;
  266. if (mCodeStreamp)
  267. {
  268. mCodeStreamp->destroy();
  269. delete mCodeStreamp;
  270. mCodeStreamp = NULL;
  271. }
  272. delete mTPosp;
  273. mTPosp = NULL;
  274. delete mTileIndicesp;
  275. mTileIndicesp = NULL;
  276. }
  277. BOOL LLImageJ2CKDU::initDecode(LLImageJ2C &base, LLImageRaw &raw_image, int discard_level, int* region)
  278. {
  279. return initDecode(base,raw_image,0.0f,MODE_FAST,0,4,discard_level,region);
  280. }
  281. BOOL LLImageJ2CKDU::initEncode(LLImageJ2C &base, LLImageRaw &raw_image, int blocks_size, int precincts_size, int levels)
  282. {
  283. mPrecinctsSize = precincts_size;
  284. if (mPrecinctsSize != -1)
  285. {
  286. mPrecinctsSize = get_lower_power_two(mPrecinctsSize,MAX_PRECINCT_SIZE);
  287. mPrecinctsSize = llmax(mPrecinctsSize,MIN_PRECINCT_SIZE);
  288. }
  289. mBlocksSize = blocks_size;
  290. if (mBlocksSize != -1)
  291. {
  292. mBlocksSize = get_lower_power_two(mBlocksSize,MAX_BLOCK_SIZE);
  293. mBlocksSize = llmax(mBlocksSize,MIN_BLOCK_SIZE);
  294. if (mPrecinctsSize != -1)
  295. {
  296. mBlocksSize = llmin(mBlocksSize,mPrecinctsSize); // blocks *must* be smaller than precincts
  297. }
  298. }
  299. mLevels = levels;
  300. if (mLevels != 0)
  301. {
  302. mLevels = llclamp(mLevels,MIN_DECOMPOSITION_LEVELS,MIN_DECOMPOSITION_LEVELS);
  303. }
  304. return TRUE;
  305. }
  306. BOOL LLImageJ2CKDU::initDecode(LLImageJ2C &base, LLImageRaw &raw_image, F32 decode_time, ECodeStreamMode mode, S32 first_channel, S32 max_channel_count, int discard_level, int* region)
  307. {
  308. base.resetLastError();
  309. // *FIX: kdu calls our callback function if there's an error, and then bombs.
  310. // To regain control, we throw an exception, and catch it here.
  311. try
  312. {
  313. base.updateRawDiscardLevel();
  314. setupCodeStream(base, TRUE, mode);
  315. mRawImagep = &raw_image;
  316. mCodeStreamp->change_appearance(false, true, false);
  317. // Apply loading discard level and cropping if required
  318. kdu_dims* region_kdu = NULL;
  319. if (region != NULL)
  320. {
  321. region_kdu = new kdu_dims;
  322. region_kdu->pos.x = region[0];
  323. region_kdu->pos.y = region[1];
  324. region_kdu->size.x = region[2] - region[0];
  325. region_kdu->size.y = region[3] - region[1];
  326. }
  327. int discard = (discard_level != -1 ? discard_level : base.getRawDiscardLevel());
  328. // Apply loading restrictions
  329. mCodeStreamp->apply_input_restrictions( first_channel, max_channel_count, discard, 0, region_kdu);
  330. // Clean-up
  331. if (region_kdu)
  332. {
  333. delete region_kdu;
  334. region_kdu = NULL;
  335. }
  336. // Resize raw_image according to the image to be decoded
  337. kdu_dims dims; mCodeStreamp->get_dims(0,dims);
  338. // *TODO: Use the real number of levels read from the file throughout the code instead of relying on an infered value from dimensions
  339. //S32 levels = mCodeStreamp->get_min_dwt_levels();
  340. S32 channels = base.getComponents() - first_channel;
  341. channels = llmin(channels,max_channel_count);
  342. raw_image.resize(dims.size.x, dims.size.y, channels);
  343. //llinfos << "j2c image dimension: width = " << dims.size.x << ", height = " << dims.size.y << ", channels = " << channels << ", levels = " << levels << llendl;
  344. if (!mTileIndicesp)
  345. {
  346. mTileIndicesp = new kdu_dims;
  347. }
  348. mCodeStreamp->get_valid_tiles(*mTileIndicesp);
  349. if (!mTPosp)
  350. {
  351. mTPosp = new kdu_coords;
  352. mTPosp->y = 0;
  353. mTPosp->x = 0;
  354. }
  355. }
  356. catch (const char* msg)
  357. {
  358. base.setLastError(ll_safe_string(msg));
  359. return FALSE;
  360. }
  361. catch (...)
  362. {
  363. base.setLastError("Unknown J2C error");
  364. return FALSE;
  365. }
  366. return TRUE;
  367. }
  368. // Returns TRUE to mean done, whether successful or not.
  369. BOOL LLImageJ2CKDU::decodeImpl(LLImageJ2C &base, LLImageRaw &raw_image, F32 decode_time, S32 first_channel, S32 max_channel_count)
  370. {
  371. ECodeStreamMode mode = MODE_FAST;
  372. LLTimer decode_timer;
  373. if (!mCodeStreamp)
  374. {
  375. if (!initDecode(base, raw_image, decode_time, mode, first_channel, max_channel_count))
  376. {
  377. // Initializing the J2C decode failed, bail out.
  378. cleanupCodeStream();
  379. return TRUE; // done
  380. }
  381. }
  382. // These can probably be grabbed from what's saved in the class.
  383. kdu_dims dims;
  384. mCodeStreamp->get_dims(0,dims);
  385. // Now we are ready to walk through the tiles processing them one-by-one.
  386. kdu_byte *buffer = raw_image.getData();
  387. while (mTPosp->y < mTileIndicesp->size.y)
  388. {
  389. while (mTPosp->x < mTileIndicesp->size.x)
  390. {
  391. try
  392. {
  393. if (!mDecodeState)
  394. {
  395. kdu_tile tile = mCodeStreamp->open_tile(*(mTPosp)+mTileIndicesp->pos);
  396. // Find the region of the buffer occupied by this
  397. // tile. Note that we have no control over
  398. // sub-sampling factors which might have been used
  399. // during compression and so it can happen that tiles
  400. // (at the image component level) actually have
  401. // different dimensions. For this reason, we cannot
  402. // figure out the buffer region occupied by a tile
  403. // directly from the tile indices. Instead, we query
  404. // the highest resolution of the first tile-component
  405. // concerning its location and size on the canvas --
  406. // the `dims' object already holds the location and
  407. // size of the entire image component on the same
  408. // canvas coordinate system. Comparing the two tells
  409. // us where the current tile is in the buffer.
  410. S32 channels = base.getComponents() - first_channel;
  411. if (channels > max_channel_count)
  412. {
  413. channels = max_channel_count;
  414. }
  415. kdu_resolution res = tile.access_component(0).access_resolution();
  416. kdu_dims tile_dims; res.get_dims(tile_dims);
  417. kdu_coords offset = tile_dims.pos - dims.pos;
  418. int row_gap = channels*dims.size.x; // inter-row separation
  419. kdu_byte *buf = buffer + offset.y*row_gap + offset.x*channels;
  420. mDecodeState = new LLKDUDecodeState(tile, buf, row_gap);
  421. }
  422. // Do the actual processing
  423. F32 remaining_time = decode_time - decode_timer.getElapsedTimeF32();
  424. // This is where we do the actual decode. If we run out of time, return false.
  425. if (mDecodeState->processTileDecode(remaining_time, (decode_time > 0.0f)))
  426. {
  427. delete mDecodeState;
  428. mDecodeState = NULL;
  429. }
  430. else
  431. {
  432. // Not finished decoding yet.
  433. // setLastError("Ran out of time while decoding");
  434. return FALSE;
  435. }
  436. }
  437. catch (const char* msg)
  438. {
  439. base.setLastError(ll_safe_string(msg));
  440. base.decodeFailed();
  441. cleanupCodeStream();
  442. return TRUE; // done
  443. }
  444. catch (...)
  445. {
  446. base.setLastError( "Unknown J2C error" );
  447. base.decodeFailed();
  448. cleanupCodeStream();
  449. return TRUE; // done
  450. }
  451. mTPosp->x++;
  452. }
  453. mTPosp->y++;
  454. mTPosp->x = 0;
  455. }
  456. cleanupCodeStream();
  457. return TRUE;
  458. }
  459. BOOL LLImageJ2CKDU::encodeImpl(LLImageJ2C &base, const LLImageRaw &raw_image, const char* comment_text, F32 encode_time, BOOL reversible)
  460. {
  461. // Declare and set simple arguments
  462. bool transpose = false;
  463. bool vflip = true;
  464. bool hflip = false;
  465. try
  466. {
  467. // Set up input image files
  468. siz_params siz;
  469. // Should set rate someplace here
  470. LLKDUMemIn mem_in(raw_image.getData(),
  471. raw_image.getDataSize(),
  472. raw_image.getWidth(),
  473. raw_image.getHeight(),
  474. raw_image.getComponents(),
  475. &siz);
  476. base.setSize(raw_image.getWidth(), raw_image.getHeight(), raw_image.getComponents());
  477. int num_components = raw_image.getComponents();
  478. siz.set(Scomponents,0,0,num_components);
  479. siz.set(Sdims,0,0,base.getHeight()); // Height of first image component
  480. siz.set(Sdims,0,1,base.getWidth()); // Width of first image component
  481. siz.set(Sprecision,0,0,8); // Image samples have original bit-depth of 8
  482. siz.set(Ssigned,0,0,false); // Image samples are originally unsigned
  483. kdu_params *siz_ref = &siz;
  484. siz_ref->finalize();
  485. siz_params transformed_siz; // Use this one to construct code-stream
  486. transformed_siz.copy_from(&siz,-1,-1,-1,0,transpose,false,false);
  487. // Construct the `kdu_codestream' object and parse all remaining arguments
  488. U32 max_output_size = base.getWidth()*base.getHeight()*base.getComponents();
  489. max_output_size = (max_output_size < 1000 ? 1000 : max_output_size);
  490. U8 *output_buffer = new U8[max_output_size];
  491. U32 output_size = 0; // Address updated by LLKDUMemTarget to give the final compressed buffer size
  492. LLKDUMemTarget output(output_buffer, output_size, max_output_size);
  493. kdu_codestream codestream;
  494. codestream.create(&transformed_siz,&output);
  495. if (comment_text)
  496. {
  497. // Set the comments for the codestream
  498. kdu_codestream_comment comment = codestream.add_comment();
  499. comment.put_text(comment_text);
  500. }
  501. // Set codestream options
  502. int num_layer_specs = 0;
  503. kdu_long layer_bytes[64];
  504. U32 max_bytes = 0;
  505. if (num_components >= 3)
  506. {
  507. // Note that we always use YCC and not YUV
  508. // *TODO: Verify this doesn't screws up reversible textures (like sculpties) as YCC is not reversible but YUV is...
  509. set_default_colour_weights(codestream.access_siz());
  510. }
  511. if (reversible)
  512. {
  513. codestream.access_siz()->parse_string("Creversible=yes");
  514. // *TODO: we should use yuv in reversible mode and one level since those images are small.
  515. // Don't turn this on now though as both create problems on decoding for the moment
  516. //codestream.access_siz()->parse_string("Clevels=1");
  517. //codestream.access_siz()->parse_string("Cycc=no");
  518. // If we're doing reversible (i.e. lossless compression), assumes we're not using quality layers.
  519. // *TODO: this is incorrect and unecessary. Try using the regular layer setting.
  520. codestream.access_siz()->parse_string("Clayers=1");
  521. num_layer_specs = 1;
  522. layer_bytes[0] = 0;
  523. }
  524. else
  525. {
  526. // Rate is the argument passed into the LLImageJ2C which
  527. // specifies the target compression rate. The default is 8:1.
  528. // Possibly if max_bytes < 500, we should just use the default setting?
  529. // *TODO: mRate is actually always 8:1 in the viewer. Test different values. Also force to reversible for small (< 500 bytes) textures.
  530. if (base.mRate != 0.f)
  531. {
  532. max_bytes = (U32)(base.mRate*base.getWidth()*base.getHeight()*base.getComponents());
  533. }
  534. else
  535. {
  536. max_bytes = (U32)(base.getWidth()*base.getHeight()*base.getComponents()*0.125);
  537. }
  538. const U32 min_bytes = FIRST_PACKET_SIZE;
  539. if (max_bytes > min_bytes)
  540. {
  541. U32 i;
  542. // This code is where we specify the target number of bytes for
  543. // each layer. Not sure if we should do this for small images
  544. // or not. The goal is to have this roughly align with
  545. // different quality levels that we decode at.
  546. for (i = min_bytes; i < max_bytes; i*=4)
  547. {
  548. if (i == min_bytes * 4)
  549. {
  550. i = 2000;
  551. }
  552. layer_bytes[num_layer_specs] = i;
  553. num_layer_specs++;
  554. }
  555. layer_bytes[num_layer_specs] = max_bytes;
  556. num_layer_specs++;
  557. std::string layer_string = llformat("Clayers=%d",num_layer_specs);
  558. codestream.access_siz()->parse_string(layer_string.c_str());
  559. }
  560. else
  561. {
  562. layer_bytes[0] = min_bytes;
  563. num_layer_specs = 1;
  564. std::string layer_string = llformat("Clayers=%d",num_layer_specs);
  565. codestream.access_siz()->parse_string(layer_string.c_str());
  566. }
  567. }
  568. // Set up data ordering, markers, etc... if precincts or blocks specified
  569. if ((mBlocksSize != -1) || (mPrecinctsSize != -1))
  570. {
  571. if (mPrecinctsSize != -1)
  572. {
  573. std::string precincts_string = llformat("Cprecincts={%d,%d}",mPrecinctsSize,mPrecinctsSize);
  574. codestream.access_siz()->parse_string(precincts_string.c_str());
  575. }
  576. if (mBlocksSize != -1)
  577. {
  578. std::string blocks_string = llformat("Cblk={%d,%d}",mBlocksSize,mBlocksSize);
  579. codestream.access_siz()->parse_string(blocks_string.c_str());
  580. }
  581. std::string ordering_string = llformat("Corder=RPCL");
  582. codestream.access_siz()->parse_string(ordering_string.c_str());
  583. std::string PLT_string = llformat("ORGgen_plt=yes");
  584. codestream.access_siz()->parse_string(PLT_string.c_str());
  585. std::string Parts_string = llformat("ORGtparts=R");
  586. codestream.access_siz()->parse_string(Parts_string.c_str());
  587. }
  588. if (mLevels != 0)
  589. {
  590. std::string levels_string = llformat("Clevels=%d",mLevels);
  591. codestream.access_siz()->parse_string(levels_string.c_str());
  592. }
  593. codestream.access_siz()->finalize_all();
  594. codestream.change_appearance(transpose,vflip,hflip);
  595. // Now we are ready for sample data processing.
  596. kdc_flow_control *tile = new kdc_flow_control(&mem_in,codestream);
  597. bool done = false;
  598. while (!done)
  599. {
  600. // Process line by line
  601. if (tile->advance_components())
  602. {
  603. tile->process_components();
  604. }
  605. else
  606. {
  607. done = true;
  608. }
  609. }
  610. // Produce the compressed output
  611. codestream.flush(layer_bytes,num_layer_specs);
  612. // Cleanup
  613. delete tile;
  614. codestream.destroy();
  615. // Now that we're done encoding, create the new data buffer for the compressed
  616. // image and stick it there.
  617. base.copyData(output_buffer, output_size);
  618. base.updateData(); // set width, height
  619. delete[] output_buffer;
  620. }
  621. catch(const char* msg)
  622. {
  623. base.setLastError(ll_safe_string(msg));
  624. return FALSE;
  625. }
  626. catch( ... )
  627. {
  628. base.setLastError( "Unknown J2C error" );
  629. return FALSE;
  630. }
  631. return TRUE;
  632. }
  633. BOOL LLImageJ2CKDU::getMetadata(LLImageJ2C &base)
  634. {
  635. // *FIX: kdu calls our callback function if there's an error, and
  636. // then bombs. To regain control, we throw an exception, and
  637. // catch it here.
  638. try
  639. {
  640. setupCodeStream(base, FALSE, MODE_FAST);
  641. return TRUE;
  642. }
  643. catch (const char* msg)
  644. {
  645. base.setLastError(ll_safe_string(msg));
  646. return FALSE;
  647. }
  648. catch (...)
  649. {
  650. base.setLastError( "Unknown J2C error" );
  651. return FALSE;
  652. }
  653. }
  654. void set_default_colour_weights(kdu_params *siz)
  655. {
  656. kdu_params *cod = siz->access_cluster(COD_params);
  657. assert(cod != NULL);
  658. bool can_use_ycc = true;
  659. bool rev0 = false;
  660. int depth0 = 0, sub_x0 = 1, sub_y0 = 1;
  661. for (int c = 0; c < 3; c++)
  662. {
  663. int depth = 0; siz->get(Sprecision,c,0,depth);
  664. int sub_y = 1; siz->get(Ssampling,c,0,sub_y);
  665. int sub_x = 1; siz->get(Ssampling,c,1,sub_x);
  666. kdu_params *coc = cod->access_relation(-1,c);
  667. bool rev = false; coc->get(Creversible,0,0,rev);
  668. if (c == 0)
  669. {
  670. rev0 = rev; depth0 = depth; sub_x0 = sub_x; sub_y0 = sub_y;
  671. }
  672. else if ((rev != rev0) || (depth != depth0) ||
  673. (sub_x != sub_x0) || (sub_y != sub_y0))
  674. {
  675. can_use_ycc = false;
  676. }
  677. }
  678. if (!can_use_ycc)
  679. {
  680. return;
  681. }
  682. bool use_ycc;
  683. if (!cod->get(Cycc,0,0,use_ycc))
  684. {
  685. cod->set(Cycc,0,0,use_ycc=true);
  686. }
  687. if (!use_ycc)
  688. {
  689. return;
  690. }
  691. float weight;
  692. if (cod->get(Clev_weights,0,0,weight) || cod->get(Cband_weights,0,0,weight))
  693. {
  694. // Weights already specified explicitly -> nothing to do
  695. return;
  696. }
  697. // These example weights are adapted from numbers generated by Marcus Nadenau
  698. // at EPFL, for a viewing distance of 15 cm and a display resolution of
  699. // 300 DPI.
  700. cod->parse_string("Cband_weights:C0="
  701. "{0.0901},{0.2758},{0.2758},"
  702. "{0.7018},{0.8378},{0.8378},{1}");
  703. cod->parse_string("Cband_weights:C1="
  704. "{0.0263},{0.0863},{0.0863},"
  705. "{0.1362},{0.2564},{0.2564},"
  706. "{0.3346},{0.4691},{0.4691},"
  707. "{0.5444},{0.6523},{0.6523},"
  708. "{0.7078},{0.7797},{0.7797},{1}");
  709. cod->parse_string("Cband_weights:C2="
  710. "{0.0773},{0.1835},{0.1835},"
  711. "{0.2598},{0.4130},{0.4130},"
  712. "{0.5040},{0.6464},{0.6464},"
  713. "{0.7220},{0.8254},{0.8254},"
  714. "{0.8769},{0.9424},{0.9424},{1}");
  715. }
  716. /******************************************************************************/
  717. /* transfer_bytes */
  718. /******************************************************************************/
  719. void transfer_bytes(kdu_byte *dest, kdu_line_buf &src, int gap, int precision)
  720. /* Transfers source samples from the supplied line buffer into the output
  721. byte buffer, spacing successive output samples apart by `gap' bytes
  722. (to allow for interleaving of colour components). The function performs
  723. all necessary level shifting, type conversion, rounding and truncation. */
  724. {
  725. int width = src.get_width();
  726. if (src.get_buf32() != NULL)
  727. { // Decompressed samples have a 32-bit representation (integer or float)
  728. assert(precision >= 8); // Else would have used 16 bit representation
  729. kdu_sample32 *sp = src.get_buf32();
  730. if (!src.is_absolute())
  731. { // Transferring normalized floating point data.
  732. float scale16 = (float)(1<<16);
  733. kdu_int32 val;
  734. for (; width > 0; width--, sp++, dest+=gap)
  735. {
  736. val = (kdu_int32)(sp->fval*scale16);
  737. val = (val+128)>>8; // May be faster than true rounding
  738. val += 128;
  739. if (val & ((-1)<<8))
  740. {
  741. val = (val < 0 ? 0 : 255);
  742. }
  743. *dest = (kdu_byte) val;
  744. }
  745. }
  746. else
  747. { // Transferring 32-bit absolute integers.
  748. kdu_int32 val;
  749. kdu_int32 downshift = precision-8;
  750. kdu_int32 offset = (1<<downshift)>>1;
  751. for (; width > 0; width--, sp++, dest+=gap)
  752. {
  753. val = sp->ival;
  754. val = (val+offset)>>downshift;
  755. val += 128;
  756. if (val & ((-1)<<8))
  757. {
  758. val = (val < 0 ? 0 : 255);
  759. }
  760. *dest = (kdu_byte) val;
  761. }
  762. }
  763. }
  764. else
  765. { // Source data is 16 bits.
  766. kdu_sample16 *sp = src.get_buf16();
  767. if (!src.is_absolute())
  768. { // Transferring 16-bit fixed point quantities
  769. kdu_int16 val;
  770. if (precision >= 8)
  771. { // Can essentially ignore the bit-depth.
  772. for (; width > 0; width--, sp++, dest+=gap)
  773. {
  774. val = sp->ival;
  775. val += (1<<(KDU_FIX_POINT-8))>>1;
  776. val >>= (KDU_FIX_POINT-8);
  777. val += 128;
  778. if (val & ((-1)<<8))
  779. {
  780. val = (val < 0 ? 0 : 255);
  781. }
  782. *dest = (kdu_byte) val;
  783. }
  784. }
  785. else
  786. { // Need to force zeros into one or more least significant bits.
  787. kdu_int16 downshift = KDU_FIX_POINT-precision;
  788. kdu_int16 upshift = 8-precision;
  789. kdu_int16 offset = 1<<(downshift-1);
  790. for (; width > 0; width--, sp++, dest+=gap)
  791. {
  792. val = sp->ival;
  793. val = (val+offset)>>downshift;
  794. val <<= upshift;
  795. val += 128;
  796. if (val & ((-1)<<8))
  797. {
  798. val = (val < 0 ? 0 : 256 - (1<<upshift));
  799. }
  800. *dest = (kdu_byte) val;
  801. }
  802. }
  803. }
  804. else
  805. { // Transferring 16-bit absolute integers.
  806. kdu_int16 val;
  807. if (precision >= 8)
  808. {
  809. kdu_int16 downshift = precision-8;
  810. kdu_int16 offset = (1<<downshift)>>1;
  811. for (; width > 0; width--, sp++, dest+=gap)
  812. {
  813. val = sp->ival;
  814. val = (val+offset)>>downshift;
  815. val += 128;
  816. if (val & ((-1)<<8))
  817. {
  818. val = (val < 0 ? 0 : 255);
  819. }
  820. *dest = (kdu_byte) val;
  821. }
  822. }
  823. else
  824. {
  825. kdu_int16 upshift = 8-precision;
  826. for (; width > 0; width--, sp++, dest+=gap)
  827. {
  828. val = sp->ival;
  829. val <<= upshift;
  830. val += 128;
  831. if (val & ((-1)<<8))
  832. {
  833. val = (val < 0 ? 0 : 256 - (1<<upshift));
  834. }
  835. *dest = (kdu_byte) val;
  836. }
  837. }
  838. }
  839. }
  840. }
  841. LLKDUDecodeState::LLKDUDecodeState(kdu_tile tile, kdu_byte *buf, S32 row_gap)
  842. {
  843. S32 c;
  844. mTile = tile;
  845. mBuf = buf;
  846. mRowGap = row_gap;
  847. mNumComponents = tile.get_num_components();
  848. llassert(mNumComponents <= 4);
  849. mUseYCC = tile.get_ycc();
  850. for (c = 0; c < 4; ++c)
  851. {
  852. mReversible[c] = false;
  853. mBitDepths[c] = 0;
  854. }
  855. // Open tile-components and create processing engines and resources
  856. for (c = 0; c < mNumComponents; c++)
  857. {
  858. mComps[c] = mTile.access_component(c);
  859. mReversible[c] = mComps[c].get_reversible();
  860. mBitDepths[c] = mComps[c].get_bit_depth();
  861. kdu_resolution res = mComps[c].access_resolution(); // Get top resolution
  862. kdu_dims comp_dims; res.get_dims(comp_dims);
  863. if (c == 0)
  864. {
  865. mDims = comp_dims;
  866. }
  867. else
  868. {
  869. llassert(mDims == comp_dims); // Safety check; the caller has ensured this
  870. }
  871. bool use_shorts = (mComps[c].get_bit_depth(true) <= 16);
  872. mLines[c].pre_create(&mAllocator,mDims.size.x,mReversible[c],use_shorts);
  873. if (res.which() == 0) // No DWT levels used
  874. {
  875. mEngines[c] = kdu_decoder(res.access_subband(LL_BAND),&mAllocator,use_shorts);
  876. }
  877. else
  878. {
  879. mEngines[c] = kdu_synthesis(res,&mAllocator,use_shorts);
  880. }
  881. }
  882. mAllocator.finalize(); // Actually creates buffering resources
  883. for (c = 0; c < mNumComponents; c++)
  884. {
  885. mLines[c].create(); // Grabs resources from the allocator.
  886. }
  887. }
  888. LLKDUDecodeState::~LLKDUDecodeState()
  889. {
  890. // Cleanup
  891. for (S32 c = 0; c < mNumComponents; c++)
  892. {
  893. mEngines[c].destroy(); // engines are interfaces; no default destructors
  894. }
  895. mTile.close();
  896. }
  897. BOOL LLKDUDecodeState::processTileDecode(F32 decode_time, BOOL limit_time)
  898. /* Decompresses a tile, writing the data into the supplied byte buffer.
  899. The buffer contains interleaved image components, if there are any.
  900. Although you may think of the buffer as belonging entirely to this tile,
  901. the `buf' pointer may actually point into a larger buffer representing
  902. multiple tiles. For this reason, `row_gap' is needed to identify the
  903. separation between consecutive rows in the real buffer. */
  904. {
  905. S32 c;
  906. // Now walk through the lines of the buffer, recovering them from the
  907. // relevant tile-component processing engines.
  908. LLTimer decode_timer;
  909. while (mDims.size.y--)
  910. {
  911. for (c = 0; c < mNumComponents; c++)
  912. {
  913. mEngines[c].pull(mLines[c],true);
  914. }
  915. if ((mNumComponents >= 3) && mUseYCC)
  916. {
  917. kdu_convert_ycc_to_rgb(mLines[0],mLines[1],mLines[2]);
  918. }
  919. for (c = 0; c < mNumComponents; c++)
  920. {
  921. transfer_bytes(mBuf+c,mLines[c],mNumComponents,mBitDepths[c]);
  922. }
  923. mBuf += mRowGap;
  924. if (mDims.size.y % 10)
  925. {
  926. if (limit_time && decode_timer.getElapsedTimeF32() > decode_time)
  927. {
  928. return FALSE;
  929. }
  930. }
  931. }
  932. return TRUE;
  933. }
  934. // kdc_flow_control
  935. kdc_flow_control::kdc_flow_control (kdu_image_in_base *img_in, kdu_codestream codestream)
  936. {
  937. int n;
  938. this->codestream = codestream;
  939. codestream.get_valid_tiles(valid_tile_indices);
  940. tile_idx = valid_tile_indices.pos;
  941. tile = codestream.open_tile(tile_idx,NULL);
  942. // Set up the individual components
  943. num_components = codestream.get_num_components(true);
  944. components = new kdc_component_flow_control[num_components];
  945. count_delta = 0;
  946. kdc_component_flow_control *comp = components;
  947. for (n = 0; n < num_components; n++, comp++)
  948. {
  949. comp->line = NULL;
  950. comp->reader = img_in;
  951. kdu_coords subsampling;
  952. codestream.get_subsampling(n,subsampling,true);
  953. kdu_dims dims;
  954. codestream.get_tile_dims(tile_idx,n,dims,true);
  955. comp->vert_subsampling = subsampling.y;
  956. if ((n == 0) || (comp->vert_subsampling < count_delta))
  957. {
  958. count_delta = comp->vert_subsampling;
  959. }
  960. comp->ratio_counter = 0;
  961. comp->remaining_lines = comp->initial_lines = dims.size.y;
  962. }
  963. assert(num_components >= 0);
  964. tile.set_components_of_interest(num_components);
  965. max_buffer_memory = engine.create(codestream,tile,false,NULL,false,1,NULL,NULL,false);
  966. }
  967. kdc_flow_control::~kdc_flow_control()
  968. {
  969. if (components != NULL)
  970. {
  971. delete[] components;
  972. }
  973. if (engine.exists())
  974. {
  975. engine.destroy();
  976. }
  977. }
  978. bool kdc_flow_control::advance_components()
  979. {
  980. bool found_line = false;
  981. while (!found_line)
  982. {
  983. bool all_done = true;
  984. kdc_component_flow_control *comp = components;
  985. for (int n = 0; n < num_components; n++, comp++)
  986. {
  987. assert(comp->ratio_counter >= 0);
  988. if (comp->remaining_lines > 0)
  989. {
  990. all_done = false;
  991. comp->ratio_counter -= count_delta;
  992. if (comp->ratio_counter < 0)
  993. {
  994. found_line = true;
  995. comp->line = engine.exchange_line(n,NULL,NULL);
  996. assert(comp->line != NULL);
  997. if (comp->line->get_width())
  998. {
  999. comp->reader->get(n,*(comp->line),0);
  1000. }
  1001. }
  1002. }
  1003. }
  1004. if (all_done)
  1005. {
  1006. return false;
  1007. }
  1008. }
  1009. return true;
  1010. }
  1011. void kdc_flow_control::process_components()
  1012. {
  1013. kdc_component_flow_control *comp = components;
  1014. for (int n = 0; n < num_components; n++, comp++)
  1015. {
  1016. if (comp->ratio_counter < 0)
  1017. {
  1018. comp->ratio_counter += comp->vert_subsampling;
  1019. assert(comp->ratio_counter >= 0);
  1020. assert(comp->remaining_lines > 0);
  1021. comp->remaining_lines--;
  1022. assert(comp->line != NULL);
  1023. engine.exchange_line(n,comp->line,NULL);
  1024. comp->line = NULL;
  1025. }
  1026. }
  1027. }