1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #undef LOG_TAG
18 #define LOG_TAG "BitmapRegionDecoder"
19 
20 #include "BitmapRegionDecoder.h"
21 
22 #include <HardwareBitmapUploader.h>
23 #include <androidfw/Asset.h>
24 #include <sys/stat.h>
25 
26 #include <memory>
27 
28 #include "BitmapFactory.h"
29 #include "CreateJavaOutputStreamAdaptor.h"
30 #include "Gainmap.h"
31 #include "GraphicsJNI.h"
32 #include "SkBitmap.h"
33 #include "SkCodec.h"
34 #include "SkColorSpace.h"
35 #include "SkData.h"
36 #include "SkGainmapInfo.h"
37 #include "SkStream.h"
38 #include "SkStreamPriv.h"
39 #include "Utils.h"
40 
41 using namespace android;
42 
43 namespace android {
44 class BitmapRegionDecoderWrapper {
45 public:
Make(sk_sp<SkData> data)46     static std::unique_ptr<BitmapRegionDecoderWrapper> Make(sk_sp<SkData> data) {
47         std::unique_ptr<skia::BitmapRegionDecoder> mainImageBRD =
48                 skia::BitmapRegionDecoder::Make(std::move(data));
49         if (!mainImageBRD) {
50             return nullptr;
51         }
52 
53         SkGainmapInfo gainmapInfo;
54         std::unique_ptr<SkStream> gainmapStream;
55         std::unique_ptr<skia::BitmapRegionDecoder> gainmapBRD = nullptr;
56         if (mainImageBRD->getAndroidGainmap(&gainmapInfo, &gainmapStream)) {
57             sk_sp<SkData> data = nullptr;
58             if (gainmapStream->getMemoryBase()) {
59                 // It is safe to make without copy because we'll hold onto the stream.
60                 data = SkData::MakeWithoutCopy(gainmapStream->getMemoryBase(),
61                                                gainmapStream->getLength());
62             } else {
63                 data = SkCopyStreamToData(gainmapStream.get());
64                 // We don't need to hold the stream anymore
65                 gainmapStream = nullptr;
66             }
67             gainmapBRD = skia::BitmapRegionDecoder::Make(std::move(data));
68         }
69 
70         return std::unique_ptr<BitmapRegionDecoderWrapper>(
71                 new BitmapRegionDecoderWrapper(std::move(mainImageBRD), std::move(gainmapBRD),
72                                                gainmapInfo, std::move(gainmapStream)));
73     }
74 
getEncodedFormat()75     SkEncodedImageFormat getEncodedFormat() { return mMainImageBRD->getEncodedFormat(); }
76 
computeOutputColorType(SkColorType requestedColorType)77     SkColorType computeOutputColorType(SkColorType requestedColorType) {
78         return mMainImageBRD->computeOutputColorType(requestedColorType);
79     }
80 
computeOutputColorSpace(SkColorType outputColorType,sk_sp<SkColorSpace> prefColorSpace=nullptr)81     sk_sp<SkColorSpace> computeOutputColorSpace(SkColorType outputColorType,
82                                                 sk_sp<SkColorSpace> prefColorSpace = nullptr) {
83         return mMainImageBRD->computeOutputColorSpace(outputColorType, prefColorSpace);
84     }
85 
decodeRegion(SkBitmap * bitmap,skia::BRDAllocator * allocator,const SkIRect & desiredSubset,int sampleSize,SkColorType colorType,bool requireUnpremul,sk_sp<SkColorSpace> prefColorSpace)86     bool decodeRegion(SkBitmap* bitmap, skia::BRDAllocator* allocator, const SkIRect& desiredSubset,
87                       int sampleSize, SkColorType colorType, bool requireUnpremul,
88                       sk_sp<SkColorSpace> prefColorSpace) {
89         return mMainImageBRD->decodeRegion(bitmap, allocator, desiredSubset, sampleSize, colorType,
90                                            requireUnpremul, prefColorSpace);
91     }
92 
decodeGainmapRegion(sp<uirenderer::Gainmap> * outGainmap,int outWidth,int outHeight,const SkIRect & desiredSubset,int sampleSize,bool requireUnpremul)93     bool decodeGainmapRegion(sp<uirenderer::Gainmap>* outGainmap, int outWidth, int outHeight,
94                              const SkIRect& desiredSubset, int sampleSize, bool requireUnpremul) {
95         SkColorType decodeColorType = mGainmapBRD->computeOutputColorType(kN32_SkColorType);
96         sk_sp<SkColorSpace> decodeColorSpace =
97                 mGainmapBRD->computeOutputColorSpace(decodeColorType, nullptr);
98         SkBitmap bm;
99         // Because we must match the dimensions of the base bitmap, we always use a
100         // recycling allocator even though we are allocating a new bitmap. This is to ensure
101         // that if a recycled bitmap was used for the base image that we match the relative
102         // dimensions of that base image. The behavior of BRD here is:
103         // if inBitmap is specified -> output dimensions are always equal to the inBitmap's
104         // if no bitmap is reused   -> output dimensions are the intersect of the desiredSubset &
105         //                           the image bounds
106         // The handling of the above conditionals are baked into the desiredSubset, so we
107         // simply need to ensure that the resulting bitmap is the exact same width/height as
108         // the specified desiredSubset regardless of the intersection to the image bounds.
109         // kPremul_SkAlphaType is used just as a placeholder as it doesn't change the underlying
110         // allocation type. RecyclingClippingPixelAllocator will populate this with the
111         // actual alpha type in either allocPixelRef() or copyIfNecessary()
112         sk_sp<Bitmap> nativeBitmap = Bitmap::allocateHeapBitmap(SkImageInfo::Make(
113                 outWidth, outHeight, decodeColorType, kPremul_SkAlphaType, decodeColorSpace));
114         if (!nativeBitmap) {
115             ALOGE("OOM allocating Bitmap for Gainmap");
116             return false;
117         }
118         RecyclingClippingPixelAllocator allocator(nativeBitmap.get(), false);
119         if (!mGainmapBRD->decodeRegion(&bm, &allocator, desiredSubset, sampleSize, decodeColorType,
120                                        requireUnpremul, decodeColorSpace)) {
121             ALOGE("Error decoding Gainmap region");
122             return false;
123         }
124         allocator.copyIfNecessary();
125         auto gainmap = sp<uirenderer::Gainmap>::make();
126         if (!gainmap) {
127             ALOGE("OOM allocating Gainmap");
128             return false;
129         }
130         gainmap->info = mGainmapInfo;
131         gainmap->bitmap = std::move(nativeBitmap);
132         *outGainmap = std::move(gainmap);
133         return true;
134     }
135 
calculateGainmapRegion(const SkIRect & mainImageRegion,int * inOutWidth,int * inOutHeight)136     SkIRect calculateGainmapRegion(const SkIRect& mainImageRegion, int* inOutWidth,
137                                    int* inOutHeight) {
138         const float scaleX = ((float)mGainmapBRD->width()) / mMainImageBRD->width();
139         const float scaleY = ((float)mGainmapBRD->height()) / mMainImageBRD->height();
140         *inOutWidth *= scaleX;
141         *inOutHeight *= scaleY;
142         // TODO: Account for rounding error?
143         return SkIRect::MakeLTRB(mainImageRegion.left() * scaleX, mainImageRegion.top() * scaleY,
144                                  mainImageRegion.right() * scaleX,
145                                  mainImageRegion.bottom() * scaleY);
146     }
147 
hasGainmap()148     bool hasGainmap() { return mGainmapBRD != nullptr; }
149 
width() const150     int width() const { return mMainImageBRD->width(); }
height() const151     int height() const { return mMainImageBRD->height(); }
152 
153 private:
BitmapRegionDecoderWrapper(std::unique_ptr<skia::BitmapRegionDecoder> mainImageBRD,std::unique_ptr<skia::BitmapRegionDecoder> gainmapBRD,SkGainmapInfo info,std::unique_ptr<SkStream> stream)154     BitmapRegionDecoderWrapper(std::unique_ptr<skia::BitmapRegionDecoder> mainImageBRD,
155                                std::unique_ptr<skia::BitmapRegionDecoder> gainmapBRD,
156                                SkGainmapInfo info, std::unique_ptr<SkStream> stream)
157             : mMainImageBRD(std::move(mainImageBRD))
158             , mGainmapBRD(std::move(gainmapBRD))
159             , mGainmapInfo(info)
160             , mGainmapStream(std::move(stream)) {}
161 
162     std::unique_ptr<skia::BitmapRegionDecoder> mMainImageBRD;
163     std::unique_ptr<skia::BitmapRegionDecoder> mGainmapBRD;
164     SkGainmapInfo mGainmapInfo;
165     std::unique_ptr<SkStream> mGainmapStream;
166 };
167 }  // namespace android
168 
createBitmapRegionDecoder(JNIEnv * env,sk_sp<SkData> data)169 static jobject createBitmapRegionDecoder(JNIEnv* env, sk_sp<SkData> data) {
170     auto brd = android::BitmapRegionDecoderWrapper::Make(std::move(data));
171     if (!brd) {
172         doThrowIOE(env, "Image format not supported");
173         return nullObjectReturn("CreateBitmapRegionDecoder returned null");
174     }
175 
176     return GraphicsJNI::createBitmapRegionDecoder(env, brd.release());
177 }
178 
nativeNewInstanceFromByteArray(JNIEnv * env,jobject,jbyteArray byteArray,jint offset,jint length)179 static jobject nativeNewInstanceFromByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
180                                               jint offset, jint length) {
181     AutoJavaByteArray ar(env, byteArray);
182     return createBitmapRegionDecoder(env, SkData::MakeWithCopy(ar.ptr() + offset, length));
183 }
184 
nativeNewInstanceFromFileDescriptor(JNIEnv * env,jobject clazz,jobject fileDescriptor)185 static jobject nativeNewInstanceFromFileDescriptor(JNIEnv* env, jobject clazz,
186                                                    jobject fileDescriptor) {
187     NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
188 
189     jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
190 
191     struct stat fdStat;
192     if (fstat(descriptor, &fdStat) == -1) {
193         doThrowIOE(env, "broken file descriptor");
194         return nullObjectReturn("fstat return -1");
195     }
196 
197     return createBitmapRegionDecoder(env, SkData::MakeFromFD(descriptor));
198 }
199 
nativeNewInstanceFromStream(JNIEnv * env,jobject clazz,jobject is,jbyteArray storage)200 static jobject nativeNewInstanceFromStream(JNIEnv* env, jobject clazz, jobject is, // InputStream
201                                            jbyteArray storage) { // byte[]
202     jobject brd = nullptr;
203     sk_sp<SkData> data = CopyJavaInputStream(env, is, storage);
204 
205     if (data) {
206         brd = createBitmapRegionDecoder(env, std::move(data));
207     }
208     return brd;
209 }
210 
nativeNewInstanceFromAsset(JNIEnv * env,jobject clazz,jlong native_asset)211 static jobject nativeNewInstanceFromAsset(JNIEnv* env, jobject clazz, jlong native_asset) {
212     Asset* asset = reinterpret_cast<Asset*>(native_asset);
213     sk_sp<SkData> data = CopyAssetToData(asset);
214     if (!data) {
215         return nullptr;
216     }
217 
218     return createBitmapRegionDecoder(env, data);
219 }
220 
221 /*
222  * nine patch not supported
223  * purgeable not supported
224  * reportSizeToVM not supported
225  */
nativeDecodeRegion(JNIEnv * env,jobject,jlong brdHandle,jint inputX,jint inputY,jint inputWidth,jint inputHeight,jobject options,jlong inBitmapHandle,jlong colorSpaceHandle)226 static jobject nativeDecodeRegion(JNIEnv* env, jobject, jlong brdHandle, jint inputX,
227         jint inputY, jint inputWidth, jint inputHeight, jobject options, jlong inBitmapHandle,
228         jlong colorSpaceHandle) {
229 
230     // Set default options.
231     int sampleSize = 1;
232     SkColorType colorType = kN32_SkColorType;
233     bool requireUnpremul = false;
234     jobject javaBitmap = nullptr;
235     bool isHardware = false;
236     sk_sp<SkColorSpace> colorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
237     // Update the default options with any options supplied by the client.
238     if (NULL != options) {
239         sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
240         jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
241         colorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
242         isHardware = GraphicsJNI::isHardwareConfig(env, jconfig);
243         requireUnpremul = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
244         javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
245         // The Java options of ditherMode and preferQualityOverSpeed are deprecated.  We will
246         // ignore the values of these fields.
247 
248         // Initialize these fields to indicate a failure.  If the decode succeeds, we
249         // will update them later on.
250         env->SetIntField(options, gOptions_widthFieldID, -1);
251         env->SetIntField(options, gOptions_heightFieldID, -1);
252         env->SetObjectField(options, gOptions_mimeFieldID, 0);
253         env->SetObjectField(options, gOptions_outConfigFieldID, 0);
254         env->SetObjectField(options, gOptions_outColorSpaceFieldID, 0);
255     }
256 
257     // Recycle a bitmap if possible.
258     android::Bitmap* recycledBitmap = nullptr;
259     if (javaBitmap) {
260         recycledBitmap = &bitmap::toBitmap(inBitmapHandle);
261         if (recycledBitmap->isImmutable()) {
262             ALOGW("Warning: Reusing an immutable bitmap as an image decoder target.");
263         }
264     }
265 
266     auto* brd = reinterpret_cast<BitmapRegionDecoderWrapper*>(brdHandle);
267     SkColorType decodeColorType = brd->computeOutputColorType(colorType);
268 
269     if (isHardware) {
270         if (decodeColorType == kRGBA_F16_SkColorType &&
271             !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
272             decodeColorType = kN32_SkColorType;
273         }
274         if (decodeColorType == kRGBA_1010102_SkColorType &&
275             !uirenderer::HardwareBitmapUploader::has1010102Support()) {
276             decodeColorType = kN32_SkColorType;
277         }
278     }
279 
280     // Set up the pixel allocator
281     skia::BRDAllocator* allocator = nullptr;
282     RecyclingClippingPixelAllocator recycleAlloc(recycledBitmap);
283     HeapAllocator heapAlloc;
284     if (javaBitmap) {
285         allocator = &recycleAlloc;
286         // We are required to match the color type of the recycled bitmap.
287         decodeColorType = recycledBitmap->info().colorType();
288     } else {
289         allocator = &heapAlloc;
290     }
291 
292     sk_sp<SkColorSpace> decodeColorSpace = brd->computeOutputColorSpace(
293             decodeColorType, colorSpace);
294 
295     // Decode the region.
296     const SkIRect subset = SkIRect::MakeXYWH(inputX, inputY, inputWidth, inputHeight);
297     SkBitmap bitmap;
298     if (!brd->decodeRegion(&bitmap, allocator, subset, sampleSize,
299             decodeColorType, requireUnpremul, decodeColorSpace)) {
300         return nullObjectReturn("Failed to decode region.");
301     }
302 
303     // If the client provided options, indicate that the decode was successful.
304     if (NULL != options) {
305         env->SetIntField(options, gOptions_widthFieldID, bitmap.width());
306         env->SetIntField(options, gOptions_heightFieldID, bitmap.height());
307 
308         env->SetObjectField(options, gOptions_mimeFieldID,
309                 getMimeTypeAsJavaString(env, brd->getEncodedFormat()));
310         if (env->ExceptionCheck()) {
311             return nullObjectReturn("OOM in encodedFormatToString()");
312         }
313 
314         jint configID = GraphicsJNI::colorTypeToLegacyBitmapConfig(decodeColorType);
315         if (isHardware) {
316             configID = GraphicsJNI::kHardware_LegacyBitmapConfig;
317         }
318         jobject config = env->CallStaticObjectMethod(gBitmapConfig_class,
319                 gBitmapConfig_nativeToConfigMethodID, configID);
320         env->SetObjectField(options, gOptions_outConfigFieldID, config);
321 
322         env->SetObjectField(options, gOptions_outColorSpaceFieldID,
323                 GraphicsJNI::getColorSpace(env, decodeColorSpace.get(), decodeColorType));
324     }
325 
326     if (javaBitmap) {
327         recycleAlloc.copyIfNecessary();
328     }
329 
330     sp<uirenderer::Gainmap> gainmap;
331     bool hasGainmap = brd->hasGainmap();
332     if (hasGainmap) {
333         int gainmapWidth = bitmap.width();
334         int gainmapHeight = bitmap.height();
335         if (javaBitmap) {
336             // If we are recycling we must match the inBitmap's relative dimensions
337             gainmapWidth = recycledBitmap->width();
338             gainmapHeight = recycledBitmap->height();
339         }
340         SkIRect gainmapSubset = brd->calculateGainmapRegion(subset, &gainmapWidth, &gainmapHeight);
341         if (!brd->decodeGainmapRegion(&gainmap, gainmapWidth, gainmapHeight, gainmapSubset,
342                                       sampleSize, requireUnpremul)) {
343             // If there is an error decoding Gainmap - we don't fail. We just don't provide Gainmap
344             hasGainmap = false;
345         }
346     }
347 
348     // If we may have reused a bitmap, we need to indicate that the pixels have changed.
349     if (javaBitmap) {
350         if (hasGainmap) {
351             recycledBitmap->setGainmap(std::move(gainmap));
352         }
353         bitmap::reinitBitmap(env, javaBitmap, recycledBitmap->info(), !requireUnpremul);
354         return javaBitmap;
355     }
356 
357     int bitmapCreateFlags = 0;
358     if (!requireUnpremul) {
359         bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Premultiplied;
360     }
361 
362     if (isHardware) {
363         sk_sp<Bitmap> hardwareBitmap = Bitmap::allocateHardwareBitmap(bitmap);
364         if (hasGainmap) {
365             auto gm = uirenderer::Gainmap::allocateHardwareGainmap(gainmap);
366             if (gm) {
367                 hardwareBitmap->setGainmap(std::move(gm));
368             }
369         }
370         return bitmap::createBitmap(env, hardwareBitmap.release(), bitmapCreateFlags);
371     }
372     Bitmap* heapBitmap = heapAlloc.getStorageObjAndReset();
373     if (hasGainmap && heapBitmap != nullptr) {
374         heapBitmap->setGainmap(std::move(gainmap));
375     }
376     return android::bitmap::createBitmap(env, heapBitmap, bitmapCreateFlags);
377 }
378 
nativeGetHeight(JNIEnv * env,jobject,jlong brdHandle)379 static jint nativeGetHeight(JNIEnv* env, jobject, jlong brdHandle) {
380     auto* brd = reinterpret_cast<BitmapRegionDecoderWrapper*>(brdHandle);
381     return static_cast<jint>(brd->height());
382 }
383 
nativeGetWidth(JNIEnv * env,jobject,jlong brdHandle)384 static jint nativeGetWidth(JNIEnv* env, jobject, jlong brdHandle) {
385     auto* brd = reinterpret_cast<BitmapRegionDecoderWrapper*>(brdHandle);
386     return static_cast<jint>(brd->width());
387 }
388 
nativeClean(JNIEnv * env,jobject,jlong brdHandle)389 static void nativeClean(JNIEnv* env, jobject, jlong brdHandle) {
390     auto* brd = reinterpret_cast<BitmapRegionDecoderWrapper*>(brdHandle);
391     delete brd;
392 }
393 
394 ///////////////////////////////////////////////////////////////////////////////
395 
396 static const JNINativeMethod gBitmapRegionDecoderMethods[] = {
397     {   "nativeDecodeRegion",
398         "(JIIIILandroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
399         (void*)nativeDecodeRegion},
400 
401     {   "nativeGetHeight", "(J)I", (void*)nativeGetHeight},
402 
403     {   "nativeGetWidth", "(J)I", (void*)nativeGetWidth},
404 
405     {   "nativeClean", "(J)V", (void*)nativeClean},
406 
407     {   "nativeNewInstance",
408         "([BII)Landroid/graphics/BitmapRegionDecoder;",
409         (void*)nativeNewInstanceFromByteArray
410     },
411 
412     {   "nativeNewInstance",
413         "(Ljava/io/InputStream;[B)Landroid/graphics/BitmapRegionDecoder;",
414         (void*)nativeNewInstanceFromStream
415     },
416 
417     {   "nativeNewInstance",
418         "(Ljava/io/FileDescriptor;)Landroid/graphics/BitmapRegionDecoder;",
419         (void*)nativeNewInstanceFromFileDescriptor
420     },
421 
422     {   "nativeNewInstance",
423         "(J)Landroid/graphics/BitmapRegionDecoder;",
424         (void*)nativeNewInstanceFromAsset
425     },
426 };
427 
register_android_graphics_BitmapRegionDecoder(JNIEnv * env)428 int register_android_graphics_BitmapRegionDecoder(JNIEnv* env)
429 {
430     return android::RegisterMethodsOrDie(env, "android/graphics/BitmapRegionDecoder",
431             gBitmapRegionDecoderMethods, NELEM(gBitmapRegionDecoderMethods));
432 }
433