1/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "client_utils/android/BitmapRegionDecoder.h"
9#include "client_utils/android/BitmapRegionDecoderPriv.h"
10#include "include/codec/SkAndroidCodec.h"
11#include "src/codec/SkCodecPriv.h"
12
13namespace android {
14namespace skia {
15
16std::unique_ptr<BitmapRegionDecoder> BitmapRegionDecoder::Make(sk_sp<SkData> data) {
17    auto codec = SkAndroidCodec::MakeFromData(std::move(data));
18    if (nullptr == codec) {
19        SkCodecPrintf("Error: Failed to create codec.\n");
20        return nullptr;
21    }
22
23    switch (codec->getEncodedFormat()) {
24        case SkEncodedImageFormat::kJPEG:
25        case SkEncodedImageFormat::kPNG:
26        case SkEncodedImageFormat::kWEBP:
27        case SkEncodedImageFormat::kHEIF:
28            break;
29        default:
30            return nullptr;
31    }
32
33    return std::unique_ptr<BitmapRegionDecoder>(new BitmapRegionDecoder(std::move(codec)));
34}
35
36BitmapRegionDecoder::BitmapRegionDecoder(std::unique_ptr<SkAndroidCodec> codec)
37    : fCodec(std::move(codec))
38{}
39
40int BitmapRegionDecoder::width() const {
41    return fCodec->getInfo().width();
42}
43
44int BitmapRegionDecoder::height() const {
45    return fCodec->getInfo().height();
46}
47
48bool BitmapRegionDecoder::decodeRegion(SkBitmap* bitmap, BRDAllocator* allocator,
49        const SkIRect& desiredSubset, int sampleSize, SkColorType dstColorType,
50        bool requireUnpremul, sk_sp<SkColorSpace> dstColorSpace) {
51
52    // Fix the input sampleSize if necessary.
53    if (sampleSize < 1) {
54        sampleSize = 1;
55    }
56
57    // The size of the output bitmap is determined by the size of the
58    // requested subset, not by the size of the intersection of the subset
59    // and the image dimensions.
60    // If inputX is negative, we will need to place decoded pixels into the
61    // output bitmap starting at a left offset.  Call this outX.
62    // If outX is non-zero, subsetX must be zero.
63    // If inputY is negative, we will need to place decoded pixels into the
64    // output bitmap starting at a top offset.  Call this outY.
65    // If outY is non-zero, subsetY must be zero.
66    int outX;
67    int outY;
68    SkIRect subset = desiredSubset;
69    SubsetType type = adjust_subset_rect(fCodec->getInfo().dimensions(), &subset, &outX, &outY);
70    if (SubsetType::kOutside_SubsetType == type) {
71        return false;
72    }
73
74    // Ask the codec for a scaled subset
75    if (!fCodec->getSupportedSubset(&subset)) {
76        SkCodecPrintf("Error: Could not get subset.\n");
77        return false;
78    }
79    SkISize scaledSize = fCodec->getSampledSubsetDimensions(sampleSize, subset);
80
81    // Create the image info for the decode
82    SkAlphaType dstAlphaType = fCodec->computeOutputAlphaType(requireUnpremul);
83    SkImageInfo decodeInfo =
84            SkImageInfo::Make(scaledSize, dstColorType, dstAlphaType, dstColorSpace);
85
86    // Initialize the destination bitmap
87    int scaledOutX = 0;
88    int scaledOutY = 0;
89    int scaledOutWidth = scaledSize.width();
90    int scaledOutHeight = scaledSize.height();
91    if (SubsetType::kPartiallyInside_SubsetType == type) {
92        scaledOutX = outX / sampleSize;
93        scaledOutY = outY / sampleSize;
94        // We need to be safe here because getSupportedSubset() may have modified the subset.
95        const int extraX = std::max(0, desiredSubset.width() - outX - subset.width());
96        const int extraY = std::max(0, desiredSubset.height() - outY - subset.height());
97        const int scaledExtraX = extraX / sampleSize;
98        const int scaledExtraY = extraY / sampleSize;
99        scaledOutWidth += scaledOutX + scaledExtraX;
100        scaledOutHeight += scaledOutY + scaledExtraY;
101    }
102    SkImageInfo outInfo = decodeInfo.makeWH(scaledOutWidth, scaledOutHeight);
103    if (kGray_8_SkColorType == dstColorType) {
104        // The legacy implementations of BitmapFactory and BitmapRegionDecoder
105        // used kAlpha8 for grayscale images (before kGray8 existed).  While
106        // the codec recognizes kGray8, we need to decode into a kAlpha8
107        // bitmap in order to avoid a behavior change.
108        outInfo = outInfo.makeColorType(kAlpha_8_SkColorType).makeAlphaType(kPremul_SkAlphaType);
109    }
110    bitmap->setInfo(outInfo);
111    if (!bitmap->tryAllocPixels(allocator)) {
112        SkCodecPrintf("Error: Could not allocate pixels.\n");
113        return false;
114    }
115
116    // Zero the bitmap if the region is not completely within the image.
117    // TODO (msarett): Can we make this faster by implementing it to only
118    //                 zero parts of the image that we won't overwrite with
119    //                 pixels?
120    SkCodec::ZeroInitialized zeroInit = allocator ? allocator->zeroInit() :
121            SkCodec::kNo_ZeroInitialized;
122    if (SubsetType::kPartiallyInside_SubsetType == type &&
123            SkCodec::kNo_ZeroInitialized == zeroInit) {
124        void* pixels = bitmap->getPixels();
125        size_t bytes = outInfo.computeByteSize(bitmap->rowBytes());
126        memset(pixels, 0, bytes);
127    }
128
129    // Decode into the destination bitmap
130    SkAndroidCodec::AndroidOptions options;
131    options.fSampleSize = sampleSize;
132    options.fSubset = &subset;
133    options.fZeroInitialized = zeroInit;
134    void* dst = bitmap->getAddr(scaledOutX, scaledOutY);
135
136    SkCodec::Result result = fCodec->getAndroidPixels(decodeInfo, dst, bitmap->rowBytes(),
137            &options);
138    switch (result) {
139        case SkCodec::kSuccess:
140        case SkCodec::kIncompleteInput:
141        case SkCodec::kErrorInInput:
142            return true;
143        default:
144            SkCodecPrintf("Error: Could not get pixels with message \"%s\".\n",
145                          SkCodec::ResultToString(result));
146            return false;
147    }
148}
149
150} // namespace skia
151} // namespace android
152