Separate ImageDecoder JNI from actual work

Bug: 135133301
Test: CtsGraphicsTestCases ImageDecoderTest

Make the native ImageDecoder a class, with methods that do the bulk of
the work that was previously done in JNI. This will allow the
forthcoming NDK API (AImageDecoder) to share the same code for decoding.

Move enums into implementation file, as no other code needs them.

Make computeAllocationSize a public static method on hwui/Bitmap, for
use by ImageDecoder.

Change-Id: I4e4dae338a951761614aed42ca2cc157e3d526dd
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index f670cf9..d945fc4 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -176,6 +176,7 @@
         "hwui/AnimatedImageThread.cpp",
         "hwui/Bitmap.cpp",
         "hwui/Canvas.cpp",
+        "hwui/ImageDecoder.cpp",
         "hwui/MinikinSkia.cpp",
         "hwui/MinikinUtils.cpp",
         "hwui/PaintImpl.cpp",
diff --git a/libs/hwui/hwui/Bitmap.cpp b/libs/hwui/hwui/Bitmap.cpp
index 2ba6fbe..f4149b9 100644
--- a/libs/hwui/hwui/Bitmap.cpp
+++ b/libs/hwui/hwui/Bitmap.cpp
@@ -44,9 +44,7 @@
 
 namespace android {
 
-// returns true if rowBytes * height can be represented by a positive int32_t value
-// and places that value in size.
-static bool computeAllocationSize(size_t rowBytes, int height, size_t* size) {
+bool Bitmap::computeAllocationSize(size_t rowBytes, int height, size_t* size) {
     return 0 <= height && height <= std::numeric_limits<size_t>::max() &&
            !__builtin_mul_overflow(rowBytes, (size_t)height, size) &&
            *size <= std::numeric_limits<int32_t>::max();
@@ -66,7 +64,7 @@
     // we must respect the rowBytes value already set on the bitmap instead of
     // attempting to compute our own.
     const size_t rowBytes = bitmap->rowBytes();
-    if (!computeAllocationSize(rowBytes, bitmap->height(), &size)) {
+    if (!Bitmap::computeAllocationSize(rowBytes, bitmap->height(), &size)) {
         return nullptr;
     }
 
diff --git a/libs/hwui/hwui/Bitmap.h b/libs/hwui/hwui/Bitmap.h
index 00733c6..1cda046 100644
--- a/libs/hwui/hwui/Bitmap.h
+++ b/libs/hwui/hwui/Bitmap.h
@@ -138,6 +138,10 @@
         return mPalette;
     }
 
+  // returns true if rowBytes * height can be represented by a positive int32_t value
+  // and places that value in size.
+  static bool computeAllocationSize(size_t rowBytes, int height, size_t* size);
+
 private:
     static sk_sp<Bitmap> allocateAshmemBitmap(size_t size, const SkImageInfo& i, size_t rowBytes);
     static sk_sp<Bitmap> allocateHeapBitmap(size_t size, const SkImageInfo& i, size_t rowBytes);
diff --git a/libs/hwui/hwui/ImageDecoder.cpp b/libs/hwui/hwui/ImageDecoder.cpp
new file mode 100644
index 0000000..4f2027d
--- /dev/null
+++ b/libs/hwui/hwui/ImageDecoder.cpp
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "ImageDecoder.h"
+
+#include <hwui/Bitmap.h>
+
+#include <SkAndroidCodec.h>
+#include <SkCanvas.h>
+#include <SkPaint.h>
+
+using namespace android;
+
+ImageDecoder::ImageDecoder(std::unique_ptr<SkAndroidCodec> codec, sk_sp<SkPngChunkReader> peeker)
+    : mCodec(std::move(codec))
+    , mPeeker(std::move(peeker))
+    , mTargetSize(mCodec->getInfo().dimensions())
+    , mDecodeSize(mTargetSize)
+    , mOutColorType(mCodec->computeOutputColorType(kN32_SkColorType))
+    , mOutAlphaType(mCodec->getInfo().isOpaque() ?
+                    kOpaque_SkAlphaType : kPremul_SkAlphaType)
+    , mOutColorSpace(mCodec->getInfo().refColorSpace())
+    , mSampleSize(1)
+{
+}
+
+bool ImageDecoder::setTargetSize(int width, int height) {
+    if (width <= 0 || height <= 0) {
+        return false;
+    }
+
+    auto info = SkImageInfo::Make(width, height, mOutColorType, mOutAlphaType);
+    size_t rowBytes = info.minRowBytes();
+    if (rowBytes == 0) {
+        // This would have overflowed.
+        return false;
+    }
+
+    size_t pixelMemorySize;
+    if (!Bitmap::computeAllocationSize(rowBytes, height, &pixelMemorySize)) {
+        return false;
+    }
+
+    if (mCropRect) {
+        if (mCropRect->right() > width || mCropRect->bottom() > height) {
+            return false;
+        }
+    }
+
+    SkISize targetSize = { width, height }, decodeSize = targetSize;
+    int sampleSize = mCodec->computeSampleSize(&decodeSize);
+
+    if (decodeSize != targetSize && mOutAlphaType == kUnpremul_SkAlphaType
+            && !mCodec->getInfo().isOpaque()) {
+        return false;
+    }
+
+    mTargetSize = targetSize;
+    mDecodeSize = decodeSize;
+    mSampleSize = sampleSize;
+    return true;
+}
+
+bool ImageDecoder::setCropRect(const SkIRect* crop) {
+    if (!crop) {
+        mCropRect.reset();
+        return true;
+    }
+
+    if (crop->left() >= crop->right() || crop->top() >= crop->bottom()) {
+        return false;
+    }
+
+    const auto& size = mTargetSize;
+    if (crop->left() < 0 || crop->top() < 0
+            || crop->right() > size.width() || crop->bottom() > size.height()) {
+      return false;
+    }
+
+    mCropRect.emplace(*crop);
+    return true;
+}
+
+bool ImageDecoder::setOutColorType(SkColorType colorType) {
+    switch (colorType) {
+        case kRGB_565_SkColorType:
+            if (!opaque()) {
+                return false;
+            }
+            break;
+        case kGray_8_SkColorType:
+            if (!gray()) {
+                return false;
+            }
+            mOutColorSpace = nullptr;
+            break;
+        case kN32_SkColorType:
+            break;
+        case kRGBA_F16_SkColorType:
+            break;
+        default:
+            return false;
+    }
+
+    mOutColorType = colorType;
+    return true;
+}
+
+bool ImageDecoder::setOutAlphaType(SkAlphaType alpha) {
+    switch (alpha) {
+        case kOpaque_SkAlphaType:
+            return opaque();
+        case kPremul_SkAlphaType:
+            if (opaque()) {
+                // Opaque can be treated as premul.
+                return true;
+            }
+            break;
+        case kUnpremul_SkAlphaType:
+            if (opaque()) {
+                // Opaque can be treated as unpremul.
+                return true;
+            }
+            if (mDecodeSize != mTargetSize) {
+                return false;
+            }
+            break;
+        default:
+            return false;
+    }
+    mOutAlphaType = alpha;
+    return true;
+}
+
+void ImageDecoder::setOutColorSpace(sk_sp<SkColorSpace> colorSpace) {
+    mOutColorSpace = std::move(colorSpace);
+}
+
+SkImageInfo ImageDecoder::getOutputInfo() const {
+    SkISize size = mCropRect ? mCropRect->size() : mTargetSize;
+    return SkImageInfo::Make(size, mOutColorType, mOutAlphaType, mOutColorSpace);
+}
+
+bool ImageDecoder::opaque() const {
+    return mOutAlphaType == kOpaque_SkAlphaType;
+}
+
+bool ImageDecoder::gray() const {
+    return mCodec->getInfo().colorType() == kGray_8_SkColorType;
+}
+
+SkCodec::Result ImageDecoder::decode(void* pixels, size_t rowBytes) {
+    void* decodePixels = pixels;
+    size_t decodeRowBytes = rowBytes;
+    auto decodeInfo = SkImageInfo::Make(mDecodeSize, mOutColorType, mOutAlphaType, mOutColorSpace);
+    // Used if we need a temporary before scaling or subsetting.
+    // FIXME: Use scanline decoding on only a couple lines to save memory. b/70709380.
+    SkBitmap tmp;
+    const bool scale = mDecodeSize != mTargetSize;
+    if (scale || mCropRect) {
+        if (!tmp.setInfo(decodeInfo)) {
+            return SkCodec::kInternalError;
+        }
+        if (!Bitmap::allocateHeapBitmap(&tmp)) {
+            return SkCodec::kInternalError;
+        }
+        decodePixels = tmp.getPixels();
+        decodeRowBytes = tmp.rowBytes();
+    }
+
+    SkAndroidCodec::AndroidOptions options;
+    options.fSampleSize = mSampleSize;
+    auto result = mCodec->getAndroidPixels(decodeInfo, decodePixels, decodeRowBytes, &options);
+
+    if (scale || mCropRect) {
+        SkBitmap scaledBm;
+        if (!scaledBm.installPixels(getOutputInfo(), pixels, rowBytes)) {
+            return SkCodec::kInternalError;
+        }
+
+        SkPaint paint;
+        paint.setBlendMode(SkBlendMode::kSrc);
+        paint.setFilterQuality(kLow_SkFilterQuality);  // bilinear filtering
+
+        SkCanvas canvas(scaledBm, SkCanvas::ColorBehavior::kLegacy);
+        if (mCropRect) {
+            canvas.translate(-mCropRect->fLeft, -mCropRect->fTop);
+        }
+        if (scale) {
+            float scaleX = (float) mTargetSize.width()  / mDecodeSize.width();
+            float scaleY = (float) mTargetSize.height() / mDecodeSize.height();
+            canvas.scale(scaleX, scaleY);
+        }
+
+        canvas.drawBitmap(tmp, 0.0f, 0.0f, &paint);
+    }
+
+    return result;
+}
+
diff --git a/libs/hwui/hwui/ImageDecoder.h b/libs/hwui/hwui/ImageDecoder.h
new file mode 100644
index 0000000..b956f4a
--- /dev/null
+++ b/libs/hwui/hwui/ImageDecoder.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <SkCodec.h>
+#include <SkImageInfo.h>
+#include <SkPngChunkReader.h>
+#include <SkRect.h>
+#include <SkSize.h>
+#include <cutils/compiler.h>
+
+#include <optional>
+
+class SkAndroidCodec;
+
+namespace android {
+
+class ANDROID_API ImageDecoder {
+public:
+    std::unique_ptr<SkAndroidCodec> mCodec;
+    sk_sp<SkPngChunkReader> mPeeker;
+
+    ImageDecoder(std::unique_ptr<SkAndroidCodec> codec,
+                 sk_sp<SkPngChunkReader> peeker = nullptr);
+
+    bool setTargetSize(int width, int height);
+    bool setCropRect(const SkIRect*);
+
+    bool setOutColorType(SkColorType outColorType);
+
+    bool setOutAlphaType(SkAlphaType outAlphaType);
+
+    void setOutColorSpace(sk_sp<SkColorSpace> cs);
+
+    // The size is the final size after scaling and cropping.
+    SkImageInfo getOutputInfo() const;
+    SkColorType getOutColorType() const { return mOutColorType; }
+    SkAlphaType getOutAlphaType() const { return mOutAlphaType; }
+
+    bool opaque() const;
+    bool gray() const;
+
+    SkCodec::Result decode(void* pixels, size_t rowBytes);
+
+private:
+    SkISize mTargetSize;
+    SkISize mDecodeSize;
+    SkColorType mOutColorType;
+    SkAlphaType mOutAlphaType;
+    sk_sp<SkColorSpace> mOutColorSpace;
+    int mSampleSize;
+    std::optional<SkIRect> mCropRect;
+
+    ImageDecoder(const ImageDecoder&) = delete;
+    ImageDecoder& operator=(const ImageDecoder&) = delete;
+};
+
+} // namespace android