Bug 470455 - test_database_sync_embed_visits.js leaks, r=sdwilsh
[wine-gecko.git] / modules / libpr0n / encoders / jpeg / nsJPEGEncoder.cpp
blobc216f0dd3f419cf44399efc4596a92144234efa6
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
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/
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.
15 * The Original Code is JPEG Encoding code
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.
22 * Contributor(s):
23 * Brett Wilson <brettw@gmail.com>
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.
37 * ***** END LICENSE BLOCK ***** */
39 #include "nsJPEGEncoder.h"
40 #include "prmem.h"
41 #include "prprf.h"
42 #include "nsString.h"
43 #include "nsStreamUtils.h"
45 #include <setjmp.h>
46 #include "jerror.h"
48 // Input streams that do not implement nsIAsyncInputStream should be threadsafe
49 // so that they may be used with nsIInputStreamPump and nsIInputStreamChannel,
50 // which read such a stream on a background thread.
51 NS_IMPL_THREADSAFE_ISUPPORTS2(nsJPEGEncoder, imgIEncoder, nsIInputStream)
53 // used to pass error info through the JPEG library
54 struct encoder_error_mgr {
55 jpeg_error_mgr pub;
56 jmp_buf setjmp_buffer;
59 nsJPEGEncoder::nsJPEGEncoder() : mImageBuffer(nsnull), mImageBufferSize(0),
60 mImageBufferUsed(0), mImageBufferReadPoint(0)
64 nsJPEGEncoder::~nsJPEGEncoder()
66 if (mImageBuffer) {
67 PR_Free(mImageBuffer);
68 mImageBuffer = nsnull;
73 // nsJPEGEncoder::InitFromData
75 // One output option is supported: "quality=X" where X is an integer in the
76 // range 0-100. Higher values for X give better quality.
78 // Transparency is always discarded.
80 NS_IMETHODIMP nsJPEGEncoder::InitFromData(const PRUint8* aData,
81 PRUint32 aLength, // (unused, req'd by JS)
82 PRUint32 aWidth,
83 PRUint32 aHeight,
84 PRUint32 aStride,
85 PRUint32 aInputFormat,
86 const nsAString& aOutputOptions)
88 // validate input format
89 if (aInputFormat != INPUT_FORMAT_RGB &&
90 aInputFormat != INPUT_FORMAT_RGBA &&
91 aInputFormat != INPUT_FORMAT_HOSTARGB)
92 return NS_ERROR_INVALID_ARG;
94 // Stride is the padded width of each row, so it better be longer (I'm afraid
95 // people will not understand what stride means, so check it well)
96 if ((aInputFormat == INPUT_FORMAT_RGB &&
97 aStride < aWidth * 3) ||
98 ((aInputFormat == INPUT_FORMAT_RGBA || aInputFormat == INPUT_FORMAT_HOSTARGB) &&
99 aStride < aWidth * 4)) {
100 NS_WARNING("Invalid stride for InitFromData");
101 return NS_ERROR_INVALID_ARG;
104 // can't initialize more than once
105 if (mImageBuffer != nsnull)
106 return NS_ERROR_ALREADY_INITIALIZED;
108 // options: we only have one option so this is easy
109 int quality = 50;
110 if (aOutputOptions.Length() > 0) {
111 // have options string
112 const nsString qualityPrefix(NS_LITERAL_STRING("quality="));
113 if (aOutputOptions.Length() > qualityPrefix.Length() &&
114 StringBeginsWith(aOutputOptions, qualityPrefix)) {
115 // have quality string
116 nsCString value = NS_ConvertUTF16toUTF8(Substring(aOutputOptions,
117 qualityPrefix.Length()));
118 int newquality = -1;
119 if (PR_sscanf(PromiseFlatCString(value).get(), "%d", &newquality) == 1) {
120 if (newquality >= 0 && newquality <= 100) {
121 quality = newquality;
122 } else {
123 NS_WARNING("Quality value out of range, should be 0-100, using default");
125 } else {
126 NS_WARNING("Quality value invalid, should be integer 0-100, using default");
129 else {
130 return NS_ERROR_INVALID_ARG;
134 jpeg_compress_struct cinfo;
136 // We set up the normal JPEG error routines, then override error_exit.
137 // This must be done before the call to create_compress
138 encoder_error_mgr errmgr;
139 cinfo.err = jpeg_std_error(&errmgr.pub);
140 errmgr.pub.error_exit = errorExit;
141 // Establish the setjmp return context for my_error_exit to use.
142 if (setjmp(errmgr.setjmp_buffer)) {
143 // If we get here, the JPEG code has signaled an error.
144 // We need to clean up the JPEG object, close the input file, and return.
145 return NS_ERROR_FAILURE;
148 jpeg_create_compress(&cinfo);
149 cinfo.image_width = aWidth;
150 cinfo.image_height = aHeight;
151 cinfo.input_components = 3;
152 cinfo.in_color_space = JCS_RGB;
153 cinfo.data_precision = 8;
155 jpeg_set_defaults(&cinfo);
156 jpeg_set_quality(&cinfo, quality, 1); // quality here is 0-100
157 if (quality >= 90) {
158 int i;
159 for (i=0; i < MAX_COMPONENTS; i++) {
160 cinfo.comp_info[i].h_samp_factor=1;
161 cinfo.comp_info[i].v_samp_factor=1;
165 // set up the destination manager
166 jpeg_destination_mgr destmgr;
167 destmgr.init_destination = initDestination;
168 destmgr.empty_output_buffer = emptyOutputBuffer;
169 destmgr.term_destination = termDestination;
170 cinfo.dest = &destmgr;
171 cinfo.client_data = this;
173 jpeg_start_compress(&cinfo, 1);
175 // feed it the rows
176 if (aInputFormat == INPUT_FORMAT_RGB) {
177 while (cinfo.next_scanline < cinfo.image_height) {
178 const PRUint8* row = &aData[cinfo.next_scanline * aStride];
179 jpeg_write_scanlines(&cinfo, const_cast<PRUint8**>(&row), 1);
181 } else if (aInputFormat == INPUT_FORMAT_RGBA) {
182 PRUint8* row = new PRUint8[aWidth * 3];
183 while (cinfo.next_scanline < cinfo.image_height) {
184 StripAlpha(&aData[cinfo.next_scanline * aStride], row, aWidth);
185 jpeg_write_scanlines(&cinfo, &row, 1);
187 delete[] row;
188 } else if (aInputFormat == INPUT_FORMAT_HOSTARGB) {
189 PRUint8* row = new PRUint8[aWidth * 3];
190 while (cinfo.next_scanline < cinfo.image_height) {
191 ConvertHostARGBRow(&aData[cinfo.next_scanline * aStride], row, aWidth);
192 jpeg_write_scanlines(&cinfo, &row, 1);
194 delete[] row;
197 jpeg_finish_compress(&cinfo);
198 jpeg_destroy_compress(&cinfo);
200 // if output callback can't get enough memory, it will free our buffer
201 if (!mImageBuffer)
202 return NS_ERROR_OUT_OF_MEMORY;
204 return NS_OK;
208 NS_IMETHODIMP nsJPEGEncoder::StartImageEncode(PRUint32 aWidth,
209 PRUint32 aHeight,
210 PRUint32 aInputFormat,
211 const nsAString& aOutputOptions)
213 return NS_ERROR_NOT_IMPLEMENTED;
216 NS_IMETHODIMP nsJPEGEncoder::AddImageFrame(const PRUint8* aData,
217 PRUint32 aLength,
218 PRUint32 aWidth,
219 PRUint32 aHeight,
220 PRUint32 aStride,
221 PRUint32 aFrameFormat,
222 const nsAString& aFrameOptions)
224 return NS_ERROR_NOT_IMPLEMENTED;
227 NS_IMETHODIMP nsJPEGEncoder::EndImageEncode()
229 return NS_ERROR_NOT_IMPLEMENTED;
233 /* void close (); */
234 NS_IMETHODIMP nsJPEGEncoder::Close()
236 if (mImageBuffer != nsnull) {
237 PR_Free(mImageBuffer);
238 mImageBuffer = nsnull;
239 mImageBufferSize = 0;
240 mImageBufferUsed = 0;
241 mImageBufferReadPoint = 0;
243 return NS_OK;
246 /* unsigned long available (); */
247 NS_IMETHODIMP nsJPEGEncoder::Available(PRUint32 *_retval)
249 if (!mImageBuffer)
250 return NS_BASE_STREAM_CLOSED;
252 *_retval = mImageBufferUsed - mImageBufferReadPoint;
253 return NS_OK;
256 /* [noscript] unsigned long read (in charPtr aBuf, in unsigned long aCount); */
257 NS_IMETHODIMP nsJPEGEncoder::Read(char * aBuf, PRUint32 aCount,
258 PRUint32 *_retval)
260 return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, _retval);
263 /* [noscript] unsigned long readSegments (in nsWriteSegmentFun aWriter, in voidPtr aClosure, in unsigned long aCount); */
264 NS_IMETHODIMP nsJPEGEncoder::ReadSegments(nsWriteSegmentFun aWriter, void *aClosure, PRUint32 aCount, PRUint32 *_retval)
266 PRUint32 maxCount = mImageBufferUsed - mImageBufferReadPoint;
267 if (maxCount == 0) {
268 *_retval = 0;
269 return NS_OK;
272 if (aCount > maxCount)
273 aCount = maxCount;
274 nsresult rv = aWriter(this, aClosure,
275 reinterpret_cast<const char*>(mImageBuffer+mImageBufferReadPoint),
276 0, aCount, _retval);
277 if (NS_SUCCEEDED(rv)) {
278 NS_ASSERTION(*_retval <= aCount, "bad write count");
279 mImageBufferReadPoint += *_retval;
282 // errors returned from the writer end here!
283 return NS_OK;
286 /* boolean isNonBlocking (); */
287 NS_IMETHODIMP nsJPEGEncoder::IsNonBlocking(PRBool *_retval)
289 *_retval = PR_FALSE; // We don't implement nsIAsyncInputStream
290 return NS_OK;
294 // nsJPEGEncoder::ConvertHostARGBRow
296 // Our colors are stored with premultiplied alphas, but we need
297 // an output with no alpha in machine-independent byte order.
299 // See gfx/cairo/cairo/src/cairo-png.c
301 void
302 nsJPEGEncoder::ConvertHostARGBRow(const PRUint8* aSrc, PRUint8* aDest,
303 PRUint32 aPixelWidth)
305 for (PRUint32 x = 0; x < aPixelWidth; x ++) {
306 const PRUint32& pixelIn = ((const PRUint32*)(aSrc))[x];
307 PRUint8 *pixelOut = &aDest[x * 3];
309 PRUint8 alpha = (pixelIn & 0xff000000) >> 24;
310 if (alpha == 0) {
311 pixelOut[0] = pixelOut[1] = pixelOut[2] = 0;
312 } else {
313 pixelOut[0] = (((pixelIn & 0xff0000) >> 16) * 255 + alpha / 2) / alpha;
314 pixelOut[1] = (((pixelIn & 0x00ff00) >> 8) * 255 + alpha / 2) / alpha;
315 pixelOut[2] = (((pixelIn & 0x0000ff) >> 0) * 255 + alpha / 2) / alpha;
321 // nsJPEGEncoder::StripAlpha
323 // Input is RGBA, output is RGB
325 void
326 nsJPEGEncoder::StripAlpha(const PRUint8* aSrc, PRUint8* aDest,
327 PRUint32 aPixelWidth)
329 for (PRUint32 x = 0; x < aPixelWidth; x ++) {
330 const PRUint8* pixelIn = &aSrc[x * 4];
331 PRUint8* pixelOut = &aDest[x * 3];
332 pixelOut[0] = pixelIn[0];
333 pixelOut[1] = pixelIn[1];
334 pixelOut[2] = pixelIn[2];
339 // nsJPEGEncoder::initDestination
341 // Initialize destination. This is called by jpeg_start_compress() before
342 // any data is actually written. It must initialize next_output_byte and
343 // free_in_buffer. free_in_buffer must be initialized to a positive value.
345 void // static
346 nsJPEGEncoder::initDestination(jpeg_compress_struct* cinfo)
348 nsJPEGEncoder* that = static_cast<nsJPEGEncoder*>(cinfo->client_data);
349 NS_ASSERTION(! that->mImageBuffer, "Image buffer already initialized");
351 that->mImageBufferSize = 8192;
352 that->mImageBuffer = (PRUint8*)PR_Malloc(that->mImageBufferSize);
353 that->mImageBufferUsed = 0;
355 cinfo->dest->next_output_byte = that->mImageBuffer;
356 cinfo->dest->free_in_buffer = that->mImageBufferSize;
360 // nsJPEGEncoder::emptyOutputBuffer
362 // This is called whenever the buffer has filled (free_in_buffer reaches
363 // zero). In typical applications, it should write out the *entire* buffer
364 // (use the saved start address and buffer length; ignore the current state
365 // of next_output_byte and free_in_buffer). Then reset the pointer & count
366 // to the start of the buffer, and return TRUE indicating that the buffer
367 // has been dumped. free_in_buffer must be set to a positive value when
368 // TRUE is returned. A FALSE return should only be used when I/O suspension
369 // is desired (this operating mode is discussed in the next section).
371 boolean // static
372 nsJPEGEncoder::emptyOutputBuffer(jpeg_compress_struct* cinfo)
374 nsJPEGEncoder* that = static_cast<nsJPEGEncoder*>(cinfo->client_data);
375 NS_ASSERTION(that->mImageBuffer, "No buffer to empty!");
377 that->mImageBufferUsed = that->mImageBufferSize;
379 // expand buffer, just double size each time
380 that->mImageBufferSize *= 2;
382 PRUint8* newBuf = (PRUint8*)PR_Realloc(that->mImageBuffer,
383 that->mImageBufferSize);
384 if (! newBuf) {
385 // can't resize, just zero (this will keep us from writing more)
386 PR_Free(that->mImageBuffer);
387 that->mImageBuffer = nsnull;
388 that->mImageBufferSize = 0;
389 that->mImageBufferUsed = 0;
391 // this seems to be the only way to do errors through the JPEG library
392 longjmp(((encoder_error_mgr*)(cinfo->err))->setjmp_buffer,
393 NS_ERROR_OUT_OF_MEMORY);
395 that->mImageBuffer = newBuf;
397 cinfo->dest->next_output_byte = &that->mImageBuffer[that->mImageBufferUsed];
398 cinfo->dest->free_in_buffer = that->mImageBufferSize - that->mImageBufferUsed;
399 return 1;
403 // nsJPEGEncoder::termDestination
405 // Terminate destination --- called by jpeg_finish_compress() after all data
406 // has been written. In most applications, this must flush any data
407 // remaining in the buffer. Use either next_output_byte or free_in_buffer
408 // to determine how much data is in the buffer.
410 void // static
411 nsJPEGEncoder::termDestination(jpeg_compress_struct* cinfo)
413 nsJPEGEncoder* that = static_cast<nsJPEGEncoder*>(cinfo->client_data);
414 if (! that->mImageBuffer)
415 return;
416 that->mImageBufferUsed = cinfo->dest->next_output_byte - that->mImageBuffer;
417 NS_ASSERTION(that->mImageBufferUsed < that->mImageBufferSize,
418 "JPEG library busted, got a bad image buffer size");
422 // nsJPEGEncoder::errorExit
424 // Override the standard error method in the IJG JPEG decoder code. This
425 // was mostly copied from nsJPEGDecoder.cpp
427 void // static
428 nsJPEGEncoder::errorExit(jpeg_common_struct* cinfo)
430 nsresult error_code;
431 encoder_error_mgr *err = (encoder_error_mgr *) cinfo->err;
433 // Convert error to a browser error code
434 switch (cinfo->err->msg_code) {
435 case JERR_OUT_OF_MEMORY:
436 error_code = NS_ERROR_OUT_OF_MEMORY;
437 default:
438 error_code = NS_ERROR_FAILURE;
441 // Return control to the setjmp point.
442 longjmp(err->setjmp_buffer, error_code);