nsJPEGDecoder.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  2. *
  3. * This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #include "ImageLogging.h" // Must appear first.
  7. #include "nsJPEGDecoder.h"
  8. #include <cstdint>
  9. #include "imgFrame.h"
  10. #include "Orientation.h"
  11. #include "EXIF.h"
  12. #include "nsIInputStream.h"
  13. #include "nspr.h"
  14. #include "nsCRT.h"
  15. #include "gfxColor.h"
  16. #include "jerror.h"
  17. #include "gfxPlatform.h"
  18. #include "mozilla/EndianUtils.h"
  19. #include "mozilla/Telemetry.h"
  20. extern "C" {
  21. #include "iccjpeg.h"
  22. }
  23. #if MOZ_BIG_ENDIAN
  24. #define MOZ_JCS_EXT_NATIVE_ENDIAN_XRGB JCS_EXT_XRGB
  25. #else
  26. #define MOZ_JCS_EXT_NATIVE_ENDIAN_XRGB JCS_EXT_BGRX
  27. #endif
  28. static void cmyk_convert_rgb(JSAMPROW row, JDIMENSION width);
  29. namespace mozilla {
  30. namespace image {
  31. static mozilla::LazyLogModule sJPEGLog("JPEGDecoder");
  32. static mozilla::LazyLogModule sJPEGDecoderAccountingLog("JPEGDecoderAccounting");
  33. static qcms_profile*
  34. GetICCProfile(struct jpeg_decompress_struct& info)
  35. {
  36. JOCTET* profilebuf;
  37. uint32_t profileLength;
  38. qcms_profile* profile = nullptr;
  39. if (read_icc_profile(&info, &profilebuf, &profileLength)) {
  40. profile = qcms_profile_from_memory(profilebuf, profileLength);
  41. free(profilebuf);
  42. }
  43. return profile;
  44. }
  45. METHODDEF(void) init_source (j_decompress_ptr jd);
  46. METHODDEF(boolean) fill_input_buffer (j_decompress_ptr jd);
  47. METHODDEF(void) skip_input_data (j_decompress_ptr jd, long num_bytes);
  48. METHODDEF(void) term_source (j_decompress_ptr jd);
  49. METHODDEF(void) my_error_exit (j_common_ptr cinfo);
  50. // Normal JFIF markers can't have more bytes than this.
  51. #define MAX_JPEG_MARKER_LENGTH (((uint32_t)1 << 16) - 1)
  52. nsJPEGDecoder::nsJPEGDecoder(RasterImage* aImage,
  53. Decoder::DecodeStyle aDecodeStyle)
  54. : Decoder(aImage)
  55. , mLexer(Transition::ToUnbuffered(State::FINISHED_JPEG_DATA,
  56. State::JPEG_DATA,
  57. SIZE_MAX),
  58. Transition::TerminateSuccess())
  59. , mDecodeStyle(aDecodeStyle)
  60. , mSampleSize(0)
  61. {
  62. mState = JPEG_HEADER;
  63. mReading = true;
  64. mImageData = nullptr;
  65. mBytesToSkip = 0;
  66. memset(&mInfo, 0, sizeof(jpeg_decompress_struct));
  67. memset(&mSourceMgr, 0, sizeof(mSourceMgr));
  68. mInfo.client_data = (void*)this;
  69. mSegment = nullptr;
  70. mSegmentLen = 0;
  71. mBackBuffer = nullptr;
  72. mBackBufferLen = mBackBufferSize = mBackBufferUnreadLen = 0;
  73. mInProfile = nullptr;
  74. mTransform = nullptr;
  75. mCMSMode = 0;
  76. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  77. ("nsJPEGDecoder::nsJPEGDecoder: Creating JPEG decoder %p",
  78. this));
  79. }
  80. nsJPEGDecoder::~nsJPEGDecoder()
  81. {
  82. // Step 8: Release JPEG decompression object
  83. mInfo.src = nullptr;
  84. jpeg_destroy_decompress(&mInfo);
  85. PR_FREEIF(mBackBuffer);
  86. if (mTransform) {
  87. qcms_transform_release(mTransform);
  88. }
  89. if (mInProfile) {
  90. qcms_profile_release(mInProfile);
  91. }
  92. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  93. ("nsJPEGDecoder::~nsJPEGDecoder: Destroying JPEG decoder %p",
  94. this));
  95. }
  96. Maybe<Telemetry::ID>
  97. nsJPEGDecoder::SpeedHistogram() const
  98. {
  99. return Some(Telemetry::IMAGE_DECODE_SPEED_JPEG);
  100. }
  101. nsresult
  102. nsJPEGDecoder::InitInternal()
  103. {
  104. mCMSMode = gfxPlatform::GetCMSMode();
  105. if (GetSurfaceFlags() & SurfaceFlags::NO_COLORSPACE_CONVERSION) {
  106. mCMSMode = eCMSMode_Off;
  107. }
  108. // We set up the normal JPEG error routines, then override error_exit.
  109. mInfo.err = jpeg_std_error(&mErr.pub);
  110. // mInfo.err = jpeg_std_error(&mErr.pub);
  111. mErr.pub.error_exit = my_error_exit;
  112. // Establish the setjmp return context for my_error_exit to use.
  113. if (setjmp(mErr.setjmp_buffer)) {
  114. // If we get here, the JPEG code has signaled an error, and initialization
  115. // has failed.
  116. return NS_ERROR_FAILURE;
  117. }
  118. // Step 1: allocate and initialize JPEG decompression object
  119. jpeg_create_decompress(&mInfo);
  120. // Set the source manager
  121. mInfo.src = &mSourceMgr;
  122. // Step 2: specify data source (eg, a file)
  123. // Setup callback functions.
  124. mSourceMgr.init_source = init_source;
  125. mSourceMgr.fill_input_buffer = fill_input_buffer;
  126. mSourceMgr.skip_input_data = skip_input_data;
  127. mSourceMgr.resync_to_restart = jpeg_resync_to_restart;
  128. mSourceMgr.term_source = term_source;
  129. // Record app markers for ICC data
  130. for (uint32_t m = 0; m < 16; m++) {
  131. jpeg_save_markers(&mInfo, JPEG_APP0 + m, 0xFFFF);
  132. }
  133. return NS_OK;
  134. }
  135. nsresult
  136. nsJPEGDecoder::FinishInternal()
  137. {
  138. // If we're not in any sort of error case, force our state to JPEG_DONE.
  139. if ((mState != JPEG_DONE && mState != JPEG_SINK_NON_JPEG_TRAILER) &&
  140. (mState != JPEG_ERROR) &&
  141. !IsMetadataDecode()) {
  142. mState = JPEG_DONE;
  143. }
  144. return NS_OK;
  145. }
  146. LexerResult
  147. nsJPEGDecoder::DoDecode(SourceBufferIterator& aIterator, IResumable* aOnResume)
  148. {
  149. MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!");
  150. return mLexer.Lex(aIterator, aOnResume,
  151. [=](State aState, const char* aData, size_t aLength) {
  152. switch (aState) {
  153. case State::JPEG_DATA:
  154. return ReadJPEGData(aData, aLength);
  155. case State::FINISHED_JPEG_DATA:
  156. return FinishedJPEGData();
  157. }
  158. MOZ_CRASH("Unknown State");
  159. });
  160. }
  161. LexerTransition<nsJPEGDecoder::State>
  162. nsJPEGDecoder::ReadJPEGData(const char* aData, size_t aLength)
  163. {
  164. mSegment = reinterpret_cast<const JOCTET*>(aData);
  165. mSegmentLen = aLength;
  166. // Return here if there is a fatal error within libjpeg.
  167. nsresult error_code;
  168. // This cast to nsresult makes sense because setjmp() returns whatever we
  169. // passed to longjmp(), which was actually an nsresult.
  170. if ((error_code = static_cast<nsresult>(setjmp(mErr.setjmp_buffer))) != NS_OK) {
  171. if (error_code == NS_ERROR_FAILURE) {
  172. // Error due to corrupt data. Make sure that we don't feed any more data
  173. // to libjpeg-turbo.
  174. mState = JPEG_SINK_NON_JPEG_TRAILER;
  175. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  176. ("} (setjmp returned NS_ERROR_FAILURE)"));
  177. } else {
  178. // Error for another reason. (Possibly OOM.)
  179. mState = JPEG_ERROR;
  180. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  181. ("} (setjmp returned an error)"));
  182. }
  183. return Transition::TerminateFailure();
  184. }
  185. MOZ_LOG(sJPEGLog, LogLevel::Debug,
  186. ("[this=%p] nsJPEGDecoder::Write -- processing JPEG data\n", this));
  187. switch (mState) {
  188. case JPEG_HEADER: {
  189. LOG_SCOPE((mozilla::LogModule*)sJPEGLog, "nsJPEGDecoder::Write -- entering JPEG_HEADER"
  190. " case");
  191. // Step 3: read file parameters with jpeg_read_header()
  192. if (jpeg_read_header(&mInfo, TRUE) == JPEG_SUSPENDED) {
  193. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  194. ("} (JPEG_SUSPENDED)"));
  195. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  196. }
  197. // If we have a sample size specified for -moz-sample-size, use it.
  198. if (mSampleSize > 0) {
  199. mInfo.scale_num = 1;
  200. mInfo.scale_denom = mSampleSize;
  201. }
  202. // Used to set up image size so arrays can be allocated
  203. jpeg_calc_output_dimensions(&mInfo);
  204. // Post our size to the superclass
  205. PostSize(mInfo.output_width, mInfo.output_height,
  206. ReadOrientationFromEXIF());
  207. if (HasError()) {
  208. // Setting the size led to an error.
  209. mState = JPEG_ERROR;
  210. return Transition::TerminateFailure();
  211. }
  212. // If we're doing a metadata decode, we're done.
  213. if (IsMetadataDecode()) {
  214. return Transition::TerminateSuccess();
  215. }
  216. // We're doing a full decode.
  217. if (mCMSMode != eCMSMode_Off &&
  218. (mInProfile = GetICCProfile(mInfo)) != nullptr) {
  219. uint32_t profileSpace = qcms_profile_get_color_space(mInProfile);
  220. bool mismatch = false;
  221. #ifdef DEBUG_tor
  222. fprintf(stderr, "JPEG profileSpace: 0x%08X\n", profileSpace);
  223. #endif
  224. switch (mInfo.jpeg_color_space) {
  225. case JCS_GRAYSCALE:
  226. if (profileSpace == icSigRgbData) {
  227. mInfo.out_color_space = JCS_RGB;
  228. } else if (profileSpace != icSigGrayData) {
  229. mismatch = true;
  230. }
  231. break;
  232. case JCS_RGB:
  233. if (profileSpace != icSigRgbData) {
  234. mismatch = true;
  235. }
  236. break;
  237. case JCS_YCbCr:
  238. if (profileSpace == icSigRgbData) {
  239. mInfo.out_color_space = JCS_RGB;
  240. } else {
  241. // qcms doesn't support ycbcr
  242. mismatch = true;
  243. }
  244. break;
  245. case JCS_CMYK:
  246. case JCS_YCCK:
  247. // qcms doesn't support cmyk
  248. mismatch = true;
  249. break;
  250. default:
  251. mState = JPEG_ERROR;
  252. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  253. ("} (unknown colorpsace (1))"));
  254. return Transition::TerminateFailure();
  255. }
  256. if (!mismatch) {
  257. qcms_data_type type;
  258. switch (mInfo.out_color_space) {
  259. case JCS_GRAYSCALE:
  260. type = QCMS_DATA_GRAY_8;
  261. break;
  262. case JCS_RGB:
  263. type = QCMS_DATA_RGB_8;
  264. break;
  265. default:
  266. mState = JPEG_ERROR;
  267. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  268. ("} (unknown colorpsace (2))"));
  269. return Transition::TerminateFailure();
  270. }
  271. #if 0
  272. // We don't currently support CMYK profiles. The following
  273. // code dealt with lcms types. Add something like this
  274. // back when we gain support for CMYK.
  275. // Adobe Photoshop writes YCCK/CMYK files with inverted data
  276. if (mInfo.out_color_space == JCS_CMYK) {
  277. type |= FLAVOR_SH(mInfo.saw_Adobe_marker ? 1 : 0);
  278. }
  279. #endif
  280. if (gfxPlatform::GetCMSOutputProfile()) {
  281. // Calculate rendering intent.
  282. int intent = gfxPlatform::GetRenderingIntent();
  283. if (intent == -1) {
  284. intent = qcms_profile_get_rendering_intent(mInProfile);
  285. }
  286. // Create the color management transform.
  287. mTransform = qcms_transform_create(mInProfile,
  288. type,
  289. gfxPlatform::GetCMSOutputProfile(),
  290. QCMS_DATA_RGB_8,
  291. (qcms_intent)intent);
  292. }
  293. } else {
  294. #ifdef DEBUG_tor
  295. fprintf(stderr, "ICM profile colorspace mismatch\n");
  296. #endif
  297. }
  298. }
  299. if (!mTransform) {
  300. switch (mInfo.jpeg_color_space) {
  301. case JCS_GRAYSCALE:
  302. case JCS_RGB:
  303. case JCS_YCbCr:
  304. // if we're not color managing we can decode directly to
  305. // MOZ_JCS_EXT_NATIVE_ENDIAN_XRGB
  306. if (mCMSMode != eCMSMode_All) {
  307. mInfo.out_color_space = MOZ_JCS_EXT_NATIVE_ENDIAN_XRGB;
  308. mInfo.out_color_components = 4;
  309. } else {
  310. mInfo.out_color_space = JCS_RGB;
  311. }
  312. break;
  313. case JCS_CMYK:
  314. case JCS_YCCK:
  315. // libjpeg can convert from YCCK to CMYK, but not to RGB
  316. mInfo.out_color_space = JCS_CMYK;
  317. break;
  318. default:
  319. mState = JPEG_ERROR;
  320. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  321. ("} (unknown colorpsace (3))"));
  322. return Transition::TerminateFailure();
  323. }
  324. }
  325. // Don't allocate a giant and superfluous memory buffer
  326. // when not doing a progressive decode.
  327. mInfo.buffered_image = mDecodeStyle == PROGRESSIVE &&
  328. jpeg_has_multiple_scans(&mInfo);
  329. MOZ_ASSERT(!mImageData, "Already have a buffer allocated?");
  330. nsresult rv = AllocateFrame(OutputSize(), FullOutputFrame(),
  331. SurfaceFormat::B8G8R8X8);
  332. if (NS_FAILED(rv)) {
  333. mState = JPEG_ERROR;
  334. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  335. ("} (could not initialize image frame)"));
  336. return Transition::TerminateFailure();
  337. }
  338. MOZ_ASSERT(mImageData, "Should have a buffer now");
  339. if (mDownscaler) {
  340. nsresult rv = mDownscaler->BeginFrame(Size(), Nothing(),
  341. mImageData,
  342. /* aHasAlpha = */ false);
  343. if (NS_FAILED(rv)) {
  344. mState = JPEG_ERROR;
  345. return Transition::TerminateFailure();
  346. }
  347. }
  348. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  349. (" JPEGDecoderAccounting: nsJPEGDecoder::"
  350. "Write -- created image frame with %ux%u pixels",
  351. mInfo.output_width, mInfo.output_height));
  352. mState = JPEG_START_DECOMPRESS;
  353. MOZ_FALLTHROUGH; // to start decompressing.
  354. }
  355. case JPEG_START_DECOMPRESS: {
  356. LOG_SCOPE((mozilla::LogModule*)sJPEGLog, "nsJPEGDecoder::Write -- entering"
  357. " JPEG_START_DECOMPRESS case");
  358. // Step 4: set parameters for decompression
  359. // FIXME -- Should reset dct_method and dither mode
  360. // for final pass of progressive JPEG
  361. mInfo.dct_method = JDCT_ISLOW;
  362. mInfo.dither_mode = JDITHER_FS;
  363. mInfo.do_fancy_upsampling = TRUE;
  364. mInfo.enable_2pass_quant = FALSE;
  365. mInfo.do_block_smoothing = TRUE;
  366. // Step 5: Start decompressor
  367. if (jpeg_start_decompress(&mInfo) == FALSE) {
  368. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  369. ("} (I/O suspension after jpeg_start_decompress())"));
  370. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  371. }
  372. // If this is a progressive JPEG ...
  373. mState = mInfo.buffered_image ?
  374. JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
  375. MOZ_FALLTHROUGH; // to decompress sequential JPEG.
  376. }
  377. case JPEG_DECOMPRESS_SEQUENTIAL: {
  378. if (mState == JPEG_DECOMPRESS_SEQUENTIAL) {
  379. LOG_SCOPE((mozilla::LogModule*)sJPEGLog, "nsJPEGDecoder::Write -- "
  380. "JPEG_DECOMPRESS_SEQUENTIAL case");
  381. bool suspend;
  382. OutputScanlines(&suspend);
  383. if (suspend) {
  384. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  385. ("} (I/O suspension after OutputScanlines() - SEQUENTIAL)"));
  386. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  387. }
  388. // If we've completed image output ...
  389. NS_ASSERTION(mInfo.output_scanline == mInfo.output_height,
  390. "We didn't process all of the data!");
  391. mState = JPEG_DONE;
  392. }
  393. MOZ_FALLTHROUGH; // to decompress progressive JPEG.
  394. }
  395. case JPEG_DECOMPRESS_PROGRESSIVE: {
  396. if (mState == JPEG_DECOMPRESS_PROGRESSIVE) {
  397. LOG_SCOPE((mozilla::LogModule*)sJPEGLog,
  398. "nsJPEGDecoder::Write -- JPEG_DECOMPRESS_PROGRESSIVE case");
  399. int status;
  400. do {
  401. status = jpeg_consume_input(&mInfo);
  402. } while ((status != JPEG_SUSPENDED) &&
  403. (status != JPEG_REACHED_EOI));
  404. for (;;) {
  405. if (mInfo.output_scanline == 0) {
  406. int scan = mInfo.input_scan_number;
  407. // if we haven't displayed anything yet (output_scan_number==0)
  408. // and we have enough data for a complete scan, force output
  409. // of the last full scan
  410. if ((mInfo.output_scan_number == 0) &&
  411. (scan > 1) &&
  412. (status != JPEG_REACHED_EOI))
  413. scan--;
  414. if (!jpeg_start_output(&mInfo, scan)) {
  415. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  416. ("} (I/O suspension after jpeg_start_output() -"
  417. " PROGRESSIVE)"));
  418. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  419. }
  420. }
  421. if (mInfo.output_scanline == 0xffffff) {
  422. mInfo.output_scanline = 0;
  423. }
  424. bool suspend;
  425. OutputScanlines(&suspend);
  426. if (suspend) {
  427. if (mInfo.output_scanline == 0) {
  428. // didn't manage to read any lines - flag so we don't call
  429. // jpeg_start_output() multiple times for the same scan
  430. mInfo.output_scanline = 0xffffff;
  431. }
  432. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  433. ("} (I/O suspension after OutputScanlines() - PROGRESSIVE)"));
  434. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  435. }
  436. if (mInfo.output_scanline == mInfo.output_height) {
  437. if (!jpeg_finish_output(&mInfo)) {
  438. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  439. ("} (I/O suspension after jpeg_finish_output() -"
  440. " PROGRESSIVE)"));
  441. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  442. }
  443. if (jpeg_input_complete(&mInfo) &&
  444. (mInfo.input_scan_number == mInfo.output_scan_number))
  445. break;
  446. mInfo.output_scanline = 0;
  447. if (mDownscaler) {
  448. mDownscaler->ResetForNextProgressivePass();
  449. }
  450. }
  451. }
  452. mState = JPEG_DONE;
  453. }
  454. MOZ_FALLTHROUGH; // to finish decompressing.
  455. }
  456. case JPEG_DONE: {
  457. LOG_SCOPE((mozilla::LogModule*)sJPEGLog, "nsJPEGDecoder::ProcessData -- entering"
  458. " JPEG_DONE case");
  459. // Step 7: Finish decompression
  460. if (jpeg_finish_decompress(&mInfo) == FALSE) {
  461. MOZ_LOG(sJPEGDecoderAccountingLog, LogLevel::Debug,
  462. ("} (I/O suspension after jpeg_finish_decompress() - DONE)"));
  463. return Transition::ContinueUnbuffered(State::JPEG_DATA); // I/O suspension
  464. }
  465. // Make sure we don't feed any more data to libjpeg-turbo.
  466. mState = JPEG_SINK_NON_JPEG_TRAILER;
  467. // We're done.
  468. return Transition::TerminateSuccess();
  469. }
  470. case JPEG_SINK_NON_JPEG_TRAILER:
  471. MOZ_LOG(sJPEGLog, LogLevel::Debug,
  472. ("[this=%p] nsJPEGDecoder::ProcessData -- entering"
  473. " JPEG_SINK_NON_JPEG_TRAILER case\n", this));
  474. MOZ_ASSERT_UNREACHABLE("Should stop getting data after entering state "
  475. "JPEG_SINK_NON_JPEG_TRAILER");
  476. return Transition::TerminateSuccess();
  477. case JPEG_ERROR:
  478. MOZ_ASSERT_UNREACHABLE("Should stop getting data after entering state "
  479. "JPEG_ERROR");
  480. return Transition::TerminateFailure();
  481. }
  482. MOZ_ASSERT_UNREACHABLE("Escaped the JPEG decoder state machine");
  483. return Transition::TerminateFailure();
  484. }
  485. LexerTransition<nsJPEGDecoder::State>
  486. nsJPEGDecoder::FinishedJPEGData()
  487. {
  488. // Since we set up an unbuffered read for SIZE_MAX bytes, if we actually read
  489. // all that data something is really wrong.
  490. MOZ_ASSERT_UNREACHABLE("Read the entire address space?");
  491. return Transition::TerminateFailure();
  492. }
  493. Orientation
  494. nsJPEGDecoder::ReadOrientationFromEXIF()
  495. {
  496. jpeg_saved_marker_ptr marker;
  497. // Locate the APP1 marker, where EXIF data is stored, in the marker list.
  498. for (marker = mInfo.marker_list ; marker != nullptr ; marker = marker->next) {
  499. if (marker->marker == JPEG_APP0 + 1) {
  500. break;
  501. }
  502. }
  503. // If we're at the end of the list, there's no EXIF data.
  504. if (!marker) {
  505. return Orientation();
  506. }
  507. // Extract the orientation information.
  508. EXIFData exif = EXIFParser::Parse(marker->data,
  509. static_cast<uint32_t>(marker->data_length));
  510. return exif.orientation;
  511. }
  512. void
  513. nsJPEGDecoder::NotifyDone()
  514. {
  515. PostFrameStop(Opacity::FULLY_OPAQUE);
  516. PostDecodeDone();
  517. }
  518. void
  519. nsJPEGDecoder::OutputScanlines(bool* suspend)
  520. {
  521. *suspend = false;
  522. const uint32_t top = mInfo.output_scanline;
  523. while ((mInfo.output_scanline < mInfo.output_height)) {
  524. uint32_t* imageRow = nullptr;
  525. if (mDownscaler) {
  526. imageRow = reinterpret_cast<uint32_t*>(mDownscaler->RowBuffer());
  527. } else {
  528. imageRow = reinterpret_cast<uint32_t*>(mImageData) +
  529. (mInfo.output_scanline * mInfo.output_width);
  530. }
  531. MOZ_ASSERT(imageRow, "Should have a row buffer here");
  532. if (mInfo.out_color_space == MOZ_JCS_EXT_NATIVE_ENDIAN_XRGB) {
  533. // Special case: scanline will be directly converted into packed ARGB
  534. if (jpeg_read_scanlines(&mInfo, (JSAMPARRAY)&imageRow, 1) != 1) {
  535. *suspend = true; // suspend
  536. break;
  537. }
  538. if (mDownscaler) {
  539. mDownscaler->CommitRow();
  540. }
  541. continue; // all done for this row!
  542. }
  543. JSAMPROW sampleRow = (JSAMPROW)imageRow;
  544. if (mInfo.output_components == 3) {
  545. // Put the pixels at end of row to enable in-place expansion
  546. sampleRow += mInfo.output_width;
  547. }
  548. // Request one scanline. Returns 0 or 1 scanlines.
  549. if (jpeg_read_scanlines(&mInfo, &sampleRow, 1) != 1) {
  550. *suspend = true; // suspend
  551. break;
  552. }
  553. if (mTransform) {
  554. JSAMPROW source = sampleRow;
  555. if (mInfo.out_color_space == JCS_GRAYSCALE) {
  556. // Convert from the 1byte grey pixels at begin of row
  557. // to the 3byte RGB byte pixels at 'end' of row
  558. sampleRow += mInfo.output_width;
  559. }
  560. qcms_transform_data(mTransform, source, sampleRow, mInfo.output_width);
  561. // Move 3byte RGB data to end of row
  562. if (mInfo.out_color_space == JCS_CMYK) {
  563. memmove(sampleRow + mInfo.output_width,
  564. sampleRow,
  565. 3 * mInfo.output_width);
  566. sampleRow += mInfo.output_width;
  567. }
  568. } else {
  569. if (mInfo.out_color_space == JCS_CMYK) {
  570. // Convert from CMYK to RGB
  571. // We cannot convert directly to Cairo, as the CMSRGBTransform
  572. // may wants to do a RGB transform...
  573. // Would be better to have platform CMSenabled transformation
  574. // from CMYK to (A)RGB...
  575. cmyk_convert_rgb((JSAMPROW)imageRow, mInfo.output_width);
  576. sampleRow += mInfo.output_width;
  577. }
  578. if (mCMSMode == eCMSMode_All) {
  579. // No embedded ICC profile - treat as sRGB
  580. qcms_transform* transform = gfxPlatform::GetCMSRGBTransform();
  581. if (transform) {
  582. qcms_transform_data(transform, sampleRow, sampleRow,
  583. mInfo.output_width);
  584. }
  585. }
  586. }
  587. // counter for while() loops below
  588. uint32_t idx = mInfo.output_width;
  589. // copy as bytes until source pointer is 32-bit-aligned
  590. for (; (NS_PTR_TO_UINT32(sampleRow) & 0x3) && idx; --idx) {
  591. *imageRow++ = gfxPackedPixel(0xFF, sampleRow[0], sampleRow[1],
  592. sampleRow[2]);
  593. sampleRow += 3;
  594. }
  595. // copy pixels in blocks of 4
  596. while (idx >= 4) {
  597. GFX_BLOCK_RGB_TO_FRGB(sampleRow, imageRow);
  598. idx -= 4;
  599. sampleRow += 12;
  600. imageRow += 4;
  601. }
  602. // copy remaining pixel(s)
  603. while (idx--) {
  604. // 32-bit read of final pixel will exceed buffer, so read bytes
  605. *imageRow++ = gfxPackedPixel(0xFF, sampleRow[0], sampleRow[1],
  606. sampleRow[2]);
  607. sampleRow += 3;
  608. }
  609. if (mDownscaler) {
  610. mDownscaler->CommitRow();
  611. }
  612. }
  613. if (mDownscaler && mDownscaler->HasInvalidation()) {
  614. DownscalerInvalidRect invalidRect = mDownscaler->TakeInvalidRect();
  615. PostInvalidation(invalidRect.mOriginalSizeRect,
  616. Some(invalidRect.mTargetSizeRect));
  617. MOZ_ASSERT(!mDownscaler->HasInvalidation());
  618. } else if (!mDownscaler && top != mInfo.output_scanline) {
  619. PostInvalidation(nsIntRect(0, top,
  620. mInfo.output_width,
  621. mInfo.output_scanline - top));
  622. }
  623. }
  624. // Override the standard error method in the IJG JPEG decoder code.
  625. METHODDEF(void)
  626. my_error_exit (j_common_ptr cinfo)
  627. {
  628. decoder_error_mgr* err = (decoder_error_mgr*) cinfo->err;
  629. // Convert error to a browser error code
  630. nsresult error_code = err->pub.msg_code == JERR_OUT_OF_MEMORY
  631. ? NS_ERROR_OUT_OF_MEMORY
  632. : NS_ERROR_FAILURE;
  633. #ifdef DEBUG
  634. char buffer[JMSG_LENGTH_MAX];
  635. // Create the message
  636. (*err->pub.format_message) (cinfo, buffer);
  637. fprintf(stderr, "JPEG decoding error:\n%s\n", buffer);
  638. #endif
  639. // Return control to the setjmp point. We pass an nsresult masquerading as
  640. // an int, which works because the setjmp() caller casts it back.
  641. longjmp(err->setjmp_buffer, static_cast<int>(error_code));
  642. }
  643. /*******************************************************************************
  644. * This is the callback routine from the IJG JPEG library used to supply new
  645. * data to the decompressor when its input buffer is exhausted. It juggles
  646. * multiple buffers in an attempt to avoid unnecessary copying of input data.
  647. *
  648. * (A simpler scheme is possible: It's much easier to use only a single
  649. * buffer; when fill_input_buffer() is called, move any unconsumed data
  650. * (beyond the current pointer/count) down to the beginning of this buffer and
  651. * then load new data into the remaining buffer space. This approach requires
  652. * a little more data copying but is far easier to get right.)
  653. *
  654. * At any one time, the JPEG decompressor is either reading from the necko
  655. * input buffer, which is volatile across top-level calls to the IJG library,
  656. * or the "backtrack" buffer. The backtrack buffer contains the remaining
  657. * unconsumed data from the necko buffer after parsing was suspended due
  658. * to insufficient data in some previous call to the IJG library.
  659. *
  660. * When suspending, the decompressor will back up to a convenient restart
  661. * point (typically the start of the current MCU). The variables
  662. * next_input_byte & bytes_in_buffer indicate where the restart point will be
  663. * if the current call returns FALSE. Data beyond this point must be
  664. * rescanned after resumption, so it must be preserved in case the decompressor
  665. * decides to backtrack.
  666. *
  667. * Returns:
  668. * TRUE if additional data is available, FALSE if no data present and
  669. * the JPEG library should therefore suspend processing of input stream
  670. ******************************************************************************/
  671. /******************************************************************************/
  672. /* data source manager method */
  673. /******************************************************************************/
  674. /******************************************************************************/
  675. /* data source manager method
  676. Initialize source. This is called by jpeg_read_header() before any
  677. data is actually read. May leave
  678. bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
  679. will occur immediately).
  680. */
  681. METHODDEF(void)
  682. init_source (j_decompress_ptr jd)
  683. {
  684. }
  685. /******************************************************************************/
  686. /* data source manager method
  687. Skip num_bytes worth of data. The buffer pointer and count should
  688. be advanced over num_bytes input bytes, refilling the buffer as
  689. needed. This is used to skip over a potentially large amount of
  690. uninteresting data (such as an APPn marker). In some applications
  691. it may be possible to optimize away the reading of the skipped data,
  692. but it's not clear that being smart is worth much trouble; large
  693. skips are uncommon. bytes_in_buffer may be zero on return.
  694. A zero or negative skip count should be treated as a no-op.
  695. */
  696. METHODDEF(void)
  697. skip_input_data (j_decompress_ptr jd, long num_bytes)
  698. {
  699. struct jpeg_source_mgr* src = jd->src;
  700. nsJPEGDecoder* decoder = (nsJPEGDecoder*)(jd->client_data);
  701. if (num_bytes > (long)src->bytes_in_buffer) {
  702. // Can't skip it all right now until we get more data from
  703. // network stream. Set things up so that fill_input_buffer
  704. // will skip remaining amount.
  705. decoder->mBytesToSkip = (size_t)num_bytes - src->bytes_in_buffer;
  706. src->next_input_byte += src->bytes_in_buffer;
  707. src->bytes_in_buffer = 0;
  708. } else {
  709. // Simple case. Just advance buffer pointer
  710. src->bytes_in_buffer -= (size_t)num_bytes;
  711. src->next_input_byte += num_bytes;
  712. }
  713. }
  714. /******************************************************************************/
  715. /* data source manager method
  716. This is called whenever bytes_in_buffer has reached zero and more
  717. data is wanted. In typical applications, it should read fresh data
  718. into the buffer (ignoring the current state of next_input_byte and
  719. bytes_in_buffer), reset the pointer & count to the start of the
  720. buffer, and return TRUE indicating that the buffer has been reloaded.
  721. It is not necessary to fill the buffer entirely, only to obtain at
  722. least one more byte. bytes_in_buffer MUST be set to a positive value
  723. if TRUE is returned. A FALSE return should only be used when I/O
  724. suspension is desired.
  725. */
  726. METHODDEF(boolean)
  727. fill_input_buffer (j_decompress_ptr jd)
  728. {
  729. struct jpeg_source_mgr* src = jd->src;
  730. nsJPEGDecoder* decoder = (nsJPEGDecoder*)(jd->client_data);
  731. if (decoder->mReading) {
  732. const JOCTET* new_buffer = decoder->mSegment;
  733. uint32_t new_buflen = decoder->mSegmentLen;
  734. if (!new_buffer || new_buflen == 0) {
  735. return false; // suspend
  736. }
  737. decoder->mSegmentLen = 0;
  738. if (decoder->mBytesToSkip) {
  739. if (decoder->mBytesToSkip < new_buflen) {
  740. // All done skipping bytes; Return what's left.
  741. new_buffer += decoder->mBytesToSkip;
  742. new_buflen -= decoder->mBytesToSkip;
  743. decoder->mBytesToSkip = 0;
  744. } else {
  745. // Still need to skip some more data in the future
  746. decoder->mBytesToSkip -= (size_t)new_buflen;
  747. return false; // suspend
  748. }
  749. }
  750. decoder->mBackBufferUnreadLen = src->bytes_in_buffer;
  751. src->next_input_byte = new_buffer;
  752. src->bytes_in_buffer = (size_t)new_buflen;
  753. decoder->mReading = false;
  754. return true;
  755. }
  756. if (src->next_input_byte != decoder->mSegment) {
  757. // Backtrack data has been permanently consumed.
  758. decoder->mBackBufferUnreadLen = 0;
  759. decoder->mBackBufferLen = 0;
  760. }
  761. // Save remainder of netlib buffer in backtrack buffer
  762. const uint32_t new_backtrack_buflen = src->bytes_in_buffer +
  763. decoder->mBackBufferLen;
  764. // Make sure backtrack buffer is big enough to hold new data.
  765. if (decoder->mBackBufferSize < new_backtrack_buflen) {
  766. // Check for malformed MARKER segment lengths, before allocating space
  767. // for it
  768. if (new_backtrack_buflen > MAX_JPEG_MARKER_LENGTH) {
  769. my_error_exit((j_common_ptr)(&decoder->mInfo));
  770. }
  771. // Round up to multiple of 256 bytes.
  772. const size_t roundup_buflen = ((new_backtrack_buflen + 255) >> 8) << 8;
  773. JOCTET* buf = (JOCTET*)PR_REALLOC(decoder->mBackBuffer, roundup_buflen);
  774. // Check for OOM
  775. if (!buf) {
  776. decoder->mInfo.err->msg_code = JERR_OUT_OF_MEMORY;
  777. my_error_exit((j_common_ptr)(&decoder->mInfo));
  778. }
  779. decoder->mBackBuffer = buf;
  780. decoder->mBackBufferSize = roundup_buflen;
  781. }
  782. // Copy remainder of netlib segment into backtrack buffer.
  783. memmove(decoder->mBackBuffer + decoder->mBackBufferLen,
  784. src->next_input_byte,
  785. src->bytes_in_buffer);
  786. // Point to start of data to be rescanned.
  787. src->next_input_byte = decoder->mBackBuffer + decoder->mBackBufferLen -
  788. decoder->mBackBufferUnreadLen;
  789. src->bytes_in_buffer += decoder->mBackBufferUnreadLen;
  790. decoder->mBackBufferLen = (size_t)new_backtrack_buflen;
  791. decoder->mReading = true;
  792. return false;
  793. }
  794. /******************************************************************************/
  795. /* data source manager method */
  796. /*
  797. * Terminate source --- called by jpeg_finish_decompress() after all
  798. * data has been read to clean up JPEG source manager. NOT called by
  799. * jpeg_abort() or jpeg_destroy().
  800. */
  801. METHODDEF(void)
  802. term_source (j_decompress_ptr jd)
  803. {
  804. nsJPEGDecoder* decoder = (nsJPEGDecoder*)(jd->client_data);
  805. // This function shouldn't be called if we ran into an error we didn't
  806. // recover from.
  807. MOZ_ASSERT(decoder->mState != JPEG_ERROR,
  808. "Calling term_source on a JPEG with mState == JPEG_ERROR!");
  809. // Notify using a helper method to get around protectedness issues.
  810. decoder->NotifyDone();
  811. }
  812. } // namespace image
  813. } // namespace mozilla
  814. ///*************** Inverted CMYK -> RGB conversion *************************
  815. /// Input is (Inverted) CMYK stored as 4 bytes per pixel.
  816. /// Output is RGB stored as 3 bytes per pixel.
  817. /// @param row Points to row buffer containing the CMYK bytes for each pixel
  818. /// in the row.
  819. /// @param width Number of pixels in the row.
  820. static void cmyk_convert_rgb(JSAMPROW row, JDIMENSION width)
  821. {
  822. // Work from end to front to shrink from 4 bytes per pixel to 3
  823. JSAMPROW in = row + width*4;
  824. JSAMPROW out = in;
  825. for (uint32_t i = width; i > 0; i--) {
  826. in -= 4;
  827. out -= 3;
  828. // Source is 'Inverted CMYK', output is RGB.
  829. // See: http://www.easyrgb.com/math.php?MATH=M12#text12
  830. // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
  831. // From CMYK to CMY
  832. // C = ( C * ( 1 - K ) + K )
  833. // M = ( M * ( 1 - K ) + K )
  834. // Y = ( Y * ( 1 - K ) + K )
  835. // From Inverted CMYK to CMY is thus:
  836. // C = ( (1-iC) * (1 - (1-iK)) + (1-iK) ) => 1 - iC*iK
  837. // Same for M and Y
  838. // Convert from CMY (0..1) to RGB (0..1)
  839. // R = 1 - C => 1 - (1 - iC*iK) => iC*iK
  840. // G = 1 - M => 1 - (1 - iM*iK) => iM*iK
  841. // B = 1 - Y => 1 - (1 - iY*iK) => iY*iK
  842. // Convert from Inverted CMYK (0..255) to RGB (0..255)
  843. const uint32_t iC = in[0];
  844. const uint32_t iM = in[1];
  845. const uint32_t iY = in[2];
  846. const uint32_t iK = in[3];
  847. out[0] = iC*iK/255; // Red
  848. out[1] = iM*iK/255; // Green
  849. out[2] = iY*iK/255; // Blue
  850. }
  851. }