Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(129)

Unified Diff: src/codec/SkRawCodec.cpp

Issue 1520403003: Prototype of RAW decoding in Skia. (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Fix bug in transferBuffer. Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: src/codec/SkRawCodec.cpp
diff --git a/src/codec/SkRawCodec.cpp b/src/codec/SkRawCodec.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b44755e4e324ecbe4acda23b187e04ed46295e30
--- /dev/null
+++ b/src/codec/SkRawCodec.cpp
@@ -0,0 +1,450 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "SkCodec.h"
+#include "SkCodecPriv.h"
+#include "SkColorPriv.h"
+#include "SkData.h"
+#if !defined(GOOGLE3)
+#include "SkJpegCodec.h"
+#endif
+#include "SkRawCodec.h"
+#include "SkRefCnt.h"
+#include "SkStream.h"
+#include "SkStreamPriv.h"
+#include "SkSwizzler.h"
+#include "SkTemplates.h"
+#include "SkTypes.h"
+
+#include "dng_color_space.h"
+#include "dng_exceptions.h"
+#include "dng_host.h"
+#include "dng_info.h"
+#include "dng_memory.h"
+#include "dng_render.h"
+#include "dng_stream.h"
+
+#include "src/piex.h"
+
+#include <cmath> // for std::round,floor,ceil
+#include <limits>
+
+namespace {
+
+// T must be unsigned type.
+template <class T>
+bool safe_add_to_size_t(T arg1, T arg2, size_t* result) {
+ SkASSERT(arg1 >= 0);
+ SkASSERT(arg2 >= 0);
+ if (arg1 >= 0 && arg2 <= std::numeric_limits<T>::max() - arg1) {
+ T sum = arg1 + arg2;
+ if (sum <= std::numeric_limits<size_t>::max()) {
+ *result = static_cast<size_t>(sum);
+ return true;
+ }
+ }
+ return false;
+}
+
+class SkDngMemoryAllocator : public dng_memory_allocator {
+public:
+ virtual ~SkDngMemoryAllocator() {}
scroggo 2016/01/20 18:13:36 nit: I think we generally drop the virtual and use
yujieqin 2016/01/20 21:42:19 Done.
+
+ dng_memory_block* Allocate(uint32 size) override {
+ // To avoid arbitary allocation requests which might lead to out-of-memory, limit the
+ // amount of memory that can be allocated at once. The memory limit is based on experiments
+ // and supposed to be sufficient for all valid DNG images.
+ if (size > 300 * 1024 * 1024) { // 300 MB
+ ThrowMemoryFull();
+ }
+ return dng_memory_allocator::Allocate(size);
+ }
+};
+
+} // namespace
+
+// Note: this class could throw exception if it is used as dng_stream.
+class SkRawStream : public dng_stream, public ::piex::StreamInterface {
+public:
+ // Note that this call will take the ownership of stream.
+ explicit SkRawStream(SkStream* stream)
+ : fStream(stream), fWholeStreamRead(false) {}
+
+ ~SkRawStream() override {}
+
+ /*
+ * Creates an SkMemoryStream from the offset with size.
+ * Note: for performance reason, this function is destructive to the SkRawStream. One should
+ * abandon current object after the function call.
+ */
+ SkMemoryStream* transferBuffer(size_t offset, size_t size) {
+ SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
+ if (offset > fStreamBuffer.bytesWritten()) {
+ // If the offset is not buffered, read from fStream directly and skip the buffering.
+ const size_t skipLength = offset - fStreamBuffer.bytesWritten();
+ if (fStream->skip(skipLength) != skipLength) {
+ return nullptr;
+ }
+ const size_t bytesRead = fStream->read(data->writable_data(), size);
+ if (bytesRead < size) {
+ data.reset(SkData::NewSubset(data.get(), 0, bytesRead));
+ }
+ } else {
+ const size_t alreadyBuffered = SkTMin(fStreamBuffer.bytesWritten() - offset, size);
+ if (alreadyBuffered > 0 &&
scroggo 2016/01/20 18:13:36 It looks like we forgot to consider the case where
yujieqin 2016/01/20 21:42:20 Yes, it seems like the SkDynamicMemoryWStream.read
scroggo 2016/01/21 16:36:09 I filed skbug.com/4836 to investigate.
+ !fStreamBuffer.read(data->writable_data(), offset, alreadyBuffered)) {
+ return nullptr;
+ }
+
+ const size_t remaining = size - alreadyBuffered;
+ if (remaining) {
+ auto* dst = static_cast<uint8_t*>(data->writable_data()) + alreadyBuffered;
+ const size_t bytesRead = fStream->read(dst, remaining);
+ size_t newSize;
+ if (bytesRead < remaining) {
+ if (!safe_add_to_size_t(alreadyBuffered, bytesRead, &newSize)) {
+ return nullptr;
+ }
+ data.reset(SkData::NewSubset(data.get(), 0, newSize));
+ }
+ }
+ }
+ return new SkMemoryStream(data);
+ }
+
+ // For PIEX
+ ::piex::Error GetData(const size_t offset, const size_t length,
+ uint8* data) override {
+ if (offset == 0 && length == 0) {
+ return ::piex::Error::kOk;
+ }
+ size_t sum;
+ if (!safe_add_to_size_t(offset, length, &sum) || !this->bufferMoreData(sum)) {
+ return ::piex::Error::kFail;
+ }
+ if (!fStreamBuffer.read(data, offset, length)) {
+ return ::piex::Error::kFail;
+ }
+ return ::piex::Error::kOk;
+ }
+
+protected:
+ // For dng_stream
+ uint64 DoGetLength() override {
+ if (!this->bufferMoreData(kReadToEnd)) { // read whole stream
+ ThrowReadFile();
+ }
+ return fStreamBuffer.bytesWritten();
+ }
+
+ // For dng_stream
+ void DoRead(void* data, uint32 count, uint64 offset) override {
+ if (count == 0 && offset == 0) {
+ return;
+ }
+ size_t sum;
+ if (!safe_add_to_size_t(static_cast<uint64>(count), offset, &sum) ||
+ !this->bufferMoreData(sum)) {
+ ThrowReadFile();
+ }
+
+ if (!fStreamBuffer.read(data, offset, count)) {
+ ThrowReadFile();
+ }
+ }
+
+private:
+ // Note: if the newSize == kReadToEnd (0), this function will read to the end of stream.
+ bool bufferMoreData(size_t newSize) {
+ if (newSize == kReadToEnd) {
+ if (fWholeStreamRead) { // already read-to-end.
+ return true;
+ }
+
+ // TODO: optimize for the special case when the input is SkMemoryStream.
+ return SkStreamCopy(&fStreamBuffer, fStream.get());
+ }
+
+ if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to newSize
+ return true;
+ }
+ if (fWholeStreamRead) { // newSize is larger than the whole stream.
+ return false;
+ }
+
+ const size_t sizeToRead = newSize - fStreamBuffer.bytesWritten();
+ SkAutoTMalloc<uint8> tempBuffer(sizeToRead);
+ const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead);
+ if (bytesRead != sizeToRead) {
+ return false;
+ }
+ return fStreamBuffer.write(tempBuffer.get(), bytesRead);
+ }
+
+ SkAutoTDelete<SkStream> fStream;
+ bool fWholeStreamRead;
+
+ SkDynamicMemoryWStream fStreamBuffer;
+
+ const size_t kReadToEnd = 0;
+};
+
+class SkDngImage {
+public:
+ static SkDngImage* NewFromStream(SkRawStream* stream) {
+ SkAutoTDelete<SkDngImage> dngImage(new SkDngImage(stream));
+ if (!dngImage->readDng()) {
+ return nullptr;
+ }
+
+ SkASSERT(dngImage->fNegative);
+ return dngImage.release();
+ }
+
+ /*
+ * Renders the DNG image to the size. The DNG SDK only allows scaling close to integer factors
+ * down to 80 pixels on the short edge. The rendered image will be close to the specified size,
+ * but there is no guarantee that any of the edges will match the requested size. E.g.
+ * 100% size: 4000 x 3000
+ * requested size: 1600 x 1200
+ * returned size could be: 2000 x 1500
+ */
+ dng_image* render(int width, int height) {
+ // render() takes ownership of fHost, fInfo and fNegative when available.
+ SkAutoTDelete<dng_host> host;
+ SkAutoTDelete<dng_info> info;
+ SkAutoTDelete<dng_negative> negative;
+ if (!fHost || !fInfo || !fNegative) {
+ SkCodecPrintf("Warning: SkDngImage::render() is called multiple times.");
scroggo 2016/01/20 18:13:36 I don't think this print statement is still necess
yujieqin 2016/01/20 21:42:19 Removed.
+ if (!this->readDng()) {
+ return nullptr;
+ }
+ } else {
+ host.reset(fHost.release());
+ info.reset(fInfo.release());
+ negative.reset(fNegative.release());
+ }
+
+ // DNG SDK preserves the aspect ratio, so it only needs to know the longer dimension.
+ const int preferredSize = SkTMax(width, height);
+ try {
+ host->SetPreferredSize(preferredSize);
+ host->ValidateSizes();
+
+ negative->ReadStage1Image(*host, *fStream, *info);
+
+ if (info->fMaskIndex != -1) {
+ negative->ReadTransparencyMask(*host, *fStream, *info);
+ }
+
+ negative->ValidateRawImageDigest(*host);
+ if (negative->IsDamaged()) {
+ return nullptr;
+ }
+
+ const int32 kMosaicPlane = -1;
+ negative->BuildStage2Image(*host);
+ negative->BuildStage3Image(*host, kMosaicPlane);
+
+ dng_render render(*host, *negative);
+ render.SetFinalSpace(dng_space_sRGB::Get());
+ render.SetFinalPixelType(ttByte);
+
+ dng_point stage3_size = negative->Stage3Image()->Size();
+ render.SetMaximumSize(SkTMax(stage3_size.h, stage3_size.v));
+
+ return render.Render();
+ } catch (...) {
+ return nullptr;
+ }
+ }
+
+ const SkImageInfo& getImageInfo() const {
+ return fImageInfo;
+ }
+
+ bool isXtransImage() const {
+ return fIsXtransImage;
+ }
+
+private:
+ bool readDng() {
+ // Due to the limit of DNG SDK, we need to reset host and info.
+ fHost.reset(new dng_host(&fAllocator));
+ fInfo.reset(new dng_info);
+ try {
+ fHost->ValidateSizes();
+ fInfo->Parse(*fHost, *fStream);
+ fInfo->PostParse(*fHost);
+ if (!fInfo->IsValidDNG()) {
+ return false;
+ }
+
+ fNegative.reset(fHost->Make_dng_negative());
+ fNegative->Parse(*fHost, *fStream, *fInfo);
+ fNegative->PostParse(*fHost, *fStream, *fInfo);
+ fNegative->SynchronizeMetadata();
+
+ fImageInfo = SkImageInfo::Make(fNegative->DefaultCropSizeH().As_real64(),
+ fNegative->DefaultCropSizeV().As_real64(),
+ kN32_SkColorType, kOpaque_SkAlphaType);
+ fIsXtransImage = fNegative->GetMosaicInfo() != nullptr
+ ? (fNegative->GetMosaicInfo()->fCFAPatternSize.v == 6
+ && fNegative->GetMosaicInfo()->fCFAPatternSize.h == 6)
+ : false;
+ return true;
+ } catch (...) {
+ fNegative.reset(nullptr);
+ return false;
+ }
+ }
+
+ SkDngImage(SkRawStream* stream)
+ : fStream(stream) {}
+
+ SkDngMemoryAllocator fAllocator;
+ SkAutoTDelete<SkRawStream> fStream;
+ SkAutoTDelete<dng_host> fHost;
+ SkAutoTDelete<dng_info> fInfo;
+ SkAutoTDelete<dng_negative> fNegative;
+
+ SkImageInfo fImageInfo;
+ bool fIsXtransImage;
+};
+
+/*
+ * Tries to handle the image with PIEX. If PIEX returns kOk and finds the preview image, create a
+ * SkJpegCodec. If PIEX returns kFail, then the file is invalid, return nullptr. In other cases,
+ * fallback to create SkRawCodec for DNG images.
+ */
+SkCodec* SkRawCodec::NewFromStream(SkStream* stream) {
+ SkAutoTDelete<SkRawStream> rawStream(new SkRawStream(stream));
+ ::piex::PreviewImageData imageData;
+ if (::piex::IsRaw(rawStream.get())) {
+ ::piex::Error error = ::piex::GetPreviewImageData(rawStream.get(), &imageData);
msarett 2016/01/20 20:23:17 This has the potential to "reallocate" the SkRawSt
yujieqin 2016/01/20 21:42:20 I am also aware of this issue. There is surely sti
+
+ if (error == ::piex::Error::kOk && imageData.preview_length > 0) {
msarett 2016/01/20 20:23:17 Bad Case Stream Memory Use for Raw Image with Piex
yujieqin 2016/01/20 21:42:20 The position of embedded preview is unpredictable
msarett 2016/01/21 15:46:16 Acknowledged.
scroggo 2016/01/21 16:36:09 We've already done something to help this problem
msarett 2016/01/21 16:48:49 Good point. Unfortunately, in my testing, it look
+#if !defined(GOOGLE3)
+ // transferBuffer() is destructive to the rawStream. Abandon the rawStream after this
+ // function call.
+ SkMemoryStream* memoryStream =
+ rawStream->transferBuffer(imageData.preview_offset, imageData.preview_length);
msarett 2016/01/20 20:23:17 This operation involves allocating a new 1-4 MB bu
scroggo 2016/01/20 20:36:24 (1) Not sure if this is where you were going with
msarett 2016/01/20 20:43:52 (1) Agreed. (2) Seems like a bad idea to hold onto
yujieqin 2016/01/20 21:42:20 Added FIXME. But, as said, the location of the emb
msarett 2016/01/21 15:46:16 Acknowledged.
+ return memoryStream ? SkJpegCodec::NewFromStream(memoryStream) : nullptr;
+#else
+ return nullptr;
+#endif
+ } else if (error == ::piex::Error::kFail) {
+ return nullptr;
+ }
+ }
+
+ SkAutoTDelete<SkDngImage> dngImage(SkDngImage::NewFromStream(rawStream.release()));
msarett 2016/01/20 20:23:17 It looks to me like ::piex::IsRaw() returns true f
yujieqin 2016/01/20 21:42:20 Similar to the type checks in SkCodec.cpp, the ::p
msarett 2016/01/21 15:46:16 Understood. Would it be possible to make it a lon
scroggo 2016/01/21 16:36:10 FWIW, SkCodec.cpp's type checks may offer false po
yujieqin 2016/01/21 17:44:26 Unfortunately, yes. Due to the variations of RAW f
+ if (!dngImage) {
+ return nullptr;
+ }
+
+ return new SkRawCodec(dngImage.release());
msarett 2016/01/20 20:23:17 Bad Case Memory Use for Dng Image without Preview:
yujieqin 2016/01/20 21:42:20 Unfortunately, the length is required by DNG SDK,
msarett 2016/01/21 15:46:16 Can we make it a longer term goal to "fix" the DNG
+}
+
+SkCodec::Result SkRawCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
+ size_t dstRowBytes, const Options& options,
+ SkPMColor ctable[], int* ctableCount,
+ int* rowsDecoded) {
+ if (!conversion_possible(requestedInfo, this->getInfo())) {
+ SkCodecPrintf("Error: cannot convert input type to output type.\n");
+ return kInvalidConversion;
+ }
+
+ SkAutoTDelete<SkSwizzler> swizzler(SkSwizzler::CreateSwizzler(
+ SkSwizzler::kRGB, nullptr, requestedInfo, options));
+ if (!swizzler) {
msarett 2016/01/20 20:23:17 I think that, because conversion_possible succeede
yujieqin 2016/01/20 21:42:19 I think the 565 does not work in current test, the
msarett 2016/01/21 15:46:16 No, SkSwizzler had a bug where we forgot to add th
yujieqin 2016/01/21 16:40:01 Yeah, after rebase, I don't need this check anymor
+ SkCodecPrintf("Error: cannot create swizzler.\n");
+ return kInvalidConversion;
+ }
+
+ const int width = requestedInfo.width();
+ const int height = requestedInfo.height();
+ SkAutoTDelete<dng_image> image(fDngImage->render(width, height));
+ if (!image) {
+ return kInvalidInput;
+ }
+
+ // Because the DNG SDK can not guarantee to render to requested size, we allow a small
+ // difference. Only the overlapping region will be converted in onGetPixels().
scroggo 2016/01/20 18:13:36 nit: "in onGetPixels()" seems unnecessary here - t
yujieqin 2016/01/20 21:42:20 Done.
+ const float maxDiffRatio = 1.03f;
+ const dng_point& imageSize = image->Size();
+ if (imageSize.h / width > maxDiffRatio || imageSize.h < width ||
+ imageSize.v / height > maxDiffRatio || imageSize.v < height) {
+ return SkCodec::kInvalidScale;
scroggo 2016/01/20 18:13:36 Is this code ever reached? This gets called by SkC
yujieqin 2016/01/20 21:42:20 adaubert@ wrote a test to verify this part could h
adaubert 2016/01/21 10:43:30 In practice we should be safe and this case should
scroggo 2016/01/21 16:36:10 I guess that's fine. My real concern would be if g
+ }
+
+ void* dstRow = dst;
+ uint8_t srcRow[width * 3];
+
+ dng_pixel_buffer buffer;
+ buffer.fData = &srcRow[0];
+ buffer.fPlane = 0;
+ buffer.fPlanes = 3;
+ buffer.fColStep = buffer.fPlanes;
+ buffer.fPlaneStep = 1;
+ buffer.fPixelType = ttByte;
+ buffer.fPixelSize = sizeof(uint8_t);
+ buffer.fRowStep = sizeof(srcRow);
+
+ for (int i = 0; i < height; ++i) {
+ buffer.fArea = dng_rect(i, 0, i + 1, width);
+
+ try {
+ image->Get(buffer, dng_image::edge_zero);
+ } catch (...) {
+ *rowsDecoded = i;
+ return kIncompleteInput;
+ }
+
+ swizzler->swizzle(dstRow, &srcRow[0]);
+ dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
+ }
+ return kSuccess;
+}
+
+SkISize SkRawCodec::onGetScaledDimensions(float desiredScale) const {
+ SkASSERT(desiredScale <= 1.f);
+ const SkISize dim = this->getInfo().dimensions();
+
+ // Limits the minimum size to be 80 on the short edge.
+ const float shortEdge = SkTMin(dim.fWidth, dim.fHeight);
+ if (desiredScale < 80.f / shortEdge) {
+ desiredScale = 80.f / shortEdge;
+ }
+
+ // For Xtrans images, the integer-factor scaling does not support the half-size scaling case
+ // (stronger downscalings are fine). In this case, returns the non-scaled version.
scroggo 2016/01/20 18:13:36 So this is saying that scaling by a half is not su
msarett 2016/01/20 20:23:17 I've changed that code multiple times for multiple
yujieqin 2016/01/20 21:42:20 Just for clarification, does it mean we can keep o
adaubert 2016/01/21 10:43:30 Downscaling to a smaller size, in this case 1/3, w
msarett 2016/01/21 15:46:16 Leon?
scroggo 2016/01/21 16:36:09 My preference would be 1/3 for now. The caller can
yujieqin 2016/01/21 17:44:26 Sure, 1/3 it is now. :)
+ if (fDngImage->isXtransImage() && desiredScale >= 0.5f) {
+ return dim;
+ }
+
+ // Round to integer-factors.
+ const float finalScale = std::floor(1.f/ desiredScale);
+ return SkISize::Make(std::floor(dim.fWidth / finalScale),
+ std::floor(dim.fHeight / finalScale));
+}
+
+bool SkRawCodec::onDimensionsSupported(const SkISize& dim) {
scroggo 2016/01/20 18:13:36 All this scaling code seems complex. Should we add
yujieqin 2016/01/20 21:42:20 * The image in current CL is not xtrans. * I think
scroggo 2016/01/21 16:36:09 I think that's a fine start.
+ const SkISize fullDim = this->getInfo().dimensions();
+ const float fullShortEdge = SkTMin(fullDim.fWidth, fullDim.fHeight);
+ const float shortEdge = SkTMin(dim.fWidth, dim.fHeight);
+
+ SkISize sizeFloor = this->onGetScaledDimensions(1.f / std::floor(fullShortEdge / shortEdge));
+ SkISize sizeCeil = this->onGetScaledDimensions(1.f / std::ceil(fullShortEdge / shortEdge));
+ return sizeFloor == dim || sizeCeil == dim;
+}
+
+SkRawCodec::~SkRawCodec() {}
+
+SkRawCodec::SkRawCodec(SkDngImage* dngImage)
+ : INHERITED(dngImage->getImageInfo(), nullptr)
+ , fDngImage(dngImage) {}

Powered by Google App Engine
This is Rietveld 408576698