blob: 8b43f1db84af0c36ed20b346e5637d9612128686 [file] [log] [blame]
Joseph Wenf1f48bc2010-07-19 16:59:51 +08001#include "BitmapFactory.h"
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +00002
3#include <Gainmap.h>
4#include <HardwareBitmapUploader.h>
5#include <androidfw/Asset.h>
6#include <androidfw/ResourceTypes.h>
7#include <cutils/compiler.h>
8#include <fcntl.h>
9#include <nativehelper/JNIPlatformHelp.h>
10#include <stdint.h>
11#include <stdio.h>
12#include <sys/stat.h>
Alec Mouri0ba21a72024-10-10 22:45:08 +000013#include <utils/StatsUtils.h>
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +000014
15#include <memory>
16
Ben Wagner60126ef2015-08-07 12:13:48 -040017#include "CreateJavaOutputStreamAdaptor.h"
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -040018#include "FrontBufferedStream.h"
Ben Wagner60126ef2015-08-07 12:13:48 -040019#include "GraphicsJNI.h"
Derek Sollenberger2173ea22020-02-19 15:37:29 -050020#include "MimeType.h"
Leon Scrogginsa06d86a2011-03-02 16:56:54 -050021#include "NinePatchPeeker.h"
Matt Sarettb8adc9a2015-12-02 13:35:22 -050022#include "SkAndroidCodec.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050023#include "SkBitmap.h"
24#include "SkBlendMode.h"
John Reckbe671952021-01-13 22:39:32 -050025#include "SkCanvas.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050026#include "SkColorSpace.h"
27#include "SkEncodedImageFormat.h"
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +000028#include "SkGainmapInfo.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050029#include "SkImageInfo.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050030#include "SkPaint.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031#include "SkPixelRef.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050032#include "SkRect.h"
33#include "SkRefCnt.h"
34#include "SkSamplingOptions.h"
35#include "SkSize.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036#include "SkStream.h"
John Reckbe671952021-01-13 22:39:32 -050037#include "SkString.h"
Wei-Ta Chen6b849e22010-09-07 17:32:18 +080038#include "Utils.h"
Ben Wagner60126ef2015-08-07 12:13:48 -040039
Joseph Wenf1f48bc2010-07-19 16:59:51 +080040jfieldID gOptions_justBoundsFieldID;
41jfieldID gOptions_sampleSizeFieldID;
42jfieldID gOptions_configFieldID;
Romain Guy95648b82017-04-13 18:43:42 -070043jfieldID gOptions_colorSpaceFieldID;
Chris Craik1abf5d62013-08-16 12:47:03 -070044jfieldID gOptions_premultipliedFieldID;
Romain Guy23610982011-01-17 12:51:55 -080045jfieldID gOptions_mutableFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080046jfieldID gOptions_ditherFieldID;
Wei-Ta Chen953f9092010-12-03 14:06:18 -080047jfieldID gOptions_preferQualityOverSpeedFieldID;
Chris Craik905e8242013-06-05 09:59:05 -070048jfieldID gOptions_scaledFieldID;
49jfieldID gOptions_densityFieldID;
50jfieldID gOptions_screenDensityFieldID;
51jfieldID gOptions_targetDensityFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080052jfieldID gOptions_widthFieldID;
53jfieldID gOptions_heightFieldID;
54jfieldID gOptions_mimeFieldID;
Romain Guye8d2ebb2017-02-09 18:38:47 -080055jfieldID gOptions_outConfigFieldID;
Romain Guy90fc43b2017-03-30 12:35:26 -070056jfieldID gOptions_outColorSpaceFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080057jfieldID gOptions_mCancelID;
Chet Haase37f74ca2010-12-08 17:56:36 -080058jfieldID gOptions_bitmapFieldID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
Chris Craik47cd8e92014-07-08 17:13:08 -070060jfieldID gBitmap_ninePatchInsetsFieldID;
61
Romain Guye8d2ebb2017-02-09 18:38:47 -080062jclass gBitmapConfig_class;
63jmethodID gBitmapConfig_nativeToConfigMethodID;
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065using namespace android;
66
Leon Scroggins III407b5442019-11-22 17:10:20 -050067const char* getMimeType(SkEncodedImageFormat format) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -050068 switch (format) {
Hal Canary10219fb2016-11-23 20:41:22 -050069 case SkEncodedImageFormat::kBMP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050070 return "image/bmp";
Hal Canary10219fb2016-11-23 20:41:22 -050071 case SkEncodedImageFormat::kGIF:
Leon Scroggins III407b5442019-11-22 17:10:20 -050072 return "image/gif";
Hal Canary10219fb2016-11-23 20:41:22 -050073 case SkEncodedImageFormat::kICO:
Leon Scroggins III407b5442019-11-22 17:10:20 -050074 return "image/x-ico";
Hal Canary10219fb2016-11-23 20:41:22 -050075 case SkEncodedImageFormat::kJPEG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050076 return "image/jpeg";
Hal Canary10219fb2016-11-23 20:41:22 -050077 case SkEncodedImageFormat::kPNG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050078 return "image/png";
Hal Canary10219fb2016-11-23 20:41:22 -050079 case SkEncodedImageFormat::kWEBP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050080 return "image/webp";
Chong Zhang48fa8902017-08-16 11:57:02 -070081 case SkEncodedImageFormat::kHEIF:
Leon Scroggins III407b5442019-11-22 17:10:20 -050082 return "image/heif";
Vignesh Venkatasubramanian4a46b9e2020-11-05 22:55:43 -080083 case SkEncodedImageFormat::kAVIF:
84 return "image/avif";
Hal Canary10219fb2016-11-23 20:41:22 -050085 case SkEncodedImageFormat::kWBMP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050086 return "image/vnd.wap.wbmp";
Hal Canary10219fb2016-11-23 20:41:22 -050087 case SkEncodedImageFormat::kDNG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050088 return "image/x-adobe-dng";
Matt Sarettb8adc9a2015-12-02 13:35:22 -050089 default:
Leon Scroggins III407b5442019-11-22 17:10:20 -050090 return nullptr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 }
Leon Scroggins III407b5442019-11-22 17:10:20 -050092}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Leon Scroggins III407b5442019-11-22 17:10:20 -050094jstring getMimeTypeAsJavaString(JNIEnv* env, SkEncodedImageFormat format) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +000095 jstring jstr = nullptr;
Leon Scroggins III407b5442019-11-22 17:10:20 -050096 const char* mimeType = getMimeType(format);
Matt Sarettb8adc9a2015-12-02 13:35:22 -050097 if (mimeType) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +000098 // NOTE: Caller should env->ExceptionCheck() for OOM
99 // (can't check for nullptr as it's a valid return value)
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500100 jstr = env->NewStringUTF(mimeType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 }
102 return jstr;
103}
104
Chris Craik905e8242013-06-05 09:59:05 -0700105class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
106public:
107 ScaleCheckingAllocator(float scale, int size)
108 : mScale(scale), mSize(size) {
109 }
110
Mike Reed81397c42017-07-18 17:04:16 -0400111 virtual bool allocPixelRef(SkBitmap* bitmap) {
Chris Craik905e8242013-06-05 09:59:05 -0700112 // accounts for scale in final allocation, using eventual size and config
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400113 const int bytesPerPixel = SkColorTypeBytesPerPixel(bitmap->colorType());
Chris Craik905e8242013-06-05 09:59:05 -0700114 const int requestedSize = bytesPerPixel *
115 int(bitmap->width() * mScale + 0.5f) *
116 int(bitmap->height() * mScale + 0.5f);
117 if (requestedSize > mSize) {
118 ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
119 mSize, requestedSize);
120 return false;
121 }
Mike Reed81397c42017-07-18 17:04:16 -0400122 return SkBitmap::HeapAllocator::allocPixelRef(bitmap);
Chris Craik905e8242013-06-05 09:59:05 -0700123 }
124private:
125 const float mScale;
126 const int mSize;
127};
128
Chris Craik7e8c03c2013-06-03 13:53:36 -0700129class RecyclingPixelAllocator : public SkBitmap::Allocator {
130public:
sergeyvc1c54062016-10-19 18:47:26 -0700131 RecyclingPixelAllocator(android::Bitmap* bitmap, unsigned int size)
John Reckf29ed282015-04-07 07:32:03 -0700132 : mBitmap(bitmap), mSize(size) {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700133 }
134
135 ~RecyclingPixelAllocator() {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700136 }
137
Mike Reed81397c42017-07-18 17:04:16 -0400138 virtual bool allocPixelRef(SkBitmap* bitmap) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500139 const SkImageInfo& info = bitmap->info();
Leon Scroggins IIIf35b9892015-07-31 10:38:40 -0400140 if (info.colorType() == kUnknown_SkColorType) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500141 ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700142 return false;
143 }
Chris Craikcd0ba712013-09-06 14:40:30 -0700144
Mike Reed7569de02017-10-06 16:25:49 -0400145 const size_t size = info.computeByteSize(bitmap->rowBytes());
Kevin Lubickbab0bb32023-01-17 15:30:34 +0000146 if (size > INT32_MAX) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500147 ALOGW("bitmap is too large");
148 return false;
149 }
150
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500151 if (size > mSize) {
Dan Albert46d84442014-11-18 16:07:51 -0800152 ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap "
153 "(%zu bytes)", mSize, size);
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500154 return false;
155 }
156
Leon Scroggins IIIf51a80d2017-07-12 10:46:35 -0400157 mBitmap->reconfigure(info, bitmap->rowBytes());
Mike Reed826deef2017-04-04 15:32:04 -0400158 bitmap->setPixelRef(sk_ref_sp(mBitmap), 0, 0);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700159 return true;
160 }
161
162private:
sergeyvc1c54062016-10-19 18:47:26 -0700163 android::Bitmap* const mBitmap;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700164 const unsigned int mSize;
165};
166
Anton Daubert4e5ec342016-03-07 17:30:20 +0100167// Necessary for decodes when the native decoder cannot scale to appropriately match the sampleSize
168// (for example, RAW). If the sampleSize divides evenly into the dimension, we require that the
169// scale matches exactly. If sampleSize does not divide evenly, we allow the decoder to choose how
170// best to round.
171static bool needsFineScale(const int fullSize, const int decodedSize, const int sampleSize) {
172 if (fullSize % sampleSize == 0 && fullSize / sampleSize != decodedSize) {
173 return true;
174 } else if ((fullSize / sampleSize + 1) != decodedSize &&
175 (fullSize / sampleSize) != decodedSize) {
176 return true;
177 }
178 return false;
179}
180
181static bool needsFineScale(const SkISize fullSize, const SkISize decodedSize,
182 const int sampleSize) {
183 return needsFineScale(fullSize.width(), decodedSize.width(), sampleSize) ||
184 needsFineScale(fullSize.height(), decodedSize.height(), sampleSize);
185}
186
Christopher Cameroncf3d3fc2024-09-11 14:18:44 +0000187static bool decodeGainmap(std::unique_ptr<SkAndroidCodec> codec, const SkGainmapInfo& gainmapInfo,
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000188 sp<uirenderer::Gainmap>* outGainmap, const int sampleSize, float scale) {
John Reck818328c2023-05-09 17:50:33 -0400189 SkColorType decodeColorType = kN32_SkColorType;
190 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
191 decodeColorType = kGray_8_SkColorType;
192 }
193 decodeColorType = codec->computeOutputColorType(decodeColorType);
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000194 sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(decodeColorType, nullptr);
195
196 SkISize size = codec->getSampledDimensions(sampleSize);
197
198 int scaledWidth = size.width();
199 int scaledHeight = size.height();
200 bool willScale = false;
201
202 // Apply a fine scaling step if necessary.
203 if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize) || scale != 1.0f) {
204 willScale = true;
205 // The operation below may loose precision (integer division), but it is put this way to
206 // mimic main image scale calculation
207 scaledWidth = static_cast<int>((codec->getInfo().width() / sampleSize) * scale + 0.5f);
208 scaledHeight = static_cast<int>((codec->getInfo().height() / sampleSize) * scale + 0.5f);
209 }
210
211 SkAlphaType alphaType = codec->computeOutputAlphaType(false);
212
213 const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(), decodeColorType,
214 alphaType, decodeColorSpace);
215
John Reck818328c2023-05-09 17:50:33 -0400216 SkImageInfo bitmapInfo = decodeInfo;
217 if (decodeColorType == kGray_8_SkColorType) {
218 // We treat gray8 as alpha8 in Bitmap's API surface
219 bitmapInfo = bitmapInfo.makeColorType(kAlpha_8_SkColorType);
220 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000221 SkBitmap decodeBitmap;
222 sk_sp<Bitmap> nativeBitmap = nullptr;
223
224 if (!decodeBitmap.setInfo(bitmapInfo)) {
225 ALOGE("Failed to setInfo.");
226 return false;
227 }
228
229 if (willScale) {
230 if (!decodeBitmap.tryAllocPixels(nullptr)) {
231 ALOGE("OOM allocating gainmap pixels.");
232 return false;
233 }
234 } else {
235 nativeBitmap = android::Bitmap::allocateHeapBitmap(&decodeBitmap);
236 if (!nativeBitmap) {
237 ALOGE("OOM allocating gainmap pixels.");
238 return false;
239 }
240 }
241
242 // Use SkAndroidCodec to perform the decode.
243 SkAndroidCodec::AndroidOptions codecOptions;
244 codecOptions.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
245 codecOptions.fSampleSize = sampleSize;
246 SkCodec::Result result = codec->getAndroidPixels(decodeInfo, decodeBitmap.getPixels(),
247 decodeBitmap.rowBytes(), &codecOptions);
248 switch (result) {
249 case SkCodec::kSuccess:
250 case SkCodec::kIncompleteInput:
251 break;
252 default:
253 ALOGE("Error decoding gainmap.");
254 return false;
255 }
256
257 if (willScale) {
258 SkBitmap gainmapBitmap;
259 const float scaleX = scaledWidth / float(decodeBitmap.width());
260 const float scaleY = scaledHeight / float(decodeBitmap.height());
261
262 SkColorType scaledColorType = decodeBitmap.colorType();
263 gainmapBitmap.setInfo(
264 bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
265
266 nativeBitmap = android::Bitmap::allocateHeapBitmap(&gainmapBitmap);
267 if (!nativeBitmap) {
268 ALOGE("OOM allocating gainmap pixels.");
269 return false;
270 }
271
272 SkPaint paint;
273 // kSrc_Mode instructs us to overwrite the uninitialized pixels in
274 // outputBitmap. Otherwise we would blend by default, which is not
275 // what we want.
276 paint.setBlendMode(SkBlendMode::kSrc);
277
278 SkCanvas canvas(gainmapBitmap, SkCanvas::ColorBehavior::kLegacy);
279 canvas.scale(scaleX, scaleY);
280 decodeBitmap.setImmutable(); // so .asImage() doesn't make a copy
281 canvas.drawImage(decodeBitmap.asImage(), 0.0f, 0.0f,
282 SkSamplingOptions(SkFilterMode::kLinear), &paint);
283 }
284
285 auto gainmap = sp<uirenderer::Gainmap>::make();
286 if (!gainmap) {
287 ALOGE("OOM allocating Gainmap");
288 return false;
289 }
290
291 gainmap->info = gainmapInfo;
292 gainmap->bitmap = std::move(nativeBitmap);
293 *outGainmap = std::move(gainmap);
294
295 return true;
296}
297
Mike Reedc7c65602017-07-26 10:40:25 -0400298static jobject doDecode(JNIEnv* env, std::unique_ptr<SkStreamRewindable> stream,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400299 jobject padding, jobject options, jlong inBitmapHandle,
300 jlong colorSpaceHandle) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500301 // Set default values for the options parameters.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 int sampleSize = 1;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500303 bool onlyDecodeSize = false;
Mike Reed42a1d082014-07-07 18:06:18 -0400304 SkColorType prefColorType = kN32_SkColorType;
sergeyvda6c8ffc2016-11-22 18:28:54 -0800305 bool isHardware = false;
Romain Guy23610982011-01-17 12:51:55 -0800306 bool isMutable = false;
Chris Craik905e8242013-06-05 09:59:05 -0700307 float scale = 1.0f;
Chris Craik1abf5d62013-08-16 12:47:03 -0700308 bool requireUnpremultiplied = false;
Chet Haase37f74ca2010-12-08 17:56:36 -0800309 jobject javaBitmap = NULL;
Leon Scroggins III0e443d12018-12-19 11:38:35 -0500310 sk_sp<SkColorSpace> prefColorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700311
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500312 // Update with options supplied by the client.
Romain Guy7b2f8b82012-03-19 17:18:54 -0700313 if (options != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500315 // Correct a non-positive sampleSize. sampleSize defaults to zero within the
316 // options object, which is strange.
317 if (sampleSize <= 0) {
318 sampleSize = 1;
319 }
320
321 if (env->GetBooleanField(options, gOptions_justBoundsFieldID)) {
322 onlyDecodeSize = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 // initialize these, in case we fail later on
326 env->SetIntField(options, gOptions_widthFieldID, -1);
327 env->SetIntField(options, gOptions_heightFieldID, -1);
328 env->SetObjectField(options, gOptions_mimeFieldID, 0);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800329 env->SetObjectField(options, gOptions_outConfigFieldID, 0);
Romain Guy90fc43b2017-03-30 12:35:26 -0700330 env->SetObjectField(options, gOptions_outColorSpaceFieldID, 0);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
Mike Reed42a1d082014-07-07 18:06:18 -0400333 prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
sergeyvda6c8ffc2016-11-22 18:28:54 -0800334 isHardware = GraphicsJNI::isHardwareConfig(env, jconfig);
Romain Guy23610982011-01-17 12:51:55 -0800335 isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
Chris Craik1abf5d62013-08-16 12:47:03 -0700336 requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
Chet Haase37f74ca2010-12-08 17:56:36 -0800337 javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
Chris Craik905e8242013-06-05 09:59:05 -0700338
339 if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
340 const int density = env->GetIntField(options, gOptions_densityFieldID);
341 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
342 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
343 if (density != 0 && targetDensity != 0 && density != screenDensity) {
344 scale = (float) targetDensity / density;
345 }
346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700348
sergeyv9fbb0b52016-11-23 10:27:33 -0800349 if (isMutable && isHardware) {
Hans Boehme5b337d2019-01-07 17:42:05 -0800350 doThrowIAE(env, "Bitmaps with Config.HARDWARE are always immutable");
sergeyv9fbb0b52016-11-23 10:27:33 -0800351 return nullObjectReturn("Cannot create mutable hardware bitmap");
352 }
353
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500354 // Create the codec.
355 NinePatchPeeker peeker;
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500356 std::unique_ptr<SkAndroidCodec> codec;
357 {
358 SkCodec::Result result;
359 std::unique_ptr<SkCodec> c = SkCodec::MakeFromStream(std::move(stream), &result,
360 &peeker);
361 if (!c) {
362 SkString msg;
363 msg.printf("Failed to create image decoder with message '%s'",
364 SkCodec::ResultToString(result));
365 return nullObjectReturn(msg.c_str());
366 }
367
368 codec = SkAndroidCodec::MakeFromCodec(std::move(c));
369 if (!codec) {
370 return nullObjectReturn("SkAndroidCodec::MakeFromCodec returned null");
371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700373
Matt Sarett3b1b68d2015-12-14 13:08:33 -0500374 // Do not allow ninepatch decodes to 565. In the past, decodes to 565
375 // would dither, and we do not want to pre-dither ninepatches, since we
376 // know that they will be stretched. We no longer dither 565 decodes,
377 // but we continue to prevent ninepatches from decoding to 565, in order
378 // to maintain the old behavior.
379 if (peeker.mPatch && kRGB_565_SkColorType == prefColorType) {
380 prefColorType = kN32_SkColorType;
381 }
382
Anton Daubert4e5ec342016-03-07 17:30:20 +0100383 // Determine the output size.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500384 SkISize size = codec->getSampledDimensions(sampleSize);
Anton Daubert4e5ec342016-03-07 17:30:20 +0100385
386 int scaledWidth = size.width();
387 int scaledHeight = size.height();
388 bool willScale = false;
389
390 // Apply a fine scaling step if necessary.
391 if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize)) {
392 willScale = true;
393 scaledWidth = codec->getInfo().width() / sampleSize;
394 scaledHeight = codec->getInfo().height() / sampleSize;
395 }
396
Romain Guye8d2ebb2017-02-09 18:38:47 -0800397 // Set the decode colorType
398 SkColorType decodeColorType = codec->computeOutputColorType(prefColorType);
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500399 if (decodeColorType == kRGBA_F16_SkColorType && isHardware &&
400 !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
401 decodeColorType = kN32_SkColorType;
402 }
403
Xiao Huangfff1a292023-04-12 17:37:36 +0000404 // b/276879147, fallback to RGBA_8888 when decoding HEIF and P010 is not supported.
405 if (decodeColorType == kRGBA_1010102_SkColorType &&
406 codec->getEncodedFormat() == SkEncodedImageFormat::kHEIF &&
407 env->CallStaticBooleanMethod(gImageDecoder_class,
408 gImageDecoder_isP010SupportedForHEVCMethodID) == JNI_FALSE) {
409 decodeColorType = kN32_SkColorType;
410 }
411
Romain Guy95648b82017-04-13 18:43:42 -0700412 sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(
413 decodeColorType, prefColorSpace);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800414
Anton Daubert4e5ec342016-03-07 17:30:20 +0100415 // Set the options and return if the client only wants the size.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500416 if (options != NULL) {
Leon Scroggins III407b5442019-11-22 17:10:20 -0500417 jstring mimeType = getMimeTypeAsJavaString(env, codec->getEncodedFormat());
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500418 if (env->ExceptionCheck()) {
Leon Scroggins III407b5442019-11-22 17:10:20 -0500419 return nullObjectReturn("OOM in getMimeTypeAsJavaString()");
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500420 }
Anton Daubert4e5ec342016-03-07 17:30:20 +0100421 env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
422 env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500423 env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
424
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400425 jint configID = GraphicsJNI::colorTypeToLegacyBitmapConfig(decodeColorType);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800426 if (isHardware) {
427 configID = GraphicsJNI::kHardware_LegacyBitmapConfig;
428 }
429 jobject config = env->CallStaticObjectMethod(gBitmapConfig_class,
430 gBitmapConfig_nativeToConfigMethodID, configID);
431 env->SetObjectField(options, gOptions_outConfigFieldID, config);
432
Romain Guy90fc43b2017-03-30 12:35:26 -0700433 env->SetObjectField(options, gOptions_outColorSpaceFieldID,
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500434 GraphicsJNI::getColorSpace(env, decodeColorSpace.get(), decodeColorType));
Romain Guy90fc43b2017-03-30 12:35:26 -0700435
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500436 if (onlyDecodeSize) {
437 return nullptr;
438 }
439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440
Anton Daubert4e5ec342016-03-07 17:30:20 +0100441 // Scale is necessary due to density differences.
442 if (scale != 1.0f) {
443 willScale = true;
444 scaledWidth = static_cast<int>(scaledWidth * scale + 0.5f);
445 scaledHeight = static_cast<int>(scaledHeight * scale + 0.5f);
446 }
447
sergeyvc1c54062016-10-19 18:47:26 -0700448 android::Bitmap* reuseBitmap = nullptr;
Chris Craik9f583612013-05-20 18:13:47 -0700449 unsigned int existingBufferSize = 0;
Leon Scroggins III71fae622019-03-26 16:28:41 -0400450 if (javaBitmap != nullptr) {
451 reuseBitmap = &bitmap::toBitmap(inBitmapHandle);
sergeyvc69853c2016-10-07 14:14:09 -0700452 if (reuseBitmap->isImmutable()) {
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400453 ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
Leon Scroggins IIIca8aef62019-03-26 12:11:27 -0400454 javaBitmap = nullptr;
John Reckf29ed282015-04-07 07:32:03 -0700455 reuseBitmap = nullptr;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700456 } else {
Leon Scroggins IIIca8aef62019-03-26 12:11:27 -0400457 existingBufferSize = reuseBitmap->getAllocationByteCount();
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400458 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460
sergeyv45082182016-09-29 18:25:40 -0700461 HeapAllocator defaultAllocator;
John Reckf29ed282015-04-07 07:32:03 -0700462 RecyclingPixelAllocator recyclingAllocator(reuseBitmap, existingBufferSize);
Chris Craik905e8242013-06-05 09:59:05 -0700463 ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500464 SkBitmap::HeapAllocator heapAllocator;
465 SkBitmap::Allocator* decodeAllocator;
466 if (javaBitmap != nullptr && willScale) {
467 // This will allocate pixels using a HeapAllocator, since there will be an extra
468 // scaling step that copies these pixels into Java memory. This allocator
469 // also checks that the recycled javaBitmap is large enough.
470 decodeAllocator = &scaleCheckingAllocator;
471 } else if (javaBitmap != nullptr) {
472 decodeAllocator = &recyclingAllocator;
sergeyvda6c8ffc2016-11-22 18:28:54 -0800473 } else if (willScale || isHardware) {
474 // This will allocate pixels using a HeapAllocator,
475 // for scale case: there will be an extra scaling step.
476 // for hardware case: there will be extra swizzling & upload to gralloc step.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500477 decodeAllocator = &heapAllocator;
478 } else {
sergeyv45082182016-09-29 18:25:40 -0700479 decodeAllocator = &defaultAllocator;
Chris Craik905e8242013-06-05 09:59:05 -0700480 }
481
Matt Sarett9e7cd632015-12-11 10:54:28 -0500482 SkAlphaType alphaType = codec->computeOutputAlphaType(requireUnpremultiplied);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500483
Romain Guy253f2c22016-09-28 17:34:42 -0700484 const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(),
Romain Guy90fc43b2017-03-30 12:35:26 -0700485 decodeColorType, alphaType, decodeColorSpace);
Matt Sarett6c382572017-02-21 17:42:41 -0500486
Matt Sarett327c7202017-02-22 17:38:20 -0500487 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500488 if (decodeColorType == kGray_8_SkColorType) {
489 // The legacy implementation of BitmapFactory used kAlpha8 for
490 // grayscale images (before kGray8 existed). While the codec
491 // recognizes kGray8, we need to decode into a kAlpha8 bitmap
492 // in order to avoid a behavior change.
Matt Sarettee80c4712016-06-03 10:23:38 -0400493 bitmapInfo =
494 bitmapInfo.makeColorType(kAlpha_8_SkColorType).makeAlphaType(kPremul_SkAlphaType);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500495 }
Chris Craik7e8c03c2013-06-03 13:53:36 -0700496 SkBitmap decodingBitmap;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500497 if (!decodingBitmap.setInfo(bitmapInfo) ||
Mike Reed81397c42017-07-18 17:04:16 -0400498 !decodingBitmap.tryAllocPixels(decodeAllocator)) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500499 // SkAndroidCodec should recommend a valid SkImageInfo, so setInfo()
500 // should only only fail if the calculated value for rowBytes is too
501 // large.
502 // tryAllocPixels() can fail due to OOM on the Java heap, OOM on the
503 // native heap, or the recycled javaBitmap being too small to reuse.
504 return nullptr;
Mike Reedc70e06b2009-04-24 11:09:12 -0400505 }
506
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500507 // Use SkAndroidCodec to perform the decode.
508 SkAndroidCodec::AndroidOptions codecOptions;
Romain Guy253f2c22016-09-28 17:34:42 -0700509 codecOptions.fZeroInitialized = decodeAllocator == &defaultAllocator ?
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500510 SkCodec::kYes_ZeroInitialized : SkCodec::kNo_ZeroInitialized;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500511 codecOptions.fSampleSize = sampleSize;
512 SkCodec::Result result = codec->getAndroidPixels(decodeInfo, decodingBitmap.getPixels(),
513 decodingBitmap.rowBytes(), &codecOptions);
514 switch (result) {
515 case SkCodec::kSuccess:
516 case SkCodec::kIncompleteInput:
517 break;
518 default:
Matt Sarett3b1b68d2015-12-14 13:08:33 -0500519 return nullObjectReturn("codec->getAndroidPixels() failed.");
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500520 }
521
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500522 // This is weird so let me explain: we could use the scale parameter
523 // directly, but for historical reasons this is how the corresponding
524 // Dalvik code has always behaved. We simply recreate the behavior here.
525 // The result is slightly different from simply using scale because of
526 // the 0.5f rounding bias applied when computing the target image size
527 const float scaleX = scaledWidth / float(decodingBitmap.width());
528 const float scaleY = scaledHeight / float(decodingBitmap.height());
529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 jbyteArray ninePatchChunk = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -0700531 if (peeker.mPatch != NULL) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700532 if (willScale) {
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500533 peeker.scale(scaleX, scaleY, scaledWidth, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700534 }
535
Chris Craik47cd8e92014-07-08 17:13:08 -0700536 size_t ninePatchArraySize = peeker.mPatch->serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700538 if (ninePatchChunk == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400539 return nullObjectReturn("ninePatchChunk == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700541
542 jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
543 if (array == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400544 return nullObjectReturn("primitive array == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700546
Chris Craik47cd8e92014-07-08 17:13:08 -0700547 memcpy(array, peeker.mPatch, peeker.mPatchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
549 }
550
Chris Craik47cd8e92014-07-08 17:13:08 -0700551 jobject ninePatchInsets = NULL;
552 if (peeker.mHasInsets) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400553 ninePatchInsets = peeker.createNinePatchInsets(env, scale);
Mathieu Chartiera08d10f2014-08-29 16:55:55 -0700554 if (ninePatchInsets == NULL) {
555 return nullObjectReturn("nine patch insets == null");
556 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700557 if (javaBitmap != NULL) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700558 env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700559 }
560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561
John Reckf29ed282015-04-07 07:32:03 -0700562 SkBitmap outputBitmap;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700563 if (willScale) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500564 // Set the allocator for the outputBitmap.
565 SkBitmap::Allocator* outputAllocator;
566 if (javaBitmap != nullptr) {
567 outputAllocator = &recyclingAllocator;
568 } else {
sergeyv45082182016-09-29 18:25:40 -0700569 outputAllocator = &defaultAllocator;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500570 }
571
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400572 SkColorType scaledColorType = decodingBitmap.colorType();
Leon Scroggins III8790be62013-12-03 16:26:51 -0500573 // FIXME: If the alphaType is kUnpremul and the image has alpha, the
574 // colors may not be correct, since Skia does not yet support drawing
575 // to/from unpremultiplied bitmaps.
Matt Sarettee80c4712016-06-03 10:23:38 -0400576 outputBitmap.setInfo(
577 bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
Mike Reed81397c42017-07-18 17:04:16 -0400578 if (!outputBitmap.tryAllocPixels(outputAllocator)) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500579 // This should only fail on OOM. The recyclingAllocator should have
580 // enough memory since we check this before decoding using the
581 // scaleCheckingAllocator.
Raph Levien005bfc62012-09-20 22:51:47 -0700582 return nullObjectReturn("allocation failed for scaled bitmap");
583 }
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400584
Romain Guy7b2f8b82012-03-19 17:18:54 -0700585 SkPaint paint;
Romain Guy253f2c22016-09-28 17:34:42 -0700586 // kSrc_Mode instructs us to overwrite the uninitialized pixels in
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500587 // outputBitmap. Otherwise we would blend by default, which is not
588 // what we want.
Mike Reed260ab722016-10-07 15:59:20 -0400589 paint.setBlendMode(SkBlendMode::kSrc);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700590
Matt Sarettca9b7032017-04-13 12:18:47 -0400591 SkCanvas canvas(outputBitmap, SkCanvas::ColorBehavior::kLegacy);
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500592 canvas.scale(scaleX, scaleY);
Mike Reed7994a312021-01-28 18:06:26 -0500593 decodingBitmap.setImmutable(); // so .asImage() doesn't make a copy
594 canvas.drawImage(decodingBitmap.asImage(), 0.0f, 0.0f,
595 SkSamplingOptions(SkFilterMode::kLinear), &paint);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700596 } else {
John Reckf29ed282015-04-07 07:32:03 -0700597 outputBitmap.swap(decodingBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700598 }
599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 if (padding) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400601 peeker.getPadding(env, padding);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500604 // If we get here, the outputBitmap should have an installed pixelref.
John Reckf29ed282015-04-07 07:32:03 -0700605 if (outputBitmap.pixelRef() == NULL) {
Marco Nelissenb2fe3be2012-05-07 11:24:13 -0700606 return nullObjectReturn("Got null SkPixelRef");
607 }
Romain Guy23610982011-01-17 12:51:55 -0800608
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000609 bool hasGainmap = false;
610 SkGainmapInfo gainmapInfo;
Christopher Cameroncf3d3fc2024-09-11 14:18:44 +0000611 std::unique_ptr<SkAndroidCodec> gainmapCodec;
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000612 sp<uirenderer::Gainmap> gainmap = nullptr;
613 if (result == SkCodec::kSuccess) {
Christopher Cameroncf3d3fc2024-09-11 14:18:44 +0000614 hasGainmap = codec->getGainmapAndroidCodec(&gainmapInfo, &gainmapCodec);
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000615 }
616
617 if (hasGainmap) {
618 hasGainmap =
Christopher Cameroncf3d3fc2024-09-11 14:18:44 +0000619 decodeGainmap(std::move(gainmapCodec), gainmapInfo, &gainmap, sampleSize, scale);
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000620 }
621
Chris Craik7e8c03c2013-06-03 13:53:36 -0700622 if (!isMutable && javaBitmap == NULL) {
Romain Guy23610982011-01-17 12:51:55 -0800623 // promise we will never change our pixels (great for sharing and pictures)
John Reckf29ed282015-04-07 07:32:03 -0700624 outputBitmap.setImmutable();
Romain Guy23610982011-01-17 12:51:55 -0800625 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800626
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500627 bool isPremultiplied = !requireUnpremultiplied;
628 if (javaBitmap != nullptr) {
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000629 if (hasGainmap) {
630 reuseBitmap->setGainmap(std::move(gainmap));
631 }
sergeyvc69853c2016-10-07 14:14:09 -0700632 bitmap::reinitBitmap(env, javaBitmap, outputBitmap.info(), isPremultiplied);
John Reckf29ed282015-04-07 07:32:03 -0700633 outputBitmap.notifyPixelsChanged();
Alec Mouri0ba21a72024-10-10 22:45:08 +0000634 uirenderer::logBitmapDecode(*reuseBitmap);
Chet Haase37f74ca2010-12-08 17:56:36 -0800635 // If a java bitmap was passed in for reuse, pass it back
636 return javaBitmap;
637 }
Chris Craik1abf5d62013-08-16 12:47:03 -0700638
639 int bitmapCreateFlags = 0x0;
sergeyvc69853c2016-10-07 14:14:09 -0700640 if (isMutable) bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Mutable;
641 if (isPremultiplied) bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Premultiplied;
Chris Craik1abf5d62013-08-16 12:47:03 -0700642
sergeyvda6c8ffc2016-11-22 18:28:54 -0800643 if (isHardware) {
644 sk_sp<Bitmap> hardwareBitmap = Bitmap::allocateHardwareBitmap(outputBitmap);
sergeyvd67bb1e2017-06-28 12:44:03 -0700645 if (!hardwareBitmap.get()) {
646 return nullObjectReturn("Failed to allocate a hardware bitmap");
647 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000648 if (hasGainmap) {
Sally Qi587fb572023-03-03 15:50:06 -0800649 auto gm = uirenderer::Gainmap::allocateHardwareGainmap(gainmap);
650 if (gm) {
651 hardwareBitmap->setGainmap(std::move(gm));
652 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000653 }
654
Alec Mouri0ba21a72024-10-10 22:45:08 +0000655 uirenderer::logBitmapDecode(*hardwareBitmap);
sergeyvda6c8ffc2016-11-22 18:28:54 -0800656 return bitmap::createBitmap(env, hardwareBitmap.release(), bitmapCreateFlags,
657 ninePatchChunk, ninePatchInsets, -1);
658 }
659
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000660 Bitmap* heapBitmap = defaultAllocator.getStorageObjAndReset();
661 if (hasGainmap && heapBitmap != nullptr) {
662 heapBitmap->setGainmap(std::move(gainmap));
663 }
664
Alec Mouri0ba21a72024-10-10 22:45:08 +0000665 uirenderer::logBitmapDecode(*heapBitmap);
Mike Reedc70e06b2009-04-24 11:09:12 -0400666 // now create the java bitmap
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000667 return bitmap::createBitmap(env, heapBitmap, bitmapCreateFlags, ninePatchChunk, ninePatchInsets,
668 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669}
670
Chris Craik905e8242013-06-05 09:59:05 -0700671static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400672 jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 jobject bitmap = NULL;
Ben Wagner60126ef2015-08-07 12:13:48 -0400675 std::unique_ptr<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676
Leon Scroggins IIIca320212013-08-20 17:59:39 -0400677 if (stream.get()) {
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400678 std::unique_ptr<SkStreamRewindable> bufferedStream(skia::FrontBufferedStream::Make(
679 std::move(stream), SkCodec::MinBufferedBytesNeeded()));
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400680 SkASSERT(bufferedStream.get() != NULL);
Leon Scroggins III71fae622019-03-26 16:28:41 -0400681 bitmap = doDecode(env, std::move(bufferedStream), padding, options, inBitmapHandle,
682 colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684 return bitmap;
685}
686
Romain Guy7b2f8b82012-03-19 17:18:54 -0700687static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400688 jobject padding, jobject bitmapFactoryOptions, jlong inBitmapHandle, jlong colorSpaceHandle) {
Michael Hoisiea7e2e592024-05-21 00:05:11 +0000689#ifdef _WIN32 // LayoutLib for Windows does not support F_DUPFD_CLOEXEC
690 return nullObjectReturn("Not supported on Windows");
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400691#else
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
693
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400694 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Mike Reedc70e06b2009-04-24 11:09:12 -0400695
Derek Sollenberger5827cb52013-07-26 14:58:06 -0400696 struct stat fdStat;
697 if (fstat(descriptor, &fdStat) == -1) {
698 doThrowIOE(env, "broken file descriptor");
699 return nullObjectReturn("fstat return -1");
700 }
701
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400702 // Restore the descriptor's offset on exiting this function. Even though
703 // we dup the descriptor, both the original and dup refer to the same open
704 // file description and changes to the file offset in one impact the other.
Jérôme Poichetd29c9022014-09-26 18:59:11 +0000705 AutoFDSeek autoRestore(descriptor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400707 // Duplicate the descriptor here to prevent leaking memory. A leak occurs
708 // if we only close the file descriptor and not the file object it is used to
709 // create. If we don't explicitly clean up the file (which in turn closes the
710 // descriptor) the buffers allocated internally by fseek will be leaked.
Nick Kralevich4b3a08c2019-01-28 10:39:10 -0800711 int dupDescriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, 0);
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400712
713 FILE* file = fdopen(dupDescriptor, "r");
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500714 if (file == NULL) {
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400715 // cleanup the duplicated descriptor since it will not be closed when the
716 // file is cleaned up (fclose).
717 close(dupDescriptor);
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500718 return nullObjectReturn("Could not open file");
Leon Scroggins IIIf65183f2013-10-07 16:32:14 -0400719 }
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500720
Leon Scroggins IIIdd3c06c2017-03-10 10:50:33 -0500721 std::unique_ptr<SkFILEStream> fileStream(new SkFILEStream(file));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100723 // If there is no offset for the file descriptor, we use SkFILEStream directly.
724 if (::lseek(descriptor, 0, SEEK_CUR) == 0) {
725 assert(isSeekable(dupDescriptor));
Leon Scroggins III0e443d12018-12-19 11:38:35 -0500726 return doDecode(env, std::move(fileStream), padding, bitmapFactoryOptions,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400727 inBitmapHandle, colorSpaceHandle);
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100728 }
729
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400730 // Use a buffered stream. Although an SkFILEStream can be rewound, this
731 // ensures that SkImageDecoder::Factory never rewinds beyond the
732 // current position of the file descriptor.
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400733 std::unique_ptr<SkStreamRewindable> stream(skia::FrontBufferedStream::Make(
734 std::move(fileStream), SkCodec::MinBufferedBytesNeeded()));
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500735
Leon Scroggins III71fae622019-03-26 16:28:41 -0400736 return doDecode(env, std::move(stream), padding, bitmapFactoryOptions, inBitmapHandle,
737 colorSpaceHandle);
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400738#endif
Mike Reedc70e06b2009-04-24 11:09:12 -0400739}
740
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000741static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400742 jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700743
Mike Reedc70e06b2009-04-24 11:09:12 -0400744 Asset* asset = reinterpret_cast<Asset*>(native_asset);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400745 // since we know we'll be done with the asset when we return, we can
746 // just use a simple wrapper
Mike Reed3cf42822019-12-12 11:59:49 -0500747 return doDecode(env, std::make_unique<AssetStreamAdaptor>(asset), padding, options,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400748 inBitmapHandle, colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749}
750
751static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400752 jint offset, jint length, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700753
Mike Reedc70e06b2009-04-24 11:09:12 -0400754 AutoJavaByteArray ar(env, byteArray);
Mike Reed3cf42822019-12-12 11:59:49 -0500755 return doDecode(env, std::make_unique<SkMemoryStream>(ar.ptr() + offset, length, false),
Leon Scroggins III71fae622019-03-26 16:28:41 -0400756 nullptr, options, inBitmapHandle, colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757}
758
Owen Lina9d0d472011-01-18 17:39:15 +0800759static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700760 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100761 return isSeekable(descriptor) ? JNI_TRUE : JNI_FALSE;
Owen Lina9d0d472011-01-18 17:39:15 +0800762}
763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764///////////////////////////////////////////////////////////////////////////////
765
Daniel Micay76f6a862015-09-19 17:31:01 -0400766static const JNINativeMethod gMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 { "nativeDecodeStream",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400768 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 (void*)nativeDecodeStream
770 },
771
772 { "nativeDecodeFileDescriptor",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400773 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 (void*)nativeDecodeFileDescriptor
775 },
776
777 { "nativeDecodeAsset",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400778 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 (void*)nativeDecodeAsset
780 },
781
782 { "nativeDecodeByteArray",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400783 "([BIILandroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 (void*)nativeDecodeByteArray
785 },
786
Owen Lina9d0d472011-01-18 17:39:15 +0800787 { "nativeIsSeekable",
788 "(Ljava/io/FileDescriptor;)Z",
789 (void*)nativeIsSeekable
790 },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791};
792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793int register_android_graphics_BitmapFactory(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800794 jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
795 gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
Chris Craik47cd8e92014-07-08 17:13:08 -0700796 "Landroid/graphics/Bitmap;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800797 gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
798 gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
799 gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 "Landroid/graphics/Bitmap$Config;");
Romain Guy95648b82017-04-13 18:43:42 -0700801 gOptions_colorSpaceFieldID = GetFieldIDOrDie(env, options_class, "inPreferredColorSpace",
802 "Landroid/graphics/ColorSpace;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800803 gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
804 gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
805 gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
806 gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800807 "inPreferQualityOverSpeed", "Z");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800808 gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
809 gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
810 gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
811 gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
812 gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
813 gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
814 gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
Romain Guye8d2ebb2017-02-09 18:38:47 -0800815 gOptions_outConfigFieldID = GetFieldIDOrDie(env, options_class, "outConfig",
816 "Landroid/graphics/Bitmap$Config;");
Romain Guy90fc43b2017-03-30 12:35:26 -0700817 gOptions_outColorSpaceFieldID = GetFieldIDOrDie(env, options_class, "outColorSpace",
818 "Landroid/graphics/ColorSpace;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800819 gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800821 jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800822 gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
Chris Craik47cd8e92014-07-08 17:13:08 -0700823 "Landroid/graphics/NinePatch$InsetStruct;");
824
Romain Guye8d2ebb2017-02-09 18:38:47 -0800825 gBitmapConfig_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
826 "android/graphics/Bitmap$Config"));
827 gBitmapConfig_nativeToConfigMethodID = GetStaticMethodIDOrDie(env, gBitmapConfig_class,
828 "nativeToConfig", "(I)Landroid/graphics/Bitmap$Config;");
829
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800830 return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
831 gMethods, NELEM(gMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832}