blob: 8abcd9a59122d16bed00acc54f8f02eea534acc0 [file] [log] [blame]
Derek Sollenberger5368eda2019-10-25 11:20:03 -04001#undef LOG_TAG
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002#define LOG_TAG "BitmapFactory"
3
Joseph Wenf1f48bc2010-07-19 16:59:51 +08004#include "BitmapFactory.h"
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +00005
6#include <Gainmap.h>
7#include <HardwareBitmapUploader.h>
8#include <androidfw/Asset.h>
9#include <androidfw/ResourceTypes.h>
10#include <cutils/compiler.h>
11#include <fcntl.h>
12#include <nativehelper/JNIPlatformHelp.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <sys/stat.h>
16
17#include <memory>
18
Ben Wagner60126ef2015-08-07 12:13:48 -040019#include "CreateJavaOutputStreamAdaptor.h"
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -040020#include "FrontBufferedStream.h"
Ben Wagner60126ef2015-08-07 12:13:48 -040021#include "GraphicsJNI.h"
Derek Sollenberger2173ea22020-02-19 15:37:29 -050022#include "MimeType.h"
Leon Scrogginsa06d86a2011-03-02 16:56:54 -050023#include "NinePatchPeeker.h"
Matt Sarettb8adc9a2015-12-02 13:35:22 -050024#include "SkAndroidCodec.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050025#include "SkBitmap.h"
26#include "SkBlendMode.h"
John Reckbe671952021-01-13 22:39:32 -050027#include "SkCanvas.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050028#include "SkColorSpace.h"
29#include "SkEncodedImageFormat.h"
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +000030#include "SkGainmapInfo.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050031#include "SkImageInfo.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050032#include "SkPaint.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033#include "SkPixelRef.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050034#include "SkRect.h"
35#include "SkRefCnt.h"
36#include "SkSamplingOptions.h"
37#include "SkSize.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038#include "SkStream.h"
John Reckbe671952021-01-13 22:39:32 -050039#include "SkString.h"
Wei-Ta Chen6b849e22010-09-07 17:32:18 +080040#include "Utils.h"
Ben Wagner60126ef2015-08-07 12:13:48 -040041
Joseph Wenf1f48bc2010-07-19 16:59:51 +080042jfieldID gOptions_justBoundsFieldID;
43jfieldID gOptions_sampleSizeFieldID;
44jfieldID gOptions_configFieldID;
Romain Guy95648b82017-04-13 18:43:42 -070045jfieldID gOptions_colorSpaceFieldID;
Chris Craik1abf5d62013-08-16 12:47:03 -070046jfieldID gOptions_premultipliedFieldID;
Romain Guy23610982011-01-17 12:51:55 -080047jfieldID gOptions_mutableFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080048jfieldID gOptions_ditherFieldID;
Wei-Ta Chen953f9092010-12-03 14:06:18 -080049jfieldID gOptions_preferQualityOverSpeedFieldID;
Chris Craik905e8242013-06-05 09:59:05 -070050jfieldID gOptions_scaledFieldID;
51jfieldID gOptions_densityFieldID;
52jfieldID gOptions_screenDensityFieldID;
53jfieldID gOptions_targetDensityFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080054jfieldID gOptions_widthFieldID;
55jfieldID gOptions_heightFieldID;
56jfieldID gOptions_mimeFieldID;
Romain Guye8d2ebb2017-02-09 18:38:47 -080057jfieldID gOptions_outConfigFieldID;
Romain Guy90fc43b2017-03-30 12:35:26 -070058jfieldID gOptions_outColorSpaceFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080059jfieldID gOptions_mCancelID;
Chet Haase37f74ca2010-12-08 17:56:36 -080060jfieldID gOptions_bitmapFieldID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
Chris Craik47cd8e92014-07-08 17:13:08 -070062jfieldID gBitmap_ninePatchInsetsFieldID;
63
Romain Guye8d2ebb2017-02-09 18:38:47 -080064jclass gBitmapConfig_class;
65jmethodID gBitmapConfig_nativeToConfigMethodID;
66
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067using namespace android;
68
Leon Scroggins III407b5442019-11-22 17:10:20 -050069const char* getMimeType(SkEncodedImageFormat format) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -050070 switch (format) {
Hal Canary10219fb2016-11-23 20:41:22 -050071 case SkEncodedImageFormat::kBMP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050072 return "image/bmp";
Hal Canary10219fb2016-11-23 20:41:22 -050073 case SkEncodedImageFormat::kGIF:
Leon Scroggins III407b5442019-11-22 17:10:20 -050074 return "image/gif";
Hal Canary10219fb2016-11-23 20:41:22 -050075 case SkEncodedImageFormat::kICO:
Leon Scroggins III407b5442019-11-22 17:10:20 -050076 return "image/x-ico";
Hal Canary10219fb2016-11-23 20:41:22 -050077 case SkEncodedImageFormat::kJPEG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050078 return "image/jpeg";
Hal Canary10219fb2016-11-23 20:41:22 -050079 case SkEncodedImageFormat::kPNG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050080 return "image/png";
Hal Canary10219fb2016-11-23 20:41:22 -050081 case SkEncodedImageFormat::kWEBP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050082 return "image/webp";
Chong Zhang48fa8902017-08-16 11:57:02 -070083 case SkEncodedImageFormat::kHEIF:
Leon Scroggins III407b5442019-11-22 17:10:20 -050084 return "image/heif";
Vignesh Venkatasubramanian4a46b9e2020-11-05 22:55:43 -080085 case SkEncodedImageFormat::kAVIF:
86 return "image/avif";
Hal Canary10219fb2016-11-23 20:41:22 -050087 case SkEncodedImageFormat::kWBMP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050088 return "image/vnd.wap.wbmp";
Hal Canary10219fb2016-11-23 20:41:22 -050089 case SkEncodedImageFormat::kDNG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050090 return "image/x-adobe-dng";
Matt Sarettb8adc9a2015-12-02 13:35:22 -050091 default:
Leon Scroggins III407b5442019-11-22 17:10:20 -050092 return nullptr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 }
Leon Scroggins III407b5442019-11-22 17:10:20 -050094}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
Leon Scroggins III407b5442019-11-22 17:10:20 -050096jstring getMimeTypeAsJavaString(JNIEnv* env, SkEncodedImageFormat format) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +000097 jstring jstr = nullptr;
Leon Scroggins III407b5442019-11-22 17:10:20 -050098 const char* mimeType = getMimeType(format);
Matt Sarettb8adc9a2015-12-02 13:35:22 -050099 if (mimeType) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +0000100 // NOTE: Caller should env->ExceptionCheck() for OOM
101 // (can't check for nullptr as it's a valid return value)
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500102 jstr = env->NewStringUTF(mimeType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 }
104 return jstr;
105}
106
Chris Craik905e8242013-06-05 09:59:05 -0700107class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
108public:
109 ScaleCheckingAllocator(float scale, int size)
110 : mScale(scale), mSize(size) {
111 }
112
Mike Reed81397c42017-07-18 17:04:16 -0400113 virtual bool allocPixelRef(SkBitmap* bitmap) {
Chris Craik905e8242013-06-05 09:59:05 -0700114 // accounts for scale in final allocation, using eventual size and config
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400115 const int bytesPerPixel = SkColorTypeBytesPerPixel(bitmap->colorType());
Chris Craik905e8242013-06-05 09:59:05 -0700116 const int requestedSize = bytesPerPixel *
117 int(bitmap->width() * mScale + 0.5f) *
118 int(bitmap->height() * mScale + 0.5f);
119 if (requestedSize > mSize) {
120 ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
121 mSize, requestedSize);
122 return false;
123 }
Mike Reed81397c42017-07-18 17:04:16 -0400124 return SkBitmap::HeapAllocator::allocPixelRef(bitmap);
Chris Craik905e8242013-06-05 09:59:05 -0700125 }
126private:
127 const float mScale;
128 const int mSize;
129};
130
Chris Craik7e8c03c2013-06-03 13:53:36 -0700131class RecyclingPixelAllocator : public SkBitmap::Allocator {
132public:
sergeyvc1c54062016-10-19 18:47:26 -0700133 RecyclingPixelAllocator(android::Bitmap* bitmap, unsigned int size)
John Reckf29ed282015-04-07 07:32:03 -0700134 : mBitmap(bitmap), mSize(size) {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700135 }
136
137 ~RecyclingPixelAllocator() {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700138 }
139
Mike Reed81397c42017-07-18 17:04:16 -0400140 virtual bool allocPixelRef(SkBitmap* bitmap) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500141 const SkImageInfo& info = bitmap->info();
Leon Scroggins IIIf35b9892015-07-31 10:38:40 -0400142 if (info.colorType() == kUnknown_SkColorType) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500143 ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700144 return false;
145 }
Chris Craikcd0ba712013-09-06 14:40:30 -0700146
Mike Reed7569de02017-10-06 16:25:49 -0400147 const size_t size = info.computeByteSize(bitmap->rowBytes());
Kevin Lubickbab0bb32023-01-17 15:30:34 +0000148 if (size > INT32_MAX) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500149 ALOGW("bitmap is too large");
150 return false;
151 }
152
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500153 if (size > mSize) {
Dan Albert46d84442014-11-18 16:07:51 -0800154 ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap "
155 "(%zu bytes)", mSize, size);
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500156 return false;
157 }
158
Leon Scroggins IIIf51a80d2017-07-12 10:46:35 -0400159 mBitmap->reconfigure(info, bitmap->rowBytes());
Mike Reed826deef2017-04-04 15:32:04 -0400160 bitmap->setPixelRef(sk_ref_sp(mBitmap), 0, 0);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700161 return true;
162 }
163
164private:
sergeyvc1c54062016-10-19 18:47:26 -0700165 android::Bitmap* const mBitmap;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700166 const unsigned int mSize;
167};
168
Anton Daubert4e5ec342016-03-07 17:30:20 +0100169// Necessary for decodes when the native decoder cannot scale to appropriately match the sampleSize
170// (for example, RAW). If the sampleSize divides evenly into the dimension, we require that the
171// scale matches exactly. If sampleSize does not divide evenly, we allow the decoder to choose how
172// best to round.
173static bool needsFineScale(const int fullSize, const int decodedSize, const int sampleSize) {
174 if (fullSize % sampleSize == 0 && fullSize / sampleSize != decodedSize) {
175 return true;
176 } else if ((fullSize / sampleSize + 1) != decodedSize &&
177 (fullSize / sampleSize) != decodedSize) {
178 return true;
179 }
180 return false;
181}
182
183static bool needsFineScale(const SkISize fullSize, const SkISize decodedSize,
184 const int sampleSize) {
185 return needsFineScale(fullSize.width(), decodedSize.width(), sampleSize) ||
186 needsFineScale(fullSize.height(), decodedSize.height(), sampleSize);
187}
188
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000189static bool decodeGainmap(std::unique_ptr<SkStream> gainmapStream, const SkGainmapInfo& gainmapInfo,
190 sp<uirenderer::Gainmap>* outGainmap, const int sampleSize, float scale) {
191 std::unique_ptr<SkAndroidCodec> codec;
192 codec = SkAndroidCodec::MakeFromStream(std::move(gainmapStream), nullptr);
193 if (!codec) {
194 ALOGE("Can not create a codec for Gainmap.");
195 return false;
196 }
John Reck818328c2023-05-09 17:50:33 -0400197 SkColorType decodeColorType = kN32_SkColorType;
198 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
199 decodeColorType = kGray_8_SkColorType;
200 }
201 decodeColorType = codec->computeOutputColorType(decodeColorType);
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000202 sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(decodeColorType, nullptr);
203
204 SkISize size = codec->getSampledDimensions(sampleSize);
205
206 int scaledWidth = size.width();
207 int scaledHeight = size.height();
208 bool willScale = false;
209
210 // Apply a fine scaling step if necessary.
211 if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize) || scale != 1.0f) {
212 willScale = true;
213 // The operation below may loose precision (integer division), but it is put this way to
214 // mimic main image scale calculation
215 scaledWidth = static_cast<int>((codec->getInfo().width() / sampleSize) * scale + 0.5f);
216 scaledHeight = static_cast<int>((codec->getInfo().height() / sampleSize) * scale + 0.5f);
217 }
218
219 SkAlphaType alphaType = codec->computeOutputAlphaType(false);
220
221 const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(), decodeColorType,
222 alphaType, decodeColorSpace);
223
John Reck818328c2023-05-09 17:50:33 -0400224 SkImageInfo bitmapInfo = decodeInfo;
225 if (decodeColorType == kGray_8_SkColorType) {
226 // We treat gray8 as alpha8 in Bitmap's API surface
227 bitmapInfo = bitmapInfo.makeColorType(kAlpha_8_SkColorType);
228 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000229 SkBitmap decodeBitmap;
230 sk_sp<Bitmap> nativeBitmap = nullptr;
231
232 if (!decodeBitmap.setInfo(bitmapInfo)) {
233 ALOGE("Failed to setInfo.");
234 return false;
235 }
236
237 if (willScale) {
238 if (!decodeBitmap.tryAllocPixels(nullptr)) {
239 ALOGE("OOM allocating gainmap pixels.");
240 return false;
241 }
242 } else {
243 nativeBitmap = android::Bitmap::allocateHeapBitmap(&decodeBitmap);
244 if (!nativeBitmap) {
245 ALOGE("OOM allocating gainmap pixels.");
246 return false;
247 }
248 }
249
250 // Use SkAndroidCodec to perform the decode.
251 SkAndroidCodec::AndroidOptions codecOptions;
252 codecOptions.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
253 codecOptions.fSampleSize = sampleSize;
254 SkCodec::Result result = codec->getAndroidPixels(decodeInfo, decodeBitmap.getPixels(),
255 decodeBitmap.rowBytes(), &codecOptions);
256 switch (result) {
257 case SkCodec::kSuccess:
258 case SkCodec::kIncompleteInput:
259 break;
260 default:
261 ALOGE("Error decoding gainmap.");
262 return false;
263 }
264
265 if (willScale) {
266 SkBitmap gainmapBitmap;
267 const float scaleX = scaledWidth / float(decodeBitmap.width());
268 const float scaleY = scaledHeight / float(decodeBitmap.height());
269
270 SkColorType scaledColorType = decodeBitmap.colorType();
271 gainmapBitmap.setInfo(
272 bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
273
274 nativeBitmap = android::Bitmap::allocateHeapBitmap(&gainmapBitmap);
275 if (!nativeBitmap) {
276 ALOGE("OOM allocating gainmap pixels.");
277 return false;
278 }
279
280 SkPaint paint;
281 // kSrc_Mode instructs us to overwrite the uninitialized pixels in
282 // outputBitmap. Otherwise we would blend by default, which is not
283 // what we want.
284 paint.setBlendMode(SkBlendMode::kSrc);
285
286 SkCanvas canvas(gainmapBitmap, SkCanvas::ColorBehavior::kLegacy);
287 canvas.scale(scaleX, scaleY);
288 decodeBitmap.setImmutable(); // so .asImage() doesn't make a copy
289 canvas.drawImage(decodeBitmap.asImage(), 0.0f, 0.0f,
290 SkSamplingOptions(SkFilterMode::kLinear), &paint);
291 }
292
293 auto gainmap = sp<uirenderer::Gainmap>::make();
294 if (!gainmap) {
295 ALOGE("OOM allocating Gainmap");
296 return false;
297 }
298
299 gainmap->info = gainmapInfo;
300 gainmap->bitmap = std::move(nativeBitmap);
301 *outGainmap = std::move(gainmap);
302
303 return true;
304}
305
Mike Reedc7c65602017-07-26 10:40:25 -0400306static jobject doDecode(JNIEnv* env, std::unique_ptr<SkStreamRewindable> stream,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400307 jobject padding, jobject options, jlong inBitmapHandle,
308 jlong colorSpaceHandle) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500309 // Set default values for the options parameters.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 int sampleSize = 1;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500311 bool onlyDecodeSize = false;
Mike Reed42a1d082014-07-07 18:06:18 -0400312 SkColorType prefColorType = kN32_SkColorType;
sergeyvda6c8ffc2016-11-22 18:28:54 -0800313 bool isHardware = false;
Romain Guy23610982011-01-17 12:51:55 -0800314 bool isMutable = false;
Chris Craik905e8242013-06-05 09:59:05 -0700315 float scale = 1.0f;
Chris Craik1abf5d62013-08-16 12:47:03 -0700316 bool requireUnpremultiplied = false;
Chet Haase37f74ca2010-12-08 17:56:36 -0800317 jobject javaBitmap = NULL;
Leon Scroggins III0e443d12018-12-19 11:38:35 -0500318 sk_sp<SkColorSpace> prefColorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700319
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500320 // Update with options supplied by the client.
Romain Guy7b2f8b82012-03-19 17:18:54 -0700321 if (options != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500323 // Correct a non-positive sampleSize. sampleSize defaults to zero within the
324 // options object, which is strange.
325 if (sampleSize <= 0) {
326 sampleSize = 1;
327 }
328
329 if (env->GetBooleanField(options, gOptions_justBoundsFieldID)) {
330 onlyDecodeSize = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 // initialize these, in case we fail later on
334 env->SetIntField(options, gOptions_widthFieldID, -1);
335 env->SetIntField(options, gOptions_heightFieldID, -1);
336 env->SetObjectField(options, gOptions_mimeFieldID, 0);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800337 env->SetObjectField(options, gOptions_outConfigFieldID, 0);
Romain Guy90fc43b2017-03-30 12:35:26 -0700338 env->SetObjectField(options, gOptions_outColorSpaceFieldID, 0);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
Mike Reed42a1d082014-07-07 18:06:18 -0400341 prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
sergeyvda6c8ffc2016-11-22 18:28:54 -0800342 isHardware = GraphicsJNI::isHardwareConfig(env, jconfig);
Romain Guy23610982011-01-17 12:51:55 -0800343 isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
Chris Craik1abf5d62013-08-16 12:47:03 -0700344 requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
Chet Haase37f74ca2010-12-08 17:56:36 -0800345 javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
Chris Craik905e8242013-06-05 09:59:05 -0700346
347 if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
348 const int density = env->GetIntField(options, gOptions_densityFieldID);
349 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
350 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
351 if (density != 0 && targetDensity != 0 && density != screenDensity) {
352 scale = (float) targetDensity / density;
353 }
354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700356
sergeyv9fbb0b52016-11-23 10:27:33 -0800357 if (isMutable && isHardware) {
Hans Boehme5b337d2019-01-07 17:42:05 -0800358 doThrowIAE(env, "Bitmaps with Config.HARDWARE are always immutable");
sergeyv9fbb0b52016-11-23 10:27:33 -0800359 return nullObjectReturn("Cannot create mutable hardware bitmap");
360 }
361
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500362 // Create the codec.
363 NinePatchPeeker peeker;
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500364 std::unique_ptr<SkAndroidCodec> codec;
365 {
366 SkCodec::Result result;
367 std::unique_ptr<SkCodec> c = SkCodec::MakeFromStream(std::move(stream), &result,
368 &peeker);
369 if (!c) {
370 SkString msg;
371 msg.printf("Failed to create image decoder with message '%s'",
372 SkCodec::ResultToString(result));
373 return nullObjectReturn(msg.c_str());
374 }
375
376 codec = SkAndroidCodec::MakeFromCodec(std::move(c));
377 if (!codec) {
378 return nullObjectReturn("SkAndroidCodec::MakeFromCodec returned null");
379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700381
Matt Sarett3b1b68d2015-12-14 13:08:33 -0500382 // Do not allow ninepatch decodes to 565. In the past, decodes to 565
383 // would dither, and we do not want to pre-dither ninepatches, since we
384 // know that they will be stretched. We no longer dither 565 decodes,
385 // but we continue to prevent ninepatches from decoding to 565, in order
386 // to maintain the old behavior.
387 if (peeker.mPatch && kRGB_565_SkColorType == prefColorType) {
388 prefColorType = kN32_SkColorType;
389 }
390
Anton Daubert4e5ec342016-03-07 17:30:20 +0100391 // Determine the output size.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500392 SkISize size = codec->getSampledDimensions(sampleSize);
Anton Daubert4e5ec342016-03-07 17:30:20 +0100393
394 int scaledWidth = size.width();
395 int scaledHeight = size.height();
396 bool willScale = false;
397
398 // Apply a fine scaling step if necessary.
399 if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize)) {
400 willScale = true;
401 scaledWidth = codec->getInfo().width() / sampleSize;
402 scaledHeight = codec->getInfo().height() / sampleSize;
403 }
404
Romain Guye8d2ebb2017-02-09 18:38:47 -0800405 // Set the decode colorType
406 SkColorType decodeColorType = codec->computeOutputColorType(prefColorType);
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500407 if (decodeColorType == kRGBA_F16_SkColorType && isHardware &&
408 !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
409 decodeColorType = kN32_SkColorType;
410 }
411
Xiao Huangfff1a292023-04-12 17:37:36 +0000412 // b/276879147, fallback to RGBA_8888 when decoding HEIF and P010 is not supported.
413 if (decodeColorType == kRGBA_1010102_SkColorType &&
414 codec->getEncodedFormat() == SkEncodedImageFormat::kHEIF &&
415 env->CallStaticBooleanMethod(gImageDecoder_class,
416 gImageDecoder_isP010SupportedForHEVCMethodID) == JNI_FALSE) {
417 decodeColorType = kN32_SkColorType;
418 }
419
Romain Guy95648b82017-04-13 18:43:42 -0700420 sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(
421 decodeColorType, prefColorSpace);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800422
Anton Daubert4e5ec342016-03-07 17:30:20 +0100423 // Set the options and return if the client only wants the size.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500424 if (options != NULL) {
Leon Scroggins III407b5442019-11-22 17:10:20 -0500425 jstring mimeType = getMimeTypeAsJavaString(env, codec->getEncodedFormat());
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500426 if (env->ExceptionCheck()) {
Leon Scroggins III407b5442019-11-22 17:10:20 -0500427 return nullObjectReturn("OOM in getMimeTypeAsJavaString()");
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500428 }
Anton Daubert4e5ec342016-03-07 17:30:20 +0100429 env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
430 env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500431 env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
432
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400433 jint configID = GraphicsJNI::colorTypeToLegacyBitmapConfig(decodeColorType);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800434 if (isHardware) {
435 configID = GraphicsJNI::kHardware_LegacyBitmapConfig;
436 }
437 jobject config = env->CallStaticObjectMethod(gBitmapConfig_class,
438 gBitmapConfig_nativeToConfigMethodID, configID);
439 env->SetObjectField(options, gOptions_outConfigFieldID, config);
440
Romain Guy90fc43b2017-03-30 12:35:26 -0700441 env->SetObjectField(options, gOptions_outColorSpaceFieldID,
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500442 GraphicsJNI::getColorSpace(env, decodeColorSpace.get(), decodeColorType));
Romain Guy90fc43b2017-03-30 12:35:26 -0700443
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500444 if (onlyDecodeSize) {
445 return nullptr;
446 }
447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448
Anton Daubert4e5ec342016-03-07 17:30:20 +0100449 // Scale is necessary due to density differences.
450 if (scale != 1.0f) {
451 willScale = true;
452 scaledWidth = static_cast<int>(scaledWidth * scale + 0.5f);
453 scaledHeight = static_cast<int>(scaledHeight * scale + 0.5f);
454 }
455
sergeyvc1c54062016-10-19 18:47:26 -0700456 android::Bitmap* reuseBitmap = nullptr;
Chris Craik9f583612013-05-20 18:13:47 -0700457 unsigned int existingBufferSize = 0;
Leon Scroggins III71fae622019-03-26 16:28:41 -0400458 if (javaBitmap != nullptr) {
459 reuseBitmap = &bitmap::toBitmap(inBitmapHandle);
sergeyvc69853c2016-10-07 14:14:09 -0700460 if (reuseBitmap->isImmutable()) {
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400461 ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
Leon Scroggins IIIca8aef62019-03-26 12:11:27 -0400462 javaBitmap = nullptr;
John Reckf29ed282015-04-07 07:32:03 -0700463 reuseBitmap = nullptr;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700464 } else {
Leon Scroggins IIIca8aef62019-03-26 12:11:27 -0400465 existingBufferSize = reuseBitmap->getAllocationByteCount();
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400466 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468
sergeyv45082182016-09-29 18:25:40 -0700469 HeapAllocator defaultAllocator;
John Reckf29ed282015-04-07 07:32:03 -0700470 RecyclingPixelAllocator recyclingAllocator(reuseBitmap, existingBufferSize);
Chris Craik905e8242013-06-05 09:59:05 -0700471 ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500472 SkBitmap::HeapAllocator heapAllocator;
473 SkBitmap::Allocator* decodeAllocator;
474 if (javaBitmap != nullptr && willScale) {
475 // This will allocate pixels using a HeapAllocator, since there will be an extra
476 // scaling step that copies these pixels into Java memory. This allocator
477 // also checks that the recycled javaBitmap is large enough.
478 decodeAllocator = &scaleCheckingAllocator;
479 } else if (javaBitmap != nullptr) {
480 decodeAllocator = &recyclingAllocator;
sergeyvda6c8ffc2016-11-22 18:28:54 -0800481 } else if (willScale || isHardware) {
482 // This will allocate pixels using a HeapAllocator,
483 // for scale case: there will be an extra scaling step.
484 // for hardware case: there will be extra swizzling & upload to gralloc step.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500485 decodeAllocator = &heapAllocator;
486 } else {
sergeyv45082182016-09-29 18:25:40 -0700487 decodeAllocator = &defaultAllocator;
Chris Craik905e8242013-06-05 09:59:05 -0700488 }
489
Matt Sarett9e7cd632015-12-11 10:54:28 -0500490 SkAlphaType alphaType = codec->computeOutputAlphaType(requireUnpremultiplied);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500491
Romain Guy253f2c22016-09-28 17:34:42 -0700492 const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(),
Romain Guy90fc43b2017-03-30 12:35:26 -0700493 decodeColorType, alphaType, decodeColorSpace);
Matt Sarett6c382572017-02-21 17:42:41 -0500494
Matt Sarett327c7202017-02-22 17:38:20 -0500495 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500496 if (decodeColorType == kGray_8_SkColorType) {
497 // The legacy implementation of BitmapFactory used kAlpha8 for
498 // grayscale images (before kGray8 existed). While the codec
499 // recognizes kGray8, we need to decode into a kAlpha8 bitmap
500 // in order to avoid a behavior change.
Matt Sarettee80c4712016-06-03 10:23:38 -0400501 bitmapInfo =
502 bitmapInfo.makeColorType(kAlpha_8_SkColorType).makeAlphaType(kPremul_SkAlphaType);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500503 }
Chris Craik7e8c03c2013-06-03 13:53:36 -0700504 SkBitmap decodingBitmap;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500505 if (!decodingBitmap.setInfo(bitmapInfo) ||
Mike Reed81397c42017-07-18 17:04:16 -0400506 !decodingBitmap.tryAllocPixels(decodeAllocator)) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500507 // SkAndroidCodec should recommend a valid SkImageInfo, so setInfo()
508 // should only only fail if the calculated value for rowBytes is too
509 // large.
510 // tryAllocPixels() can fail due to OOM on the Java heap, OOM on the
511 // native heap, or the recycled javaBitmap being too small to reuse.
512 return nullptr;
Mike Reedc70e06b2009-04-24 11:09:12 -0400513 }
514
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500515 // Use SkAndroidCodec to perform the decode.
516 SkAndroidCodec::AndroidOptions codecOptions;
Romain Guy253f2c22016-09-28 17:34:42 -0700517 codecOptions.fZeroInitialized = decodeAllocator == &defaultAllocator ?
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500518 SkCodec::kYes_ZeroInitialized : SkCodec::kNo_ZeroInitialized;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500519 codecOptions.fSampleSize = sampleSize;
520 SkCodec::Result result = codec->getAndroidPixels(decodeInfo, decodingBitmap.getPixels(),
521 decodingBitmap.rowBytes(), &codecOptions);
522 switch (result) {
523 case SkCodec::kSuccess:
524 case SkCodec::kIncompleteInput:
525 break;
526 default:
Matt Sarett3b1b68d2015-12-14 13:08:33 -0500527 return nullObjectReturn("codec->getAndroidPixels() failed.");
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500528 }
529
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500530 // This is weird so let me explain: we could use the scale parameter
531 // directly, but for historical reasons this is how the corresponding
532 // Dalvik code has always behaved. We simply recreate the behavior here.
533 // The result is slightly different from simply using scale because of
534 // the 0.5f rounding bias applied when computing the target image size
535 const float scaleX = scaledWidth / float(decodingBitmap.width());
536 const float scaleY = scaledHeight / float(decodingBitmap.height());
537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 jbyteArray ninePatchChunk = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -0700539 if (peeker.mPatch != NULL) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700540 if (willScale) {
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500541 peeker.scale(scaleX, scaleY, scaledWidth, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700542 }
543
Chris Craik47cd8e92014-07-08 17:13:08 -0700544 size_t ninePatchArraySize = peeker.mPatch->serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700546 if (ninePatchChunk == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400547 return nullObjectReturn("ninePatchChunk == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700549
550 jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
551 if (array == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400552 return nullObjectReturn("primitive array == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700554
Chris Craik47cd8e92014-07-08 17:13:08 -0700555 memcpy(array, peeker.mPatch, peeker.mPatchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
557 }
558
Chris Craik47cd8e92014-07-08 17:13:08 -0700559 jobject ninePatchInsets = NULL;
560 if (peeker.mHasInsets) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400561 ninePatchInsets = peeker.createNinePatchInsets(env, scale);
Mathieu Chartiera08d10f2014-08-29 16:55:55 -0700562 if (ninePatchInsets == NULL) {
563 return nullObjectReturn("nine patch insets == null");
564 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700565 if (javaBitmap != NULL) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700566 env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700567 }
568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569
John Reckf29ed282015-04-07 07:32:03 -0700570 SkBitmap outputBitmap;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700571 if (willScale) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500572 // Set the allocator for the outputBitmap.
573 SkBitmap::Allocator* outputAllocator;
574 if (javaBitmap != nullptr) {
575 outputAllocator = &recyclingAllocator;
576 } else {
sergeyv45082182016-09-29 18:25:40 -0700577 outputAllocator = &defaultAllocator;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500578 }
579
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400580 SkColorType scaledColorType = decodingBitmap.colorType();
Leon Scroggins III8790be62013-12-03 16:26:51 -0500581 // FIXME: If the alphaType is kUnpremul and the image has alpha, the
582 // colors may not be correct, since Skia does not yet support drawing
583 // to/from unpremultiplied bitmaps.
Matt Sarettee80c4712016-06-03 10:23:38 -0400584 outputBitmap.setInfo(
585 bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
Mike Reed81397c42017-07-18 17:04:16 -0400586 if (!outputBitmap.tryAllocPixels(outputAllocator)) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500587 // This should only fail on OOM. The recyclingAllocator should have
588 // enough memory since we check this before decoding using the
589 // scaleCheckingAllocator.
Raph Levien005bfc62012-09-20 22:51:47 -0700590 return nullObjectReturn("allocation failed for scaled bitmap");
591 }
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400592
Romain Guy7b2f8b82012-03-19 17:18:54 -0700593 SkPaint paint;
Romain Guy253f2c22016-09-28 17:34:42 -0700594 // kSrc_Mode instructs us to overwrite the uninitialized pixels in
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500595 // outputBitmap. Otherwise we would blend by default, which is not
596 // what we want.
Mike Reed260ab722016-10-07 15:59:20 -0400597 paint.setBlendMode(SkBlendMode::kSrc);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700598
Matt Sarettca9b7032017-04-13 12:18:47 -0400599 SkCanvas canvas(outputBitmap, SkCanvas::ColorBehavior::kLegacy);
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500600 canvas.scale(scaleX, scaleY);
Mike Reed7994a312021-01-28 18:06:26 -0500601 decodingBitmap.setImmutable(); // so .asImage() doesn't make a copy
602 canvas.drawImage(decodingBitmap.asImage(), 0.0f, 0.0f,
603 SkSamplingOptions(SkFilterMode::kLinear), &paint);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700604 } else {
John Reckf29ed282015-04-07 07:32:03 -0700605 outputBitmap.swap(decodingBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700606 }
607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 if (padding) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400609 peeker.getPadding(env, padding);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500612 // If we get here, the outputBitmap should have an installed pixelref.
John Reckf29ed282015-04-07 07:32:03 -0700613 if (outputBitmap.pixelRef() == NULL) {
Marco Nelissenb2fe3be2012-05-07 11:24:13 -0700614 return nullObjectReturn("Got null SkPixelRef");
615 }
Romain Guy23610982011-01-17 12:51:55 -0800616
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000617 bool hasGainmap = false;
618 SkGainmapInfo gainmapInfo;
619 std::unique_ptr<SkStream> gainmapStream = nullptr;
620 sp<uirenderer::Gainmap> gainmap = nullptr;
621 if (result == SkCodec::kSuccess) {
622 hasGainmap = codec->getAndroidGainmap(&gainmapInfo, &gainmapStream);
623 }
624
625 if (hasGainmap) {
626 hasGainmap =
627 decodeGainmap(std::move(gainmapStream), gainmapInfo, &gainmap, sampleSize, scale);
628 }
629
Chris Craik7e8c03c2013-06-03 13:53:36 -0700630 if (!isMutable && javaBitmap == NULL) {
Romain Guy23610982011-01-17 12:51:55 -0800631 // promise we will never change our pixels (great for sharing and pictures)
John Reckf29ed282015-04-07 07:32:03 -0700632 outputBitmap.setImmutable();
Romain Guy23610982011-01-17 12:51:55 -0800633 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800634
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500635 bool isPremultiplied = !requireUnpremultiplied;
636 if (javaBitmap != nullptr) {
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000637 if (hasGainmap) {
638 reuseBitmap->setGainmap(std::move(gainmap));
639 }
sergeyvc69853c2016-10-07 14:14:09 -0700640 bitmap::reinitBitmap(env, javaBitmap, outputBitmap.info(), isPremultiplied);
John Reckf29ed282015-04-07 07:32:03 -0700641 outputBitmap.notifyPixelsChanged();
Chet Haase37f74ca2010-12-08 17:56:36 -0800642 // If a java bitmap was passed in for reuse, pass it back
643 return javaBitmap;
644 }
Chris Craik1abf5d62013-08-16 12:47:03 -0700645
646 int bitmapCreateFlags = 0x0;
sergeyvc69853c2016-10-07 14:14:09 -0700647 if (isMutable) bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Mutable;
648 if (isPremultiplied) bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Premultiplied;
Chris Craik1abf5d62013-08-16 12:47:03 -0700649
sergeyvda6c8ffc2016-11-22 18:28:54 -0800650 if (isHardware) {
651 sk_sp<Bitmap> hardwareBitmap = Bitmap::allocateHardwareBitmap(outputBitmap);
sergeyvd67bb1e2017-06-28 12:44:03 -0700652 if (!hardwareBitmap.get()) {
653 return nullObjectReturn("Failed to allocate a hardware bitmap");
654 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000655 if (hasGainmap) {
Sally Qi587fb572023-03-03 15:50:06 -0800656 auto gm = uirenderer::Gainmap::allocateHardwareGainmap(gainmap);
657 if (gm) {
658 hardwareBitmap->setGainmap(std::move(gm));
659 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000660 }
661
sergeyvda6c8ffc2016-11-22 18:28:54 -0800662 return bitmap::createBitmap(env, hardwareBitmap.release(), bitmapCreateFlags,
663 ninePatchChunk, ninePatchInsets, -1);
664 }
665
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000666 Bitmap* heapBitmap = defaultAllocator.getStorageObjAndReset();
667 if (hasGainmap && heapBitmap != nullptr) {
668 heapBitmap->setGainmap(std::move(gainmap));
669 }
670
Mike Reedc70e06b2009-04-24 11:09:12 -0400671 // now create the java bitmap
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000672 return bitmap::createBitmap(env, heapBitmap, bitmapCreateFlags, ninePatchChunk, ninePatchInsets,
673 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674}
675
Chris Craik905e8242013-06-05 09:59:05 -0700676static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400677 jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 jobject bitmap = NULL;
Ben Wagner60126ef2015-08-07 12:13:48 -0400680 std::unique_ptr<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681
Leon Scroggins IIIca320212013-08-20 17:59:39 -0400682 if (stream.get()) {
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400683 std::unique_ptr<SkStreamRewindable> bufferedStream(skia::FrontBufferedStream::Make(
684 std::move(stream), SkCodec::MinBufferedBytesNeeded()));
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400685 SkASSERT(bufferedStream.get() != NULL);
Leon Scroggins III71fae622019-03-26 16:28:41 -0400686 bitmap = doDecode(env, std::move(bufferedStream), padding, options, inBitmapHandle,
687 colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
689 return bitmap;
690}
691
Romain Guy7b2f8b82012-03-19 17:18:54 -0700692static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400693 jobject padding, jobject bitmapFactoryOptions, jlong inBitmapHandle, jlong colorSpaceHandle) {
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400694#ifndef __ANDROID__ // LayoutLib for Windows does not support F_DUPFD_CLOEXEC
695 return nullObjectReturn("Not supported on Windows");
696#else
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
698
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400699 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Mike Reedc70e06b2009-04-24 11:09:12 -0400700
Derek Sollenberger5827cb52013-07-26 14:58:06 -0400701 struct stat fdStat;
702 if (fstat(descriptor, &fdStat) == -1) {
703 doThrowIOE(env, "broken file descriptor");
704 return nullObjectReturn("fstat return -1");
705 }
706
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400707 // Restore the descriptor's offset on exiting this function. Even though
708 // we dup the descriptor, both the original and dup refer to the same open
709 // file description and changes to the file offset in one impact the other.
Jérôme Poichetd29c9022014-09-26 18:59:11 +0000710 AutoFDSeek autoRestore(descriptor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400712 // Duplicate the descriptor here to prevent leaking memory. A leak occurs
713 // if we only close the file descriptor and not the file object it is used to
714 // create. If we don't explicitly clean up the file (which in turn closes the
715 // descriptor) the buffers allocated internally by fseek will be leaked.
Nick Kralevich4b3a08c2019-01-28 10:39:10 -0800716 int dupDescriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, 0);
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400717
718 FILE* file = fdopen(dupDescriptor, "r");
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500719 if (file == NULL) {
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400720 // cleanup the duplicated descriptor since it will not be closed when the
721 // file is cleaned up (fclose).
722 close(dupDescriptor);
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500723 return nullObjectReturn("Could not open file");
Leon Scroggins IIIf65183f2013-10-07 16:32:14 -0400724 }
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500725
Leon Scroggins IIIdd3c06c2017-03-10 10:50:33 -0500726 std::unique_ptr<SkFILEStream> fileStream(new SkFILEStream(file));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100728 // If there is no offset for the file descriptor, we use SkFILEStream directly.
729 if (::lseek(descriptor, 0, SEEK_CUR) == 0) {
730 assert(isSeekable(dupDescriptor));
Leon Scroggins III0e443d12018-12-19 11:38:35 -0500731 return doDecode(env, std::move(fileStream), padding, bitmapFactoryOptions,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400732 inBitmapHandle, colorSpaceHandle);
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100733 }
734
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400735 // Use a buffered stream. Although an SkFILEStream can be rewound, this
736 // ensures that SkImageDecoder::Factory never rewinds beyond the
737 // current position of the file descriptor.
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400738 std::unique_ptr<SkStreamRewindable> stream(skia::FrontBufferedStream::Make(
739 std::move(fileStream), SkCodec::MinBufferedBytesNeeded()));
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500740
Leon Scroggins III71fae622019-03-26 16:28:41 -0400741 return doDecode(env, std::move(stream), padding, bitmapFactoryOptions, inBitmapHandle,
742 colorSpaceHandle);
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400743#endif
Mike Reedc70e06b2009-04-24 11:09:12 -0400744}
745
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000746static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400747 jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700748
Mike Reedc70e06b2009-04-24 11:09:12 -0400749 Asset* asset = reinterpret_cast<Asset*>(native_asset);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400750 // since we know we'll be done with the asset when we return, we can
751 // just use a simple wrapper
Mike Reed3cf42822019-12-12 11:59:49 -0500752 return doDecode(env, std::make_unique<AssetStreamAdaptor>(asset), padding, options,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400753 inBitmapHandle, colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754}
755
756static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400757 jint offset, jint length, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700758
Mike Reedc70e06b2009-04-24 11:09:12 -0400759 AutoJavaByteArray ar(env, byteArray);
Mike Reed3cf42822019-12-12 11:59:49 -0500760 return doDecode(env, std::make_unique<SkMemoryStream>(ar.ptr() + offset, length, false),
Leon Scroggins III71fae622019-03-26 16:28:41 -0400761 nullptr, options, inBitmapHandle, colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762}
763
Owen Lina9d0d472011-01-18 17:39:15 +0800764static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700765 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100766 return isSeekable(descriptor) ? JNI_TRUE : JNI_FALSE;
Owen Lina9d0d472011-01-18 17:39:15 +0800767}
768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769///////////////////////////////////////////////////////////////////////////////
770
Daniel Micay76f6a862015-09-19 17:31:01 -0400771static const JNINativeMethod gMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 { "nativeDecodeStream",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400773 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 (void*)nativeDecodeStream
775 },
776
777 { "nativeDecodeFileDescriptor",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400778 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 (void*)nativeDecodeFileDescriptor
780 },
781
782 { "nativeDecodeAsset",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400783 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 (void*)nativeDecodeAsset
785 },
786
787 { "nativeDecodeByteArray",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400788 "([BIILandroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 (void*)nativeDecodeByteArray
790 },
791
Owen Lina9d0d472011-01-18 17:39:15 +0800792 { "nativeIsSeekable",
793 "(Ljava/io/FileDescriptor;)Z",
794 (void*)nativeIsSeekable
795 },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796};
797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798int register_android_graphics_BitmapFactory(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800799 jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
800 gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
Chris Craik47cd8e92014-07-08 17:13:08 -0700801 "Landroid/graphics/Bitmap;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800802 gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
803 gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
804 gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 "Landroid/graphics/Bitmap$Config;");
Romain Guy95648b82017-04-13 18:43:42 -0700806 gOptions_colorSpaceFieldID = GetFieldIDOrDie(env, options_class, "inPreferredColorSpace",
807 "Landroid/graphics/ColorSpace;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800808 gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
809 gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
810 gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
811 gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800812 "inPreferQualityOverSpeed", "Z");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800813 gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
814 gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
815 gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
816 gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
817 gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
818 gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
819 gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
Romain Guye8d2ebb2017-02-09 18:38:47 -0800820 gOptions_outConfigFieldID = GetFieldIDOrDie(env, options_class, "outConfig",
821 "Landroid/graphics/Bitmap$Config;");
Romain Guy90fc43b2017-03-30 12:35:26 -0700822 gOptions_outColorSpaceFieldID = GetFieldIDOrDie(env, options_class, "outColorSpace",
823 "Landroid/graphics/ColorSpace;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800824 gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800826 jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800827 gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
Chris Craik47cd8e92014-07-08 17:13:08 -0700828 "Landroid/graphics/NinePatch$InsetStruct;");
829
Romain Guye8d2ebb2017-02-09 18:38:47 -0800830 gBitmapConfig_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
831 "android/graphics/Bitmap$Config"));
832 gBitmapConfig_nativeToConfigMethodID = GetStaticMethodIDOrDie(env, gBitmapConfig_class,
833 "nativeToConfig", "(I)Landroid/graphics/Bitmap$Config;");
834
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800835 return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
836 gMethods, NELEM(gMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837}