michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "nsJPEGEncoder.h" michael@0: #include "prprf.h" michael@0: #include "nsString.h" michael@0: #include "nsStreamUtils.h" michael@0: #include "gfxColor.h" michael@0: michael@0: #include michael@0: #include "jerror.h" michael@0: michael@0: using namespace mozilla; michael@0: michael@0: NS_IMPL_ISUPPORTS(nsJPEGEncoder, imgIEncoder, nsIInputStream, nsIAsyncInputStream) michael@0: michael@0: // used to pass error info through the JPEG library michael@0: struct encoder_error_mgr { michael@0: jpeg_error_mgr pub; michael@0: jmp_buf setjmp_buffer; michael@0: }; michael@0: michael@0: nsJPEGEncoder::nsJPEGEncoder() : mFinished(false), michael@0: mImageBuffer(nullptr), mImageBufferSize(0), michael@0: mImageBufferUsed(0), mImageBufferReadPoint(0), michael@0: mCallback(nullptr), michael@0: mCallbackTarget(nullptr), mNotifyThreshold(0), michael@0: mReentrantMonitor("nsJPEGEncoder.mReentrantMonitor") michael@0: { michael@0: } michael@0: michael@0: nsJPEGEncoder::~nsJPEGEncoder() michael@0: { michael@0: if (mImageBuffer) { michael@0: moz_free(mImageBuffer); michael@0: mImageBuffer = nullptr; michael@0: } michael@0: } michael@0: michael@0: michael@0: // nsJPEGEncoder::InitFromData michael@0: // michael@0: // One output option is supported: "quality=X" where X is an integer in the michael@0: // range 0-100. Higher values for X give better quality. michael@0: // michael@0: // Transparency is always discarded. michael@0: michael@0: NS_IMETHODIMP nsJPEGEncoder::InitFromData(const uint8_t* aData, michael@0: uint32_t aLength, // (unused, req'd by JS) michael@0: uint32_t aWidth, michael@0: uint32_t aHeight, michael@0: uint32_t aStride, michael@0: uint32_t aInputFormat, michael@0: const nsAString& aOutputOptions) michael@0: { michael@0: NS_ENSURE_ARG(aData); michael@0: michael@0: // validate input format michael@0: if (aInputFormat != INPUT_FORMAT_RGB && michael@0: aInputFormat != INPUT_FORMAT_RGBA && michael@0: aInputFormat != INPUT_FORMAT_HOSTARGB) michael@0: return NS_ERROR_INVALID_ARG; michael@0: michael@0: // Stride is the padded width of each row, so it better be longer (I'm afraid michael@0: // people will not understand what stride means, so check it well) michael@0: if ((aInputFormat == INPUT_FORMAT_RGB && michael@0: aStride < aWidth * 3) || michael@0: ((aInputFormat == INPUT_FORMAT_RGBA || aInputFormat == INPUT_FORMAT_HOSTARGB) && michael@0: aStride < aWidth * 4)) { michael@0: NS_WARNING("Invalid stride for InitFromData"); michael@0: return NS_ERROR_INVALID_ARG; michael@0: } michael@0: michael@0: // can't initialize more than once michael@0: if (mImageBuffer != nullptr) michael@0: return NS_ERROR_ALREADY_INITIALIZED; michael@0: michael@0: // options: we only have one option so this is easy michael@0: int quality = 92; michael@0: if (aOutputOptions.Length() > 0) { michael@0: // have options string michael@0: const nsString qualityPrefix(NS_LITERAL_STRING("quality=")); michael@0: if (aOutputOptions.Length() > qualityPrefix.Length() && michael@0: StringBeginsWith(aOutputOptions, qualityPrefix)) { michael@0: // have quality string michael@0: nsCString value = NS_ConvertUTF16toUTF8(Substring(aOutputOptions, michael@0: qualityPrefix.Length())); michael@0: int newquality = -1; michael@0: if (PR_sscanf(value.get(), "%d", &newquality) == 1) { michael@0: if (newquality >= 0 && newquality <= 100) { michael@0: quality = newquality; michael@0: } else { michael@0: NS_WARNING("Quality value out of range, should be 0-100, using default"); michael@0: } michael@0: } else { michael@0: NS_WARNING("Quality value invalid, should be integer 0-100, using default"); michael@0: } michael@0: } michael@0: else { michael@0: return NS_ERROR_INVALID_ARG; michael@0: } michael@0: } michael@0: michael@0: jpeg_compress_struct cinfo; michael@0: michael@0: // We set up the normal JPEG error routines, then override error_exit. michael@0: // This must be done before the call to create_compress michael@0: encoder_error_mgr errmgr; michael@0: cinfo.err = jpeg_std_error(&errmgr.pub); michael@0: errmgr.pub.error_exit = errorExit; michael@0: // Establish the setjmp return context for my_error_exit to use. michael@0: if (setjmp(errmgr.setjmp_buffer)) { michael@0: // If we get here, the JPEG code has signaled an error. michael@0: // We need to clean up the JPEG object, close the input file, and return. michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: jpeg_create_compress(&cinfo); michael@0: cinfo.image_width = aWidth; michael@0: cinfo.image_height = aHeight; michael@0: cinfo.input_components = 3; michael@0: cinfo.in_color_space = JCS_RGB; michael@0: cinfo.data_precision = 8; michael@0: michael@0: jpeg_set_defaults(&cinfo); michael@0: jpeg_set_quality(&cinfo, quality, 1); // quality here is 0-100 michael@0: if (quality >= 90) { michael@0: int i; michael@0: for (i=0; i < MAX_COMPONENTS; i++) { michael@0: cinfo.comp_info[i].h_samp_factor=1; michael@0: cinfo.comp_info[i].v_samp_factor=1; michael@0: } michael@0: } michael@0: michael@0: // set up the destination manager michael@0: jpeg_destination_mgr destmgr; michael@0: destmgr.init_destination = initDestination; michael@0: destmgr.empty_output_buffer = emptyOutputBuffer; michael@0: destmgr.term_destination = termDestination; michael@0: cinfo.dest = &destmgr; michael@0: cinfo.client_data = this; michael@0: michael@0: jpeg_start_compress(&cinfo, 1); michael@0: michael@0: // feed it the rows michael@0: if (aInputFormat == INPUT_FORMAT_RGB) { michael@0: while (cinfo.next_scanline < cinfo.image_height) { michael@0: const uint8_t* row = &aData[cinfo.next_scanline * aStride]; michael@0: jpeg_write_scanlines(&cinfo, const_cast(&row), 1); michael@0: } michael@0: } else if (aInputFormat == INPUT_FORMAT_RGBA) { michael@0: uint8_t* row = new uint8_t[aWidth * 3]; michael@0: while (cinfo.next_scanline < cinfo.image_height) { michael@0: ConvertRGBARow(&aData[cinfo.next_scanline * aStride], row, aWidth); michael@0: jpeg_write_scanlines(&cinfo, &row, 1); michael@0: } michael@0: delete[] row; michael@0: } else if (aInputFormat == INPUT_FORMAT_HOSTARGB) { michael@0: uint8_t* row = new uint8_t[aWidth * 3]; michael@0: while (cinfo.next_scanline < cinfo.image_height) { michael@0: ConvertHostARGBRow(&aData[cinfo.next_scanline * aStride], row, aWidth); michael@0: jpeg_write_scanlines(&cinfo, &row, 1); michael@0: } michael@0: delete[] row; michael@0: } michael@0: michael@0: jpeg_finish_compress(&cinfo); michael@0: jpeg_destroy_compress(&cinfo); michael@0: michael@0: mFinished = true; michael@0: NotifyListener(); michael@0: michael@0: // if output callback can't get enough memory, it will free our buffer michael@0: if (!mImageBuffer) michael@0: return NS_ERROR_OUT_OF_MEMORY; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: michael@0: NS_IMETHODIMP nsJPEGEncoder::StartImageEncode(uint32_t aWidth, michael@0: uint32_t aHeight, michael@0: uint32_t aInputFormat, michael@0: const nsAString& aOutputOptions) michael@0: { michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: } michael@0: michael@0: // Returns the number of bytes in the image buffer used. michael@0: NS_IMETHODIMP nsJPEGEncoder::GetImageBufferUsed(uint32_t *aOutputSize) michael@0: { michael@0: NS_ENSURE_ARG_POINTER(aOutputSize); michael@0: *aOutputSize = mImageBufferUsed; michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Returns a pointer to the start of the image buffer michael@0: NS_IMETHODIMP nsJPEGEncoder::GetImageBuffer(char **aOutputBuffer) michael@0: { michael@0: NS_ENSURE_ARG_POINTER(aOutputBuffer); michael@0: *aOutputBuffer = reinterpret_cast(mImageBuffer); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP nsJPEGEncoder::AddImageFrame(const uint8_t* aData, michael@0: uint32_t aLength, michael@0: uint32_t aWidth, michael@0: uint32_t aHeight, michael@0: uint32_t aStride, michael@0: uint32_t aFrameFormat, michael@0: const nsAString& aFrameOptions) michael@0: { michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: } michael@0: michael@0: NS_IMETHODIMP nsJPEGEncoder::EndImageEncode() michael@0: { michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: } michael@0: michael@0: michael@0: /* void close (); */ michael@0: NS_IMETHODIMP nsJPEGEncoder::Close() michael@0: { michael@0: if (mImageBuffer != nullptr) { michael@0: moz_free(mImageBuffer); michael@0: mImageBuffer = nullptr; michael@0: mImageBufferSize = 0; michael@0: mImageBufferUsed = 0; michael@0: mImageBufferReadPoint = 0; michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: /* unsigned long available (); */ michael@0: NS_IMETHODIMP nsJPEGEncoder::Available(uint64_t *_retval) michael@0: { michael@0: if (!mImageBuffer) michael@0: return NS_BASE_STREAM_CLOSED; michael@0: michael@0: *_retval = mImageBufferUsed - mImageBufferReadPoint; michael@0: return NS_OK; michael@0: } michael@0: michael@0: /* [noscript] unsigned long read (in charPtr aBuf, in unsigned long aCount); */ michael@0: NS_IMETHODIMP nsJPEGEncoder::Read(char * aBuf, uint32_t aCount, michael@0: uint32_t *_retval) michael@0: { michael@0: return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, _retval); michael@0: } michael@0: michael@0: /* [noscript] unsigned long readSegments (in nsWriteSegmentFun aWriter, in voidPtr aClosure, in unsigned long aCount); */ michael@0: NS_IMETHODIMP nsJPEGEncoder::ReadSegments(nsWriteSegmentFun aWriter, void *aClosure, uint32_t aCount, uint32_t *_retval) michael@0: { michael@0: // Avoid another thread reallocing the buffer underneath us michael@0: ReentrantMonitorAutoEnter autoEnter(mReentrantMonitor); michael@0: michael@0: uint32_t maxCount = mImageBufferUsed - mImageBufferReadPoint; michael@0: if (maxCount == 0) { michael@0: *_retval = 0; michael@0: return mFinished ? NS_OK : NS_BASE_STREAM_WOULD_BLOCK; michael@0: } michael@0: michael@0: if (aCount > maxCount) michael@0: aCount = maxCount; michael@0: nsresult rv = aWriter(this, aClosure, michael@0: reinterpret_cast(mImageBuffer+mImageBufferReadPoint), michael@0: 0, aCount, _retval); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: NS_ASSERTION(*_retval <= aCount, "bad write count"); michael@0: mImageBufferReadPoint += *_retval; michael@0: } michael@0: michael@0: // errors returned from the writer end here! michael@0: return NS_OK; michael@0: } michael@0: michael@0: /* boolean isNonBlocking (); */ michael@0: NS_IMETHODIMP nsJPEGEncoder::IsNonBlocking(bool *_retval) michael@0: { michael@0: *_retval = true; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP nsJPEGEncoder::AsyncWait(nsIInputStreamCallback *aCallback, michael@0: uint32_t aFlags, michael@0: uint32_t aRequestedCount, michael@0: nsIEventTarget *aTarget) michael@0: { michael@0: if (aFlags != 0) michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: michael@0: if (mCallback || mCallbackTarget) michael@0: return NS_ERROR_UNEXPECTED; michael@0: michael@0: mCallbackTarget = aTarget; michael@0: // 0 means "any number of bytes except 0" michael@0: mNotifyThreshold = aRequestedCount; michael@0: if (!aRequestedCount) michael@0: mNotifyThreshold = 1024; // 1 KB seems good. We don't want to notify incessantly michael@0: michael@0: // We set the callback absolutely last, because NotifyListener uses it to michael@0: // determine if someone needs to be notified. If we don't set it last, michael@0: // NotifyListener might try to fire off a notification to a null target michael@0: // which will generally cause non-threadsafe objects to be used off the main thread michael@0: mCallback = aCallback; michael@0: michael@0: // What we are being asked for may be present already michael@0: NotifyListener(); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP nsJPEGEncoder::CloseWithStatus(nsresult aStatus) michael@0: { michael@0: return Close(); michael@0: } michael@0: michael@0: michael@0: michael@0: // nsJPEGEncoder::ConvertHostARGBRow michael@0: // michael@0: // Our colors are stored with premultiplied alphas, but we need michael@0: // an output with no alpha in machine-independent byte order. michael@0: // michael@0: // See gfx/cairo/cairo/src/cairo-png.c michael@0: void michael@0: nsJPEGEncoder::ConvertHostARGBRow(const uint8_t* aSrc, uint8_t* aDest, michael@0: uint32_t aPixelWidth) michael@0: { michael@0: for (uint32_t x = 0; x < aPixelWidth; x++) { michael@0: const uint32_t& pixelIn = ((const uint32_t*)(aSrc))[x]; michael@0: uint8_t *pixelOut = &aDest[x * 3]; michael@0: michael@0: pixelOut[0] = (pixelIn & 0xff0000) >> 16; michael@0: pixelOut[1] = (pixelIn & 0x00ff00) >> 8; michael@0: pixelOut[2] = (pixelIn & 0x0000ff) >> 0; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * nsJPEGEncoder::ConvertRGBARow michael@0: * michael@0: * Input is RGBA, output is RGB, so we should alpha-premultiply. michael@0: */ michael@0: void michael@0: nsJPEGEncoder::ConvertRGBARow(const uint8_t* aSrc, uint8_t* aDest, michael@0: uint32_t aPixelWidth) michael@0: { michael@0: for (uint32_t x = 0; x < aPixelWidth; x++) { michael@0: const uint8_t* pixelIn = &aSrc[x * 4]; michael@0: uint8_t* pixelOut = &aDest[x * 3]; michael@0: michael@0: uint8_t alpha = pixelIn[3]; michael@0: pixelOut[0] = gfxPreMultiply(pixelIn[0], alpha); michael@0: pixelOut[1] = gfxPreMultiply(pixelIn[1], alpha); michael@0: pixelOut[2] = gfxPreMultiply(pixelIn[2], alpha); michael@0: } michael@0: } michael@0: michael@0: // nsJPEGEncoder::initDestination michael@0: // michael@0: // Initialize destination. This is called by jpeg_start_compress() before michael@0: // any data is actually written. It must initialize next_output_byte and michael@0: // free_in_buffer. free_in_buffer must be initialized to a positive value. michael@0: michael@0: void // static michael@0: nsJPEGEncoder::initDestination(jpeg_compress_struct* cinfo) michael@0: { michael@0: nsJPEGEncoder* that = static_cast(cinfo->client_data); michael@0: NS_ASSERTION(! that->mImageBuffer, "Image buffer already initialized"); michael@0: michael@0: that->mImageBufferSize = 8192; michael@0: that->mImageBuffer = (uint8_t*)moz_malloc(that->mImageBufferSize); michael@0: that->mImageBufferUsed = 0; michael@0: michael@0: cinfo->dest->next_output_byte = that->mImageBuffer; michael@0: cinfo->dest->free_in_buffer = that->mImageBufferSize; michael@0: } michael@0: michael@0: michael@0: // nsJPEGEncoder::emptyOutputBuffer michael@0: // michael@0: // This is called whenever the buffer has filled (free_in_buffer reaches michael@0: // zero). In typical applications, it should write out the *entire* buffer michael@0: // (use the saved start address and buffer length; ignore the current state michael@0: // of next_output_byte and free_in_buffer). Then reset the pointer & count michael@0: // to the start of the buffer, and return TRUE indicating that the buffer michael@0: // has been dumped. free_in_buffer must be set to a positive value when michael@0: // TRUE is returned. A FALSE return should only be used when I/O suspension michael@0: // is desired (this operating mode is discussed in the next section). michael@0: michael@0: boolean // static michael@0: nsJPEGEncoder::emptyOutputBuffer(jpeg_compress_struct* cinfo) michael@0: { michael@0: nsJPEGEncoder* that = static_cast(cinfo->client_data); michael@0: NS_ASSERTION(that->mImageBuffer, "No buffer to empty!"); michael@0: michael@0: // When we're reallocing the buffer we need to take the lock to ensure michael@0: // that nobody is trying to read from the buffer we are destroying michael@0: ReentrantMonitorAutoEnter autoEnter(that->mReentrantMonitor); michael@0: michael@0: that->mImageBufferUsed = that->mImageBufferSize; michael@0: michael@0: // expand buffer, just double size each time michael@0: that->mImageBufferSize *= 2; michael@0: michael@0: uint8_t* newBuf = (uint8_t*)moz_realloc(that->mImageBuffer, michael@0: that->mImageBufferSize); michael@0: if (! newBuf) { michael@0: // can't resize, just zero (this will keep us from writing more) michael@0: moz_free(that->mImageBuffer); michael@0: that->mImageBuffer = nullptr; michael@0: that->mImageBufferSize = 0; michael@0: that->mImageBufferUsed = 0; michael@0: michael@0: // This seems to be the only way to do errors through the JPEG library. We michael@0: // pass an nsresult masquerading as an int, which works because the michael@0: // setjmp() caller casts it back. michael@0: longjmp(((encoder_error_mgr*)(cinfo->err))->setjmp_buffer, michael@0: static_cast(NS_ERROR_OUT_OF_MEMORY)); michael@0: } michael@0: that->mImageBuffer = newBuf; michael@0: michael@0: cinfo->dest->next_output_byte = &that->mImageBuffer[that->mImageBufferUsed]; michael@0: cinfo->dest->free_in_buffer = that->mImageBufferSize - that->mImageBufferUsed; michael@0: return 1; michael@0: } michael@0: michael@0: michael@0: // nsJPEGEncoder::termDestination michael@0: // michael@0: // Terminate destination --- called by jpeg_finish_compress() after all data michael@0: // has been written. In most applications, this must flush any data michael@0: // remaining in the buffer. Use either next_output_byte or free_in_buffer michael@0: // to determine how much data is in the buffer. michael@0: michael@0: void // static michael@0: nsJPEGEncoder::termDestination(jpeg_compress_struct* cinfo) michael@0: { michael@0: nsJPEGEncoder* that = static_cast(cinfo->client_data); michael@0: if (! that->mImageBuffer) michael@0: return; michael@0: that->mImageBufferUsed = cinfo->dest->next_output_byte - that->mImageBuffer; michael@0: NS_ASSERTION(that->mImageBufferUsed < that->mImageBufferSize, michael@0: "JPEG library busted, got a bad image buffer size"); michael@0: that->NotifyListener(); michael@0: } michael@0: michael@0: michael@0: // nsJPEGEncoder::errorExit michael@0: // michael@0: // Override the standard error method in the IJG JPEG decoder code. This michael@0: // was mostly copied from nsJPEGDecoder.cpp michael@0: michael@0: void // static michael@0: nsJPEGEncoder::errorExit(jpeg_common_struct* cinfo) michael@0: { michael@0: nsresult error_code; michael@0: encoder_error_mgr *err = (encoder_error_mgr *) cinfo->err; michael@0: michael@0: // Convert error to a browser error code michael@0: switch (cinfo->err->msg_code) { michael@0: case JERR_OUT_OF_MEMORY: michael@0: error_code = NS_ERROR_OUT_OF_MEMORY; michael@0: break; michael@0: default: michael@0: error_code = NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: // Return control to the setjmp point. We pass an nsresult masquerading as michael@0: // an int, which works because the setjmp() caller casts it back. michael@0: longjmp(err->setjmp_buffer, static_cast(error_code)); michael@0: } michael@0: michael@0: void michael@0: nsJPEGEncoder::NotifyListener() michael@0: { michael@0: // We might call this function on multiple threads (any threads that call michael@0: // AsyncWait and any that do encoding) so we lock to avoid notifying the michael@0: // listener twice about the same data (which generally leads to a truncated michael@0: // image). michael@0: ReentrantMonitorAutoEnter autoEnter(mReentrantMonitor); michael@0: michael@0: if (mCallback && michael@0: (mImageBufferUsed - mImageBufferReadPoint >= mNotifyThreshold || michael@0: mFinished)) { michael@0: nsCOMPtr callback; michael@0: if (mCallbackTarget) { michael@0: callback = NS_NewInputStreamReadyEvent(mCallback, mCallbackTarget); michael@0: } else { michael@0: callback = mCallback; michael@0: } michael@0: michael@0: NS_ASSERTION(callback, "Shouldn't fail to make the callback"); michael@0: // Null the callback first because OnInputStreamReady could reenter michael@0: // AsyncWait michael@0: mCallback = nullptr; michael@0: mCallbackTarget = nullptr; michael@0: mNotifyThreshold = 0; michael@0: michael@0: callback->OnInputStreamReady(this); michael@0: } michael@0: }