Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "imgTools.h"
#include "DecodePool.h"
#include "gfxUtils.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/RefPtr.h"
#include "nsCOMPtr.h"
#include "mozilla/dom/Document.h"
#include "nsError.h"
#include "imgLoader.h"
#include "imgICache.h"
#include "imgIContainer.h"
#include "imgIEncoder.h"
#include "nsComponentManagerUtils.h"
#include "nsNetUtil.h" // for NS_NewBufferedInputStream
#include "nsStreamUtils.h"
#include "nsStringStream.h"
#include "nsContentUtils.h"
#include "nsProxyRelease.h"
#include "nsIStreamListener.h"
#include "ImageFactory.h"
#include "Image.h"
#include "IProgressObserver.h"
#include "ScriptedNotificationObserver.h"
#include "imgIScriptedNotificationObserver.h"
#include "gfxPlatform.h"
#include "js/ArrayBuffer.h"
#include "js/RootingAPI.h" // JS::{Handle,Rooted}
#include "js/Value.h" // JS::Value
#include "Orientation.h"
using namespace mozilla::gfx;
namespace mozilla {
namespace image {
namespace {
static nsresult sniff_mimetype_callback(nsIInputStream* in, void* data,
const char* fromRawSegment,
uint32_t toOffset, uint32_t count,
uint32_t* writeCount) {
nsCString* mimeType = static_cast<nsCString*>(data);
MOZ_ASSERT(mimeType, "mimeType is null!");
if (count > 0) {
imgLoader::GetMimeTypeFromContent(fromRawSegment, count, *mimeType);
}
*writeCount = 0;
return NS_ERROR_FAILURE;
}
class ImageDecoderListener final : public nsIStreamListener,
public IProgressObserver,
public imgIContainer {
public:
NS_DECL_ISUPPORTS
ImageDecoderListener(nsIURI* aURI, imgIContainerCallback* aCallback,
imgINotificationObserver* aObserver)
: mURI(aURI),
mImage(nullptr),
mCallback(aCallback),
mObserver(aObserver) {
MOZ_ASSERT(NS_IsMainThread());
}
NS_IMETHOD
OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInputStream,
uint64_t aOffset, uint32_t aCount) override {
if (!mImage) {
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
nsCString mimeType;
channel->GetContentType(mimeType);
if (aInputStream) {
// Look at the first few bytes and see if we can tell what the data is
// from that since servers tend to lie. :(
uint32_t unused;
aInputStream->ReadSegments(sniff_mimetype_callback, &mimeType, aCount,
&unused);
}
RefPtr<ProgressTracker> tracker = new ProgressTracker();
if (mObserver) {
tracker->AddObserver(this);
}
mImage = ImageFactory::CreateImage(channel, tracker, mimeType, mURI,
/* aIsMultiPart */ false, 0);
if (mImage->HasError()) {
return NS_ERROR_FAILURE;
}
}
return mImage->OnImageDataAvailable(aRequest, aInputStream, aOffset,
aCount);
}
NS_IMETHOD
OnStartRequest(nsIRequest* aRequest) override { return NS_OK; }
NS_IMETHOD
OnStopRequest(nsIRequest* aRequest, nsresult aStatus) override {
// Encouter a fetch error, or no data could be fetched.
if (!mImage || NS_FAILED(aStatus)) {
mCallback->OnImageReady(nullptr, mImage ? aStatus : NS_ERROR_FAILURE);
return NS_OK;
}
mImage->OnImageDataComplete(aRequest, aStatus, true);
nsCOMPtr<imgIContainer> container = this;
mCallback->OnImageReady(container, aStatus);
return NS_OK;
}
virtual void Notify(int32_t aType,
const nsIntRect* aRect = nullptr) override {
if (mObserver) {
mObserver->Notify(nullptr, aType, aRect);
}
}
virtual void OnLoadComplete(bool aLastPart) override {}
// Other notifications are ignored.
virtual void SetHasImage() override {}
virtual bool NotificationsDeferred() const override { return false; }
virtual void MarkPendingNotify() override {}
virtual void ClearPendingNotify() override {}
// imgIContainer
NS_FORWARD_IMGICONTAINER(mImage->)
private:
virtual ~ImageDecoderListener() = default;
nsCOMPtr<nsIURI> mURI;
RefPtr<image::Image> mImage;
nsCOMPtr<imgIContainerCallback> mCallback;
nsCOMPtr<imgINotificationObserver> mObserver;
};
NS_IMPL_ISUPPORTS(ImageDecoderListener, nsIStreamListener, imgIContainer)
class ImageDecoderHelper final : public Runnable,
public nsIInputStreamCallback {
public:
NS_DECL_ISUPPORTS_INHERITED
ImageDecoderHelper(already_AddRefed<image::Image> aImage,
already_AddRefed<nsIInputStream> aInputStream,
nsIEventTarget* aEventTarget,
imgIContainerCallback* aCallback,
nsIEventTarget* aCallbackEventTarget)
: Runnable("ImageDecoderHelper"),
mImage(std::move(aImage)),
mInputStream(std::move(aInputStream)),
mEventTarget(aEventTarget),
mCallback(aCallback),
mCallbackEventTarget(aCallbackEventTarget),
mStatus(NS_OK) {
MOZ_ASSERT(NS_IsMainThread());
}
NS_IMETHOD
Run() override {
// This runnable is dispatched on the Image thread when reading data, but
// at the end, it goes back to the main-thread in order to complete the
// operation.
if (NS_IsMainThread()) {
// Let the Image know we've sent all the data.
mImage->OnImageDataComplete(nullptr, mStatus, true);
RefPtr<ProgressTracker> tracker = mImage->GetProgressTracker();
tracker->SyncNotifyProgress(FLAG_LOAD_COMPLETE);
nsCOMPtr<imgIContainer> container;
if (NS_SUCCEEDED(mStatus)) {
container = mImage;
}
mCallback->OnImageReady(container, mStatus);
return NS_OK;
}
uint64_t length;
nsresult rv = mInputStream->Available(&length);
if (rv == NS_BASE_STREAM_CLOSED) {
return OperationCompleted(NS_OK);
}
if (NS_WARN_IF(NS_FAILED(rv))) {
return OperationCompleted(rv);
}
// Nothing else to read, but maybe we just need to wait.
if (length == 0) {
nsCOMPtr<nsIAsyncInputStream> asyncInputStream =
do_QueryInterface(mInputStream);
if (asyncInputStream) {
rv = asyncInputStream->AsyncWait(this, 0, 0, mEventTarget);
if (NS_WARN_IF(NS_FAILED(rv))) {
return OperationCompleted(rv);
}
return NS_OK;
}
// We really have nothing else to read.
if (length == 0) {
return OperationCompleted(NS_OK);
}
}
// Send the source data to the Image.
rv = mImage->OnImageDataAvailable(nullptr, mInputStream, 0,
uint32_t(length));
if (NS_WARN_IF(NS_FAILED(rv))) {
return OperationCompleted(rv);
}
rv = mEventTarget->Dispatch(this, NS_DISPATCH_NORMAL);
if (NS_WARN_IF(NS_FAILED(rv))) {
return OperationCompleted(rv);
}
return NS_OK;
}
NS_IMETHOD
OnInputStreamReady(nsIAsyncInputStream* aAsyncInputStream) override {
MOZ_ASSERT(!NS_IsMainThread());
return Run();
}
nsresult OperationCompleted(nsresult aStatus) {
MOZ_ASSERT(!NS_IsMainThread());
mStatus = aStatus;
mCallbackEventTarget->Dispatch(this, NS_DISPATCH_NORMAL);
return NS_OK;
}
private:
~ImageDecoderHelper() {
SurfaceCache::ReleaseImageOnMainThread(mImage.forget());
NS_ReleaseOnMainThread("ImageDecoderHelper::mCallback", mCallback.forget());
}
RefPtr<image::Image> mImage;
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIEventTarget> mEventTarget;
nsCOMPtr<imgIContainerCallback> mCallback;
nsCOMPtr<nsIEventTarget> mCallbackEventTarget;
nsresult mStatus;
};
NS_IMPL_ISUPPORTS_INHERITED(ImageDecoderHelper, Runnable,
nsIInputStreamCallback)
} // namespace
/* ========== imgITools implementation ========== */
NS_IMPL_ISUPPORTS(imgTools, imgITools)
imgTools::imgTools() { /* member initializers and constructor code */
}
imgTools::~imgTools() { /* destructor code */
}
NS_IMETHODIMP
imgTools::DecodeImageFromArrayBuffer(JS::Handle<JS::Value> aArrayBuffer,
const nsACString& aMimeType,
JSContext* aCx,
imgIContainer** aContainer) {
if (!aArrayBuffer.isObject()) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JSObject*> obj(aCx,
JS::UnwrapArrayBuffer(&aArrayBuffer.toObject()));
if (!obj) {
return NS_ERROR_FAILURE;
}
uint8_t* bufferData = nullptr;
size_t bufferLength = 0;
bool isSharedMemory = false;
JS::GetArrayBufferLengthAndData(obj, &bufferLength, &isSharedMemory,
&bufferData);
// Throw for large ArrayBuffers to prevent truncation.
if (bufferLength > INT32_MAX) {
return NS_ERROR_ILLEGAL_VALUE;
}
return DecodeImageFromBuffer((char*)bufferData, bufferLength, aMimeType,
aContainer);
}
NS_IMETHODIMP
imgTools::DecodeImageFromBuffer(const char* aBuffer, uint32_t aSize,
const nsACString& aMimeType,
imgIContainer** aContainer) {
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_ARG_POINTER(aBuffer);
// Create a new image container to hold the decoded data.
nsAutoCString mimeType(aMimeType);
RefPtr<image::Image> image =
ImageFactory::CreateAnonymousImage(mimeType, aSize);
RefPtr<ProgressTracker> tracker = image->GetProgressTracker();
if (image->HasError()) {
return NS_ERROR_FAILURE;
}
// Let's create a temporary inputStream.
nsCOMPtr<nsIInputStream> stream;
nsresult rv = NS_NewByteInputStream(
getter_AddRefs(stream), Span(aBuffer, aSize), NS_ASSIGNMENT_DEPEND);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(stream);
MOZ_ASSERT(NS_InputStreamIsBuffered(stream));
rv = image->OnImageDataAvailable(nullptr, stream, 0, aSize);
NS_ENSURE_SUCCESS(rv, rv);
// Let the Image know we've sent all the data.
rv = image->OnImageDataComplete(nullptr, NS_OK, true);
tracker->SyncNotifyProgress(FLAG_LOAD_COMPLETE);
NS_ENSURE_SUCCESS(rv, rv);
// All done.
image.forget(aContainer);
return NS_OK;
}
NS_IMETHODIMP
imgTools::DecodeImageFromChannelAsync(nsIURI* aURI, nsIChannel* aChannel,
imgIContainerCallback* aCallback,
imgINotificationObserver* aObserver) {
MOZ_ASSERT(NS_IsMainThread());