/image/encoders/jpeg/nsJPEGEncoder.cpp

http://github.com/zpao/v8monkey · C++ · 538 lines · 337 code · 78 blank · 123 comment · 56 complexity · a27009f1e92606bf2430a7ce3c89cac0 MD5 · raw file

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  2. * ***** BEGIN LICENSE BLOCK *****
  3. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. * http://www.mozilla.org/MPL/
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. *
  15. * The Original Code is JPEG Encoding code
  16. *
  17. * The Initial Developer of the Original Code is
  18. * Google Inc.
  19. * Portions created by the Initial Developer are Copyright (C) 2005
  20. * the Initial Developer. All Rights Reserved.
  21. *
  22. * Contributor(s):
  23. * Brett Wilson <brettw@gmail.com>
  24. *
  25. * Alternatively, the contents of this file may be used under the terms of
  26. * either the GNU General Public License Version 2 or later (the "GPL"), or
  27. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28. * in which case the provisions of the GPL or the LGPL are applicable instead
  29. * of those above. If you wish to allow use of your version of this file only
  30. * under the terms of either the GPL or the LGPL, and not to allow others to
  31. * use your version of this file under the terms of the MPL, indicate your
  32. * decision by deleting the provisions above and replace them with the notice
  33. * and other provisions required by the GPL or the LGPL. If you do not delete
  34. * the provisions above, a recipient may use your version of this file under
  35. * the terms of any one of the MPL, the GPL or the LGPL.
  36. *
  37. * ***** END LICENSE BLOCK ***** */
  38. #include "nsJPEGEncoder.h"
  39. #include "prmem.h"
  40. #include "prprf.h"
  41. #include "nsString.h"
  42. #include "nsStreamUtils.h"
  43. #include "gfxColor.h"
  44. #include <setjmp.h>
  45. #include "jerror.h"
  46. using namespace mozilla;
  47. NS_IMPL_THREADSAFE_ISUPPORTS3(nsJPEGEncoder, imgIEncoder, nsIInputStream, nsIAsyncInputStream)
  48. // used to pass error info through the JPEG library
  49. struct encoder_error_mgr {
  50. jpeg_error_mgr pub;
  51. jmp_buf setjmp_buffer;
  52. };
  53. nsJPEGEncoder::nsJPEGEncoder() : mFinished(false),
  54. mImageBuffer(nsnull), mImageBufferSize(0),
  55. mImageBufferUsed(0), mImageBufferReadPoint(0),
  56. mCallback(nsnull),
  57. mCallbackTarget(nsnull), mNotifyThreshold(0),
  58. mReentrantMonitor("nsJPEGEncoder.mReentrantMonitor")
  59. {
  60. }
  61. nsJPEGEncoder::~nsJPEGEncoder()
  62. {
  63. if (mImageBuffer) {
  64. PR_Free(mImageBuffer);
  65. mImageBuffer = nsnull;
  66. }
  67. }
  68. // nsJPEGEncoder::InitFromData
  69. //
  70. // One output option is supported: "quality=X" where X is an integer in the
  71. // range 0-100. Higher values for X give better quality.
  72. //
  73. // Transparency is always discarded.
  74. NS_IMETHODIMP nsJPEGEncoder::InitFromData(const PRUint8* aData,
  75. PRUint32 aLength, // (unused, req'd by JS)
  76. PRUint32 aWidth,
  77. PRUint32 aHeight,
  78. PRUint32 aStride,
  79. PRUint32 aInputFormat,
  80. const nsAString& aOutputOptions)
  81. {
  82. NS_ENSURE_ARG(aData);
  83. // validate input format
  84. if (aInputFormat != INPUT_FORMAT_RGB &&
  85. aInputFormat != INPUT_FORMAT_RGBA &&
  86. aInputFormat != INPUT_FORMAT_HOSTARGB)
  87. return NS_ERROR_INVALID_ARG;
  88. // Stride is the padded width of each row, so it better be longer (I'm afraid
  89. // people will not understand what stride means, so check it well)
  90. if ((aInputFormat == INPUT_FORMAT_RGB &&
  91. aStride < aWidth * 3) ||
  92. ((aInputFormat == INPUT_FORMAT_RGBA || aInputFormat == INPUT_FORMAT_HOSTARGB) &&
  93. aStride < aWidth * 4)) {
  94. NS_WARNING("Invalid stride for InitFromData");
  95. return NS_ERROR_INVALID_ARG;
  96. }
  97. // can't initialize more than once
  98. if (mImageBuffer != nsnull)
  99. return NS_ERROR_ALREADY_INITIALIZED;
  100. // options: we only have one option so this is easy
  101. int quality = 92;
  102. if (aOutputOptions.Length() > 0) {
  103. // have options string
  104. const nsString qualityPrefix(NS_LITERAL_STRING("quality="));
  105. if (aOutputOptions.Length() > qualityPrefix.Length() &&
  106. StringBeginsWith(aOutputOptions, qualityPrefix)) {
  107. // have quality string
  108. nsCString value = NS_ConvertUTF16toUTF8(Substring(aOutputOptions,
  109. qualityPrefix.Length()));
  110. int newquality = -1;
  111. if (PR_sscanf(value.get(), "%d", &newquality) == 1) {
  112. if (newquality >= 0 && newquality <= 100) {
  113. quality = newquality;
  114. } else {
  115. NS_WARNING("Quality value out of range, should be 0-100, using default");
  116. }
  117. } else {
  118. NS_WARNING("Quality value invalid, should be integer 0-100, using default");
  119. }
  120. }
  121. else {
  122. return NS_ERROR_INVALID_ARG;
  123. }
  124. }
  125. jpeg_compress_struct cinfo;
  126. // We set up the normal JPEG error routines, then override error_exit.
  127. // This must be done before the call to create_compress
  128. encoder_error_mgr errmgr;
  129. cinfo.err = jpeg_std_error(&errmgr.pub);
  130. errmgr.pub.error_exit = errorExit;
  131. // Establish the setjmp return context for my_error_exit to use.
  132. if (setjmp(errmgr.setjmp_buffer)) {
  133. // If we get here, the JPEG code has signaled an error.
  134. // We need to clean up the JPEG object, close the input file, and return.
  135. return NS_ERROR_FAILURE;
  136. }
  137. jpeg_create_compress(&cinfo);
  138. cinfo.image_width = aWidth;
  139. cinfo.image_height = aHeight;
  140. cinfo.input_components = 3;
  141. cinfo.in_color_space = JCS_RGB;
  142. cinfo.data_precision = 8;
  143. jpeg_set_defaults(&cinfo);
  144. jpeg_set_quality(&cinfo, quality, 1); // quality here is 0-100
  145. if (quality >= 90) {
  146. int i;
  147. for (i=0; i < MAX_COMPONENTS; i++) {
  148. cinfo.comp_info[i].h_samp_factor=1;
  149. cinfo.comp_info[i].v_samp_factor=1;
  150. }
  151. }
  152. // set up the destination manager
  153. jpeg_destination_mgr destmgr;
  154. destmgr.init_destination = initDestination;
  155. destmgr.empty_output_buffer = emptyOutputBuffer;
  156. destmgr.term_destination = termDestination;
  157. cinfo.dest = &destmgr;
  158. cinfo.client_data = this;
  159. jpeg_start_compress(&cinfo, 1);
  160. // feed it the rows
  161. if (aInputFormat == INPUT_FORMAT_RGB) {
  162. while (cinfo.next_scanline < cinfo.image_height) {
  163. const PRUint8* row = &aData[cinfo.next_scanline * aStride];
  164. jpeg_write_scanlines(&cinfo, const_cast<PRUint8**>(&row), 1);
  165. }
  166. } else if (aInputFormat == INPUT_FORMAT_RGBA) {
  167. PRUint8* row = new PRUint8[aWidth * 3];
  168. while (cinfo.next_scanline < cinfo.image_height) {
  169. ConvertRGBARow(&aData[cinfo.next_scanline * aStride], row, aWidth);
  170. jpeg_write_scanlines(&cinfo, &row, 1);
  171. }
  172. delete[] row;
  173. } else if (aInputFormat == INPUT_FORMAT_HOSTARGB) {
  174. PRUint8* row = new PRUint8[aWidth * 3];
  175. while (cinfo.next_scanline < cinfo.image_height) {
  176. ConvertHostARGBRow(&aData[cinfo.next_scanline * aStride], row, aWidth);
  177. jpeg_write_scanlines(&cinfo, &row, 1);
  178. }
  179. delete[] row;
  180. }
  181. jpeg_finish_compress(&cinfo);
  182. jpeg_destroy_compress(&cinfo);
  183. mFinished = true;
  184. NotifyListener();
  185. // if output callback can't get enough memory, it will free our buffer
  186. if (!mImageBuffer)
  187. return NS_ERROR_OUT_OF_MEMORY;
  188. return NS_OK;
  189. }
  190. NS_IMETHODIMP nsJPEGEncoder::StartImageEncode(PRUint32 aWidth,
  191. PRUint32 aHeight,
  192. PRUint32 aInputFormat,
  193. const nsAString& aOutputOptions)
  194. {
  195. return NS_ERROR_NOT_IMPLEMENTED;
  196. }
  197. // Returns the number of bytes in the image buffer used.
  198. NS_IMETHODIMP nsJPEGEncoder::GetImageBufferUsed(PRUint32 *aOutputSize)
  199. {
  200. NS_ENSURE_ARG_POINTER(aOutputSize);
  201. *aOutputSize = mImageBufferUsed;
  202. return NS_OK;
  203. }
  204. // Returns a pointer to the start of the image buffer
  205. NS_IMETHODIMP nsJPEGEncoder::GetImageBuffer(char **aOutputBuffer)
  206. {
  207. NS_ENSURE_ARG_POINTER(aOutputBuffer);
  208. *aOutputBuffer = reinterpret_cast<char*>(mImageBuffer);
  209. return NS_OK;
  210. }
  211. NS_IMETHODIMP nsJPEGEncoder::AddImageFrame(const PRUint8* aData,
  212. PRUint32 aLength,
  213. PRUint32 aWidth,
  214. PRUint32 aHeight,
  215. PRUint32 aStride,
  216. PRUint32 aFrameFormat,
  217. const nsAString& aFrameOptions)
  218. {
  219. return NS_ERROR_NOT_IMPLEMENTED;
  220. }
  221. NS_IMETHODIMP nsJPEGEncoder::EndImageEncode()
  222. {
  223. return NS_ERROR_NOT_IMPLEMENTED;
  224. }
  225. /* void close (); */
  226. NS_IMETHODIMP nsJPEGEncoder::Close()
  227. {
  228. if (mImageBuffer != nsnull) {
  229. PR_Free(mImageBuffer);
  230. mImageBuffer = nsnull;
  231. mImageBufferSize = 0;
  232. mImageBufferUsed = 0;
  233. mImageBufferReadPoint = 0;
  234. }
  235. return NS_OK;
  236. }
  237. /* unsigned long available (); */
  238. NS_IMETHODIMP nsJPEGEncoder::Available(PRUint32 *_retval)
  239. {
  240. if (!mImageBuffer)
  241. return NS_BASE_STREAM_CLOSED;
  242. *_retval = mImageBufferUsed - mImageBufferReadPoint;
  243. return NS_OK;
  244. }
  245. /* [noscript] unsigned long read (in charPtr aBuf, in unsigned long aCount); */
  246. NS_IMETHODIMP nsJPEGEncoder::Read(char * aBuf, PRUint32 aCount,
  247. PRUint32 *_retval)
  248. {
  249. return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, _retval);
  250. }
  251. /* [noscript] unsigned long readSegments (in nsWriteSegmentFun aWriter, in voidPtr aClosure, in unsigned long aCount); */
  252. NS_IMETHODIMP nsJPEGEncoder::ReadSegments(nsWriteSegmentFun aWriter, void *aClosure, PRUint32 aCount, PRUint32 *_retval)
  253. {
  254. // Avoid another thread reallocing the buffer underneath us
  255. ReentrantMonitorAutoEnter autoEnter(mReentrantMonitor);
  256. PRUint32 maxCount = mImageBufferUsed - mImageBufferReadPoint;
  257. if (maxCount == 0) {
  258. *_retval = 0;
  259. return mFinished ? NS_OK : NS_BASE_STREAM_WOULD_BLOCK;
  260. }
  261. if (aCount > maxCount)
  262. aCount = maxCount;
  263. nsresult rv = aWriter(this, aClosure,
  264. reinterpret_cast<const char*>(mImageBuffer+mImageBufferReadPoint),
  265. 0, aCount, _retval);
  266. if (NS_SUCCEEDED(rv)) {
  267. NS_ASSERTION(*_retval <= aCount, "bad write count");
  268. mImageBufferReadPoint += *_retval;
  269. }
  270. // errors returned from the writer end here!
  271. return NS_OK;
  272. }
  273. /* boolean isNonBlocking (); */
  274. NS_IMETHODIMP nsJPEGEncoder::IsNonBlocking(bool *_retval)
  275. {
  276. *_retval = true;
  277. return NS_OK;
  278. }
  279. NS_IMETHODIMP nsJPEGEncoder::AsyncWait(nsIInputStreamCallback *aCallback,
  280. PRUint32 aFlags,
  281. PRUint32 aRequestedCount,
  282. nsIEventTarget *aTarget)
  283. {
  284. if (aFlags != 0)
  285. return NS_ERROR_NOT_IMPLEMENTED;
  286. if (mCallback || mCallbackTarget)
  287. return NS_ERROR_UNEXPECTED;
  288. mCallbackTarget = aTarget;
  289. // 0 means "any number of bytes except 0"
  290. mNotifyThreshold = aRequestedCount;
  291. if (!aRequestedCount)
  292. mNotifyThreshold = 1024; // 1 KB seems good. We don't want to notify incessantly
  293. // We set the callback absolutely last, because NotifyListener uses it to
  294. // determine if someone needs to be notified. If we don't set it last,
  295. // NotifyListener might try to fire off a notification to a null target
  296. // which will generally cause non-threadsafe objects to be used off the main thread
  297. mCallback = aCallback;
  298. // What we are being asked for may be present already
  299. NotifyListener();
  300. return NS_OK;
  301. }
  302. NS_IMETHODIMP nsJPEGEncoder::CloseWithStatus(nsresult aStatus)
  303. {
  304. return Close();
  305. }
  306. // nsJPEGEncoder::ConvertHostARGBRow
  307. //
  308. // Our colors are stored with premultiplied alphas, but we need
  309. // an output with no alpha in machine-independent byte order.
  310. //
  311. // See gfx/cairo/cairo/src/cairo-png.c
  312. void
  313. nsJPEGEncoder::ConvertHostARGBRow(const PRUint8* aSrc, PRUint8* aDest,
  314. PRUint32 aPixelWidth)
  315. {
  316. for (PRUint32 x = 0; x < aPixelWidth; x++) {
  317. const PRUint32& pixelIn = ((const PRUint32*)(aSrc))[x];
  318. PRUint8 *pixelOut = &aDest[x * 3];
  319. pixelOut[0] = (pixelIn & 0xff0000) >> 16;
  320. pixelOut[1] = (pixelIn & 0x00ff00) >> 8;
  321. pixelOut[2] = (pixelIn & 0x0000ff) >> 0;
  322. }
  323. }
  324. /**
  325. * nsJPEGEncoder::ConvertRGBARow
  326. *
  327. * Input is RGBA, output is RGB, so we should alpha-premultiply.
  328. */
  329. void
  330. nsJPEGEncoder::ConvertRGBARow(const PRUint8* aSrc, PRUint8* aDest,
  331. PRUint32 aPixelWidth)
  332. {
  333. for (PRUint32 x = 0; x < aPixelWidth; x++) {
  334. const PRUint8* pixelIn = &aSrc[x * 4];
  335. PRUint8* pixelOut = &aDest[x * 3];
  336. PRUint8 alpha = pixelIn[3];
  337. pixelOut[0] = GFX_PREMULTIPLY(pixelIn[0], alpha);
  338. pixelOut[1] = GFX_PREMULTIPLY(pixelIn[1], alpha);
  339. pixelOut[2] = GFX_PREMULTIPLY(pixelIn[2], alpha);
  340. }
  341. }
  342. // nsJPEGEncoder::initDestination
  343. //
  344. // Initialize destination. This is called by jpeg_start_compress() before
  345. // any data is actually written. It must initialize next_output_byte and
  346. // free_in_buffer. free_in_buffer must be initialized to a positive value.
  347. void // static
  348. nsJPEGEncoder::initDestination(jpeg_compress_struct* cinfo)
  349. {
  350. nsJPEGEncoder* that = static_cast<nsJPEGEncoder*>(cinfo->client_data);
  351. NS_ASSERTION(! that->mImageBuffer, "Image buffer already initialized");
  352. that->mImageBufferSize = 8192;
  353. that->mImageBuffer = (PRUint8*)PR_Malloc(that->mImageBufferSize);
  354. that->mImageBufferUsed = 0;
  355. cinfo->dest->next_output_byte = that->mImageBuffer;
  356. cinfo->dest->free_in_buffer = that->mImageBufferSize;
  357. }
  358. // nsJPEGEncoder::emptyOutputBuffer
  359. //
  360. // This is called whenever the buffer has filled (free_in_buffer reaches
  361. // zero). In typical applications, it should write out the *entire* buffer
  362. // (use the saved start address and buffer length; ignore the current state
  363. // of next_output_byte and free_in_buffer). Then reset the pointer & count
  364. // to the start of the buffer, and return TRUE indicating that the buffer
  365. // has been dumped. free_in_buffer must be set to a positive value when
  366. // TRUE is returned. A FALSE return should only be used when I/O suspension
  367. // is desired (this operating mode is discussed in the next section).
  368. boolean // static
  369. nsJPEGEncoder::emptyOutputBuffer(jpeg_compress_struct* cinfo)
  370. {
  371. nsJPEGEncoder* that = static_cast<nsJPEGEncoder*>(cinfo->client_data);
  372. NS_ASSERTION(that->mImageBuffer, "No buffer to empty!");
  373. // When we're reallocing the buffer we need to take the lock to ensure
  374. // that nobody is trying to read from the buffer we are destroying
  375. ReentrantMonitorAutoEnter autoEnter(that->mReentrantMonitor);
  376. that->mImageBufferUsed = that->mImageBufferSize;
  377. // expand buffer, just double size each time
  378. that->mImageBufferSize *= 2;
  379. PRUint8* newBuf = (PRUint8*)PR_Realloc(that->mImageBuffer,
  380. that->mImageBufferSize);
  381. if (! newBuf) {
  382. // can't resize, just zero (this will keep us from writing more)
  383. PR_Free(that->mImageBuffer);
  384. that->mImageBuffer = nsnull;
  385. that->mImageBufferSize = 0;
  386. that->mImageBufferUsed = 0;
  387. // this seems to be the only way to do errors through the JPEG library
  388. longjmp(((encoder_error_mgr*)(cinfo->err))->setjmp_buffer,
  389. NS_ERROR_OUT_OF_MEMORY);
  390. }
  391. that->mImageBuffer = newBuf;
  392. cinfo->dest->next_output_byte = &that->mImageBuffer[that->mImageBufferUsed];
  393. cinfo->dest->free_in_buffer = that->mImageBufferSize - that->mImageBufferUsed;
  394. return 1;
  395. }
  396. // nsJPEGEncoder::termDestination
  397. //
  398. // Terminate destination --- called by jpeg_finish_compress() after all data
  399. // has been written. In most applications, this must flush any data
  400. // remaining in the buffer. Use either next_output_byte or free_in_buffer
  401. // to determine how much data is in the buffer.
  402. void // static
  403. nsJPEGEncoder::termDestination(jpeg_compress_struct* cinfo)
  404. {
  405. nsJPEGEncoder* that = static_cast<nsJPEGEncoder*>(cinfo->client_data);
  406. if (! that->mImageBuffer)
  407. return;
  408. that->mImageBufferUsed = cinfo->dest->next_output_byte - that->mImageBuffer;
  409. NS_ASSERTION(that->mImageBufferUsed < that->mImageBufferSize,
  410. "JPEG library busted, got a bad image buffer size");
  411. that->NotifyListener();
  412. }
  413. // nsJPEGEncoder::errorExit
  414. //
  415. // Override the standard error method in the IJG JPEG decoder code. This
  416. // was mostly copied from nsJPEGDecoder.cpp
  417. void // static
  418. nsJPEGEncoder::errorExit(jpeg_common_struct* cinfo)
  419. {
  420. nsresult error_code;
  421. encoder_error_mgr *err = (encoder_error_mgr *) cinfo->err;
  422. // Convert error to a browser error code
  423. switch (cinfo->err->msg_code) {
  424. case JERR_OUT_OF_MEMORY:
  425. error_code = NS_ERROR_OUT_OF_MEMORY;
  426. break;
  427. default:
  428. error_code = NS_ERROR_FAILURE;
  429. }
  430. // Return control to the setjmp point.
  431. longjmp(err->setjmp_buffer, error_code);
  432. }
  433. void
  434. nsJPEGEncoder::NotifyListener()
  435. {
  436. // We might call this function on multiple threads (any threads that call
  437. // AsyncWait and any that do encoding) so we lock to avoid notifying the
  438. // listener twice about the same data (which generally leads to a truncated
  439. // image).
  440. ReentrantMonitorAutoEnter autoEnter(mReentrantMonitor);
  441. if (mCallback &&
  442. (mImageBufferUsed - mImageBufferReadPoint >= mNotifyThreshold ||
  443. mFinished)) {
  444. nsCOMPtr<nsIInputStreamCallback> callback;
  445. if (mCallbackTarget) {
  446. NS_NewInputStreamReadyEvent(getter_AddRefs(callback),
  447. mCallback,
  448. mCallbackTarget);
  449. } else {
  450. callback = mCallback;
  451. }
  452. NS_ASSERTION(callback, "Shouldn't fail to make the callback");
  453. // Null the callback first because OnInputStreamReady could reenter
  454. // AsyncWait
  455. mCallback = nsnull;
  456. mCallbackTarget = nsnull;
  457. mNotifyThreshold = 0;
  458. callback->OnInputStreamReady(this);
  459. }
  460. }