blob: 785aef312072ceb4167e5e66cf652f3b098b11b1 [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>
13
14#include <memory>
15
Ben Wagner60126ef2015-08-07 12:13:48 -040016#include "CreateJavaOutputStreamAdaptor.h"
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -040017#include "FrontBufferedStream.h"
Ben Wagner60126ef2015-08-07 12:13:48 -040018#include "GraphicsJNI.h"
Derek Sollenberger2173ea22020-02-19 15:37:29 -050019#include "MimeType.h"
Leon Scrogginsa06d86a2011-03-02 16:56:54 -050020#include "NinePatchPeeker.h"
Matt Sarettb8adc9a2015-12-02 13:35:22 -050021#include "SkAndroidCodec.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050022#include "SkBitmap.h"
23#include "SkBlendMode.h"
John Reckbe671952021-01-13 22:39:32 -050024#include "SkCanvas.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050025#include "SkColorSpace.h"
26#include "SkEncodedImageFormat.h"
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +000027#include "SkGainmapInfo.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050028#include "SkImageInfo.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050029#include "SkPaint.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030#include "SkPixelRef.h"
Kevin Lubick1175dc02022-02-28 12:41:27 -050031#include "SkRect.h"
32#include "SkRefCnt.h"
33#include "SkSamplingOptions.h"
34#include "SkSize.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035#include "SkStream.h"
John Reckbe671952021-01-13 22:39:32 -050036#include "SkString.h"
Wei-Ta Chen6b849e22010-09-07 17:32:18 +080037#include "Utils.h"
Ben Wagner60126ef2015-08-07 12:13:48 -040038
Joseph Wenf1f48bc2010-07-19 16:59:51 +080039jfieldID gOptions_justBoundsFieldID;
40jfieldID gOptions_sampleSizeFieldID;
41jfieldID gOptions_configFieldID;
Romain Guy95648b82017-04-13 18:43:42 -070042jfieldID gOptions_colorSpaceFieldID;
Chris Craik1abf5d62013-08-16 12:47:03 -070043jfieldID gOptions_premultipliedFieldID;
Romain Guy23610982011-01-17 12:51:55 -080044jfieldID gOptions_mutableFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080045jfieldID gOptions_ditherFieldID;
Wei-Ta Chen953f9092010-12-03 14:06:18 -080046jfieldID gOptions_preferQualityOverSpeedFieldID;
Chris Craik905e8242013-06-05 09:59:05 -070047jfieldID gOptions_scaledFieldID;
48jfieldID gOptions_densityFieldID;
49jfieldID gOptions_screenDensityFieldID;
50jfieldID gOptions_targetDensityFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080051jfieldID gOptions_widthFieldID;
52jfieldID gOptions_heightFieldID;
53jfieldID gOptions_mimeFieldID;
Romain Guye8d2ebb2017-02-09 18:38:47 -080054jfieldID gOptions_outConfigFieldID;
Romain Guy90fc43b2017-03-30 12:35:26 -070055jfieldID gOptions_outColorSpaceFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080056jfieldID gOptions_mCancelID;
Chet Haase37f74ca2010-12-08 17:56:36 -080057jfieldID gOptions_bitmapFieldID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
Chris Craik47cd8e92014-07-08 17:13:08 -070059jfieldID gBitmap_ninePatchInsetsFieldID;
60
Romain Guye8d2ebb2017-02-09 18:38:47 -080061jclass gBitmapConfig_class;
62jmethodID gBitmapConfig_nativeToConfigMethodID;
63
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064using namespace android;
65
Leon Scroggins III407b5442019-11-22 17:10:20 -050066const char* getMimeType(SkEncodedImageFormat format) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -050067 switch (format) {
Hal Canary10219fb2016-11-23 20:41:22 -050068 case SkEncodedImageFormat::kBMP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050069 return "image/bmp";
Hal Canary10219fb2016-11-23 20:41:22 -050070 case SkEncodedImageFormat::kGIF:
Leon Scroggins III407b5442019-11-22 17:10:20 -050071 return "image/gif";
Hal Canary10219fb2016-11-23 20:41:22 -050072 case SkEncodedImageFormat::kICO:
Leon Scroggins III407b5442019-11-22 17:10:20 -050073 return "image/x-ico";
Hal Canary10219fb2016-11-23 20:41:22 -050074 case SkEncodedImageFormat::kJPEG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050075 return "image/jpeg";
Hal Canary10219fb2016-11-23 20:41:22 -050076 case SkEncodedImageFormat::kPNG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050077 return "image/png";
Hal Canary10219fb2016-11-23 20:41:22 -050078 case SkEncodedImageFormat::kWEBP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050079 return "image/webp";
Chong Zhang48fa8902017-08-16 11:57:02 -070080 case SkEncodedImageFormat::kHEIF:
Leon Scroggins III407b5442019-11-22 17:10:20 -050081 return "image/heif";
Vignesh Venkatasubramanian4a46b9e2020-11-05 22:55:43 -080082 case SkEncodedImageFormat::kAVIF:
83 return "image/avif";
Hal Canary10219fb2016-11-23 20:41:22 -050084 case SkEncodedImageFormat::kWBMP:
Leon Scroggins III407b5442019-11-22 17:10:20 -050085 return "image/vnd.wap.wbmp";
Hal Canary10219fb2016-11-23 20:41:22 -050086 case SkEncodedImageFormat::kDNG:
Leon Scroggins III407b5442019-11-22 17:10:20 -050087 return "image/x-adobe-dng";
Matt Sarettb8adc9a2015-12-02 13:35:22 -050088 default:
Leon Scroggins III407b5442019-11-22 17:10:20 -050089 return nullptr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 }
Leon Scroggins III407b5442019-11-22 17:10:20 -050091}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Leon Scroggins III407b5442019-11-22 17:10:20 -050093jstring getMimeTypeAsJavaString(JNIEnv* env, SkEncodedImageFormat format) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +000094 jstring jstr = nullptr;
Leon Scroggins III407b5442019-11-22 17:10:20 -050095 const char* mimeType = getMimeType(format);
Matt Sarettb8adc9a2015-12-02 13:35:22 -050096 if (mimeType) {
Vladimir Marko7ab249a2015-01-06 18:17:52 +000097 // NOTE: Caller should env->ExceptionCheck() for OOM
98 // (can't check for nullptr as it's a valid return value)
Matt Sarettb8adc9a2015-12-02 13:35:22 -050099 jstr = env->NewStringUTF(mimeType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 }
101 return jstr;
102}
103
Chris Craik905e8242013-06-05 09:59:05 -0700104class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
105public:
106 ScaleCheckingAllocator(float scale, int size)
107 : mScale(scale), mSize(size) {
108 }
109
Mike Reed81397c42017-07-18 17:04:16 -0400110 virtual bool allocPixelRef(SkBitmap* bitmap) {
Chris Craik905e8242013-06-05 09:59:05 -0700111 // accounts for scale in final allocation, using eventual size and config
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400112 const int bytesPerPixel = SkColorTypeBytesPerPixel(bitmap->colorType());
Chris Craik905e8242013-06-05 09:59:05 -0700113 const int requestedSize = bytesPerPixel *
114 int(bitmap->width() * mScale + 0.5f) *
115 int(bitmap->height() * mScale + 0.5f);
116 if (requestedSize > mSize) {
117 ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
118 mSize, requestedSize);
119 return false;
120 }
Mike Reed81397c42017-07-18 17:04:16 -0400121 return SkBitmap::HeapAllocator::allocPixelRef(bitmap);
Chris Craik905e8242013-06-05 09:59:05 -0700122 }
123private:
124 const float mScale;
125 const int mSize;
126};
127
Chris Craik7e8c03c2013-06-03 13:53:36 -0700128class RecyclingPixelAllocator : public SkBitmap::Allocator {
129public:
sergeyvc1c54062016-10-19 18:47:26 -0700130 RecyclingPixelAllocator(android::Bitmap* bitmap, unsigned int size)
John Reckf29ed282015-04-07 07:32:03 -0700131 : mBitmap(bitmap), mSize(size) {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700132 }
133
134 ~RecyclingPixelAllocator() {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700135 }
136
Mike Reed81397c42017-07-18 17:04:16 -0400137 virtual bool allocPixelRef(SkBitmap* bitmap) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500138 const SkImageInfo& info = bitmap->info();
Leon Scroggins IIIf35b9892015-07-31 10:38:40 -0400139 if (info.colorType() == kUnknown_SkColorType) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500140 ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700141 return false;
142 }
Chris Craikcd0ba712013-09-06 14:40:30 -0700143
Mike Reed7569de02017-10-06 16:25:49 -0400144 const size_t size = info.computeByteSize(bitmap->rowBytes());
Kevin Lubickbab0bb32023-01-17 15:30:34 +0000145 if (size > INT32_MAX) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500146 ALOGW("bitmap is too large");
147 return false;
148 }
149
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500150 if (size > mSize) {
Dan Albert46d84442014-11-18 16:07:51 -0800151 ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap "
152 "(%zu bytes)", mSize, size);
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500153 return false;
154 }
155
Leon Scroggins IIIf51a80d2017-07-12 10:46:35 -0400156 mBitmap->reconfigure(info, bitmap->rowBytes());
Mike Reed826deef2017-04-04 15:32:04 -0400157 bitmap->setPixelRef(sk_ref_sp(mBitmap), 0, 0);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700158 return true;
159 }
160
161private:
sergeyvc1c54062016-10-19 18:47:26 -0700162 android::Bitmap* const mBitmap;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700163 const unsigned int mSize;
164};
165
Anton Daubert4e5ec342016-03-07 17:30:20 +0100166// Necessary for decodes when the native decoder cannot scale to appropriately match the sampleSize
167// (for example, RAW). If the sampleSize divides evenly into the dimension, we require that the
168// scale matches exactly. If sampleSize does not divide evenly, we allow the decoder to choose how
169// best to round.
170static bool needsFineScale(const int fullSize, const int decodedSize, const int sampleSize) {
171 if (fullSize % sampleSize == 0 && fullSize / sampleSize != decodedSize) {
172 return true;
173 } else if ((fullSize / sampleSize + 1) != decodedSize &&
174 (fullSize / sampleSize) != decodedSize) {
175 return true;
176 }
177 return false;
178}
179
180static bool needsFineScale(const SkISize fullSize, const SkISize decodedSize,
181 const int sampleSize) {
182 return needsFineScale(fullSize.width(), decodedSize.width(), sampleSize) ||
183 needsFineScale(fullSize.height(), decodedSize.height(), sampleSize);
184}
185
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000186static bool decodeGainmap(std::unique_ptr<SkStream> gainmapStream, const SkGainmapInfo& gainmapInfo,
187 sp<uirenderer::Gainmap>* outGainmap, const int sampleSize, float scale) {
188 std::unique_ptr<SkAndroidCodec> codec;
189 codec = SkAndroidCodec::MakeFromStream(std::move(gainmapStream), nullptr);
190 if (!codec) {
191 ALOGE("Can not create a codec for Gainmap.");
192 return false;
193 }
John Reck818328c2023-05-09 17:50:33 -0400194 SkColorType decodeColorType = kN32_SkColorType;
195 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
196 decodeColorType = kGray_8_SkColorType;
197 }
198 decodeColorType = codec->computeOutputColorType(decodeColorType);
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000199 sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(decodeColorType, nullptr);
200
201 SkISize size = codec->getSampledDimensions(sampleSize);
202
203 int scaledWidth = size.width();
204 int scaledHeight = size.height();
205 bool willScale = false;
206
207 // Apply a fine scaling step if necessary.
208 if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize) || scale != 1.0f) {
209 willScale = true;
210 // The operation below may loose precision (integer division), but it is put this way to
211 // mimic main image scale calculation
212 scaledWidth = static_cast<int>((codec->getInfo().width() / sampleSize) * scale + 0.5f);
213 scaledHeight = static_cast<int>((codec->getInfo().height() / sampleSize) * scale + 0.5f);
214 }
215
216 SkAlphaType alphaType = codec->computeOutputAlphaType(false);
217
218 const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(), decodeColorType,
219 alphaType, decodeColorSpace);
220
John Reck818328c2023-05-09 17:50:33 -0400221 SkImageInfo bitmapInfo = decodeInfo;
222 if (decodeColorType == kGray_8_SkColorType) {
223 // We treat gray8 as alpha8 in Bitmap's API surface
224 bitmapInfo = bitmapInfo.makeColorType(kAlpha_8_SkColorType);
225 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000226 SkBitmap decodeBitmap;
227 sk_sp<Bitmap> nativeBitmap = nullptr;
228
229 if (!decodeBitmap.setInfo(bitmapInfo)) {
230 ALOGE("Failed to setInfo.");
231 return false;
232 }
233
234 if (willScale) {
235 if (!decodeBitmap.tryAllocPixels(nullptr)) {
236 ALOGE("OOM allocating gainmap pixels.");
237 return false;
238 }
239 } else {
240 nativeBitmap = android::Bitmap::allocateHeapBitmap(&decodeBitmap);
241 if (!nativeBitmap) {
242 ALOGE("OOM allocating gainmap pixels.");
243 return false;
244 }
245 }
246
247 // Use SkAndroidCodec to perform the decode.
248 SkAndroidCodec::AndroidOptions codecOptions;
249 codecOptions.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
250 codecOptions.fSampleSize = sampleSize;
251 SkCodec::Result result = codec->getAndroidPixels(decodeInfo, decodeBitmap.getPixels(),
252 decodeBitmap.rowBytes(), &codecOptions);
253 switch (result) {
254 case SkCodec::kSuccess:
255 case SkCodec::kIncompleteInput:
256 break;
257 default:
258 ALOGE("Error decoding gainmap.");
259 return false;
260 }
261
262 if (willScale) {
263 SkBitmap gainmapBitmap;
264 const float scaleX = scaledWidth / float(decodeBitmap.width());
265 const float scaleY = scaledHeight / float(decodeBitmap.height());
266
267 SkColorType scaledColorType = decodeBitmap.colorType();
268 gainmapBitmap.setInfo(
269 bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
270
271 nativeBitmap = android::Bitmap::allocateHeapBitmap(&gainmapBitmap);
272 if (!nativeBitmap) {
273 ALOGE("OOM allocating gainmap pixels.");
274 return false;
275 }
276
277 SkPaint paint;
278 // kSrc_Mode instructs us to overwrite the uninitialized pixels in
279 // outputBitmap. Otherwise we would blend by default, which is not
280 // what we want.
281 paint.setBlendMode(SkBlendMode::kSrc);
282
283 SkCanvas canvas(gainmapBitmap, SkCanvas::ColorBehavior::kLegacy);
284 canvas.scale(scaleX, scaleY);
285 decodeBitmap.setImmutable(); // so .asImage() doesn't make a copy
286 canvas.drawImage(decodeBitmap.asImage(), 0.0f, 0.0f,
287 SkSamplingOptions(SkFilterMode::kLinear), &paint);
288 }
289
290 auto gainmap = sp<uirenderer::Gainmap>::make();
291 if (!gainmap) {
292 ALOGE("OOM allocating Gainmap");
293 return false;
294 }
295
296 gainmap->info = gainmapInfo;
297 gainmap->bitmap = std::move(nativeBitmap);
298 *outGainmap = std::move(gainmap);
299
300 return true;
301}
302
Mike Reedc7c65602017-07-26 10:40:25 -0400303static jobject doDecode(JNIEnv* env, std::unique_ptr<SkStreamRewindable> stream,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400304 jobject padding, jobject options, jlong inBitmapHandle,
305 jlong colorSpaceHandle) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500306 // Set default values for the options parameters.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 int sampleSize = 1;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500308 bool onlyDecodeSize = false;
Mike Reed42a1d082014-07-07 18:06:18 -0400309 SkColorType prefColorType = kN32_SkColorType;
sergeyvda6c8ffc2016-11-22 18:28:54 -0800310 bool isHardware = false;
Romain Guy23610982011-01-17 12:51:55 -0800311 bool isMutable = false;
Chris Craik905e8242013-06-05 09:59:05 -0700312 float scale = 1.0f;
Chris Craik1abf5d62013-08-16 12:47:03 -0700313 bool requireUnpremultiplied = false;
Chet Haase37f74ca2010-12-08 17:56:36 -0800314 jobject javaBitmap = NULL;
Leon Scroggins III0e443d12018-12-19 11:38:35 -0500315 sk_sp<SkColorSpace> prefColorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700316
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500317 // Update with options supplied by the client.
Romain Guy7b2f8b82012-03-19 17:18:54 -0700318 if (options != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500320 // Correct a non-positive sampleSize. sampleSize defaults to zero within the
321 // options object, which is strange.
322 if (sampleSize <= 0) {
323 sampleSize = 1;
324 }
325
326 if (env->GetBooleanField(options, gOptions_justBoundsFieldID)) {
327 onlyDecodeSize = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 // initialize these, in case we fail later on
331 env->SetIntField(options, gOptions_widthFieldID, -1);
332 env->SetIntField(options, gOptions_heightFieldID, -1);
333 env->SetObjectField(options, gOptions_mimeFieldID, 0);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800334 env->SetObjectField(options, gOptions_outConfigFieldID, 0);
Romain Guy90fc43b2017-03-30 12:35:26 -0700335 env->SetObjectField(options, gOptions_outColorSpaceFieldID, 0);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
Mike Reed42a1d082014-07-07 18:06:18 -0400338 prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
sergeyvda6c8ffc2016-11-22 18:28:54 -0800339 isHardware = GraphicsJNI::isHardwareConfig(env, jconfig);
Romain Guy23610982011-01-17 12:51:55 -0800340 isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
Chris Craik1abf5d62013-08-16 12:47:03 -0700341 requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
Chet Haase37f74ca2010-12-08 17:56:36 -0800342 javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
Chris Craik905e8242013-06-05 09:59:05 -0700343
344 if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
345 const int density = env->GetIntField(options, gOptions_densityFieldID);
346 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
347 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
348 if (density != 0 && targetDensity != 0 && density != screenDensity) {
349 scale = (float) targetDensity / density;
350 }
351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700353
sergeyv9fbb0b52016-11-23 10:27:33 -0800354 if (isMutable && isHardware) {
Hans Boehme5b337d2019-01-07 17:42:05 -0800355 doThrowIAE(env, "Bitmaps with Config.HARDWARE are always immutable");
sergeyv9fbb0b52016-11-23 10:27:33 -0800356 return nullObjectReturn("Cannot create mutable hardware bitmap");
357 }
358
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500359 // Create the codec.
360 NinePatchPeeker peeker;
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500361 std::unique_ptr<SkAndroidCodec> codec;
362 {
363 SkCodec::Result result;
364 std::unique_ptr<SkCodec> c = SkCodec::MakeFromStream(std::move(stream), &result,
365 &peeker);
366 if (!c) {
367 SkString msg;
368 msg.printf("Failed to create image decoder with message '%s'",
369 SkCodec::ResultToString(result));
370 return nullObjectReturn(msg.c_str());
371 }
372
373 codec = SkAndroidCodec::MakeFromCodec(std::move(c));
374 if (!codec) {
375 return nullObjectReturn("SkAndroidCodec::MakeFromCodec returned null");
376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700378
Matt Sarett3b1b68d2015-12-14 13:08:33 -0500379 // Do not allow ninepatch decodes to 565. In the past, decodes to 565
380 // would dither, and we do not want to pre-dither ninepatches, since we
381 // know that they will be stretched. We no longer dither 565 decodes,
382 // but we continue to prevent ninepatches from decoding to 565, in order
383 // to maintain the old behavior.
384 if (peeker.mPatch && kRGB_565_SkColorType == prefColorType) {
385 prefColorType = kN32_SkColorType;
386 }
387
Anton Daubert4e5ec342016-03-07 17:30:20 +0100388 // Determine the output size.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500389 SkISize size = codec->getSampledDimensions(sampleSize);
Anton Daubert4e5ec342016-03-07 17:30:20 +0100390
391 int scaledWidth = size.width();
392 int scaledHeight = size.height();
393 bool willScale = false;
394
395 // Apply a fine scaling step if necessary.
396 if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize)) {
397 willScale = true;
398 scaledWidth = codec->getInfo().width() / sampleSize;
399 scaledHeight = codec->getInfo().height() / sampleSize;
400 }
401
Romain Guye8d2ebb2017-02-09 18:38:47 -0800402 // Set the decode colorType
403 SkColorType decodeColorType = codec->computeOutputColorType(prefColorType);
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500404 if (decodeColorType == kRGBA_F16_SkColorType && isHardware &&
405 !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
406 decodeColorType = kN32_SkColorType;
407 }
408
Xiao Huangfff1a292023-04-12 17:37:36 +0000409 // b/276879147, fallback to RGBA_8888 when decoding HEIF and P010 is not supported.
410 if (decodeColorType == kRGBA_1010102_SkColorType &&
411 codec->getEncodedFormat() == SkEncodedImageFormat::kHEIF &&
412 env->CallStaticBooleanMethod(gImageDecoder_class,
413 gImageDecoder_isP010SupportedForHEVCMethodID) == JNI_FALSE) {
414 decodeColorType = kN32_SkColorType;
415 }
416
Romain Guy95648b82017-04-13 18:43:42 -0700417 sk_sp<SkColorSpace> decodeColorSpace = codec->computeOutputColorSpace(
418 decodeColorType, prefColorSpace);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800419
Anton Daubert4e5ec342016-03-07 17:30:20 +0100420 // Set the options and return if the client only wants the size.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500421 if (options != NULL) {
Leon Scroggins III407b5442019-11-22 17:10:20 -0500422 jstring mimeType = getMimeTypeAsJavaString(env, codec->getEncodedFormat());
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500423 if (env->ExceptionCheck()) {
Leon Scroggins III407b5442019-11-22 17:10:20 -0500424 return nullObjectReturn("OOM in getMimeTypeAsJavaString()");
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500425 }
Anton Daubert4e5ec342016-03-07 17:30:20 +0100426 env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
427 env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500428 env->SetObjectField(options, gOptions_mimeFieldID, mimeType);
429
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400430 jint configID = GraphicsJNI::colorTypeToLegacyBitmapConfig(decodeColorType);
Romain Guye8d2ebb2017-02-09 18:38:47 -0800431 if (isHardware) {
432 configID = GraphicsJNI::kHardware_LegacyBitmapConfig;
433 }
434 jobject config = env->CallStaticObjectMethod(gBitmapConfig_class,
435 gBitmapConfig_nativeToConfigMethodID, configID);
436 env->SetObjectField(options, gOptions_outConfigFieldID, config);
437
Romain Guy90fc43b2017-03-30 12:35:26 -0700438 env->SetObjectField(options, gOptions_outColorSpaceFieldID,
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500439 GraphicsJNI::getColorSpace(env, decodeColorSpace.get(), decodeColorType));
Romain Guy90fc43b2017-03-30 12:35:26 -0700440
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500441 if (onlyDecodeSize) {
442 return nullptr;
443 }
444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445
Anton Daubert4e5ec342016-03-07 17:30:20 +0100446 // Scale is necessary due to density differences.
447 if (scale != 1.0f) {
448 willScale = true;
449 scaledWidth = static_cast<int>(scaledWidth * scale + 0.5f);
450 scaledHeight = static_cast<int>(scaledHeight * scale + 0.5f);
451 }
452
sergeyvc1c54062016-10-19 18:47:26 -0700453 android::Bitmap* reuseBitmap = nullptr;
Chris Craik9f583612013-05-20 18:13:47 -0700454 unsigned int existingBufferSize = 0;
Leon Scroggins III71fae622019-03-26 16:28:41 -0400455 if (javaBitmap != nullptr) {
456 reuseBitmap = &bitmap::toBitmap(inBitmapHandle);
sergeyvc69853c2016-10-07 14:14:09 -0700457 if (reuseBitmap->isImmutable()) {
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400458 ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
Leon Scroggins IIIca8aef62019-03-26 12:11:27 -0400459 javaBitmap = nullptr;
John Reckf29ed282015-04-07 07:32:03 -0700460 reuseBitmap = nullptr;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700461 } else {
Leon Scroggins IIIca8aef62019-03-26 12:11:27 -0400462 existingBufferSize = reuseBitmap->getAllocationByteCount();
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400463 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465
sergeyv45082182016-09-29 18:25:40 -0700466 HeapAllocator defaultAllocator;
John Reckf29ed282015-04-07 07:32:03 -0700467 RecyclingPixelAllocator recyclingAllocator(reuseBitmap, existingBufferSize);
Chris Craik905e8242013-06-05 09:59:05 -0700468 ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500469 SkBitmap::HeapAllocator heapAllocator;
470 SkBitmap::Allocator* decodeAllocator;
471 if (javaBitmap != nullptr && willScale) {
472 // This will allocate pixels using a HeapAllocator, since there will be an extra
473 // scaling step that copies these pixels into Java memory. This allocator
474 // also checks that the recycled javaBitmap is large enough.
475 decodeAllocator = &scaleCheckingAllocator;
476 } else if (javaBitmap != nullptr) {
477 decodeAllocator = &recyclingAllocator;
sergeyvda6c8ffc2016-11-22 18:28:54 -0800478 } else if (willScale || isHardware) {
479 // This will allocate pixels using a HeapAllocator,
480 // for scale case: there will be an extra scaling step.
481 // for hardware case: there will be extra swizzling & upload to gralloc step.
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500482 decodeAllocator = &heapAllocator;
483 } else {
sergeyv45082182016-09-29 18:25:40 -0700484 decodeAllocator = &defaultAllocator;
Chris Craik905e8242013-06-05 09:59:05 -0700485 }
486
Matt Sarett9e7cd632015-12-11 10:54:28 -0500487 SkAlphaType alphaType = codec->computeOutputAlphaType(requireUnpremultiplied);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500488
Romain Guy253f2c22016-09-28 17:34:42 -0700489 const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(),
Romain Guy90fc43b2017-03-30 12:35:26 -0700490 decodeColorType, alphaType, decodeColorSpace);
Matt Sarett6c382572017-02-21 17:42:41 -0500491
Matt Sarett327c7202017-02-22 17:38:20 -0500492 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500493 if (decodeColorType == kGray_8_SkColorType) {
494 // The legacy implementation of BitmapFactory used kAlpha8 for
495 // grayscale images (before kGray8 existed). While the codec
496 // recognizes kGray8, we need to decode into a kAlpha8 bitmap
497 // in order to avoid a behavior change.
Matt Sarettee80c4712016-06-03 10:23:38 -0400498 bitmapInfo =
499 bitmapInfo.makeColorType(kAlpha_8_SkColorType).makeAlphaType(kPremul_SkAlphaType);
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500500 }
Chris Craik7e8c03c2013-06-03 13:53:36 -0700501 SkBitmap decodingBitmap;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500502 if (!decodingBitmap.setInfo(bitmapInfo) ||
Mike Reed81397c42017-07-18 17:04:16 -0400503 !decodingBitmap.tryAllocPixels(decodeAllocator)) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500504 // SkAndroidCodec should recommend a valid SkImageInfo, so setInfo()
505 // should only only fail if the calculated value for rowBytes is too
506 // large.
507 // tryAllocPixels() can fail due to OOM on the Java heap, OOM on the
508 // native heap, or the recycled javaBitmap being too small to reuse.
509 return nullptr;
Mike Reedc70e06b2009-04-24 11:09:12 -0400510 }
511
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500512 // Use SkAndroidCodec to perform the decode.
513 SkAndroidCodec::AndroidOptions codecOptions;
Romain Guy253f2c22016-09-28 17:34:42 -0700514 codecOptions.fZeroInitialized = decodeAllocator == &defaultAllocator ?
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500515 SkCodec::kYes_ZeroInitialized : SkCodec::kNo_ZeroInitialized;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500516 codecOptions.fSampleSize = sampleSize;
517 SkCodec::Result result = codec->getAndroidPixels(decodeInfo, decodingBitmap.getPixels(),
518 decodingBitmap.rowBytes(), &codecOptions);
519 switch (result) {
520 case SkCodec::kSuccess:
521 case SkCodec::kIncompleteInput:
522 break;
523 default:
Matt Sarett3b1b68d2015-12-14 13:08:33 -0500524 return nullObjectReturn("codec->getAndroidPixels() failed.");
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500525 }
526
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500527 // This is weird so let me explain: we could use the scale parameter
528 // directly, but for historical reasons this is how the corresponding
529 // Dalvik code has always behaved. We simply recreate the behavior here.
530 // The result is slightly different from simply using scale because of
531 // the 0.5f rounding bias applied when computing the target image size
532 const float scaleX = scaledWidth / float(decodingBitmap.width());
533 const float scaleY = scaledHeight / float(decodingBitmap.height());
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 jbyteArray ninePatchChunk = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -0700536 if (peeker.mPatch != NULL) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700537 if (willScale) {
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500538 peeker.scale(scaleX, scaleY, scaledWidth, scaledHeight);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700539 }
540
Chris Craik47cd8e92014-07-08 17:13:08 -0700541 size_t ninePatchArraySize = peeker.mPatch->serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700543 if (ninePatchChunk == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400544 return nullObjectReturn("ninePatchChunk == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700546
547 jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
548 if (array == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400549 return nullObjectReturn("primitive array == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700551
Chris Craik47cd8e92014-07-08 17:13:08 -0700552 memcpy(array, peeker.mPatch, peeker.mPatchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
554 }
555
Chris Craik47cd8e92014-07-08 17:13:08 -0700556 jobject ninePatchInsets = NULL;
557 if (peeker.mHasInsets) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400558 ninePatchInsets = peeker.createNinePatchInsets(env, scale);
Mathieu Chartiera08d10f2014-08-29 16:55:55 -0700559 if (ninePatchInsets == NULL) {
560 return nullObjectReturn("nine patch insets == null");
561 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700562 if (javaBitmap != NULL) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700563 env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700564 }
565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566
John Reckf29ed282015-04-07 07:32:03 -0700567 SkBitmap outputBitmap;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700568 if (willScale) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500569 // Set the allocator for the outputBitmap.
570 SkBitmap::Allocator* outputAllocator;
571 if (javaBitmap != nullptr) {
572 outputAllocator = &recyclingAllocator;
573 } else {
sergeyv45082182016-09-29 18:25:40 -0700574 outputAllocator = &defaultAllocator;
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500575 }
576
Leon Scroggins IIIef691a3d2017-07-10 17:03:55 -0400577 SkColorType scaledColorType = decodingBitmap.colorType();
Leon Scroggins III8790be62013-12-03 16:26:51 -0500578 // FIXME: If the alphaType is kUnpremul and the image has alpha, the
579 // colors may not be correct, since Skia does not yet support drawing
580 // to/from unpremultiplied bitmaps.
Matt Sarettee80c4712016-06-03 10:23:38 -0400581 outputBitmap.setInfo(
582 bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
Mike Reed81397c42017-07-18 17:04:16 -0400583 if (!outputBitmap.tryAllocPixels(outputAllocator)) {
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500584 // This should only fail on OOM. The recyclingAllocator should have
585 // enough memory since we check this before decoding using the
586 // scaleCheckingAllocator.
Raph Levien005bfc62012-09-20 22:51:47 -0700587 return nullObjectReturn("allocation failed for scaled bitmap");
588 }
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400589
Romain Guy7b2f8b82012-03-19 17:18:54 -0700590 SkPaint paint;
Romain Guy253f2c22016-09-28 17:34:42 -0700591 // kSrc_Mode instructs us to overwrite the uninitialized pixels in
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500592 // outputBitmap. Otherwise we would blend by default, which is not
593 // what we want.
Mike Reed260ab722016-10-07 15:59:20 -0400594 paint.setBlendMode(SkBlendMode::kSrc);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700595
Matt Sarettca9b7032017-04-13 12:18:47 -0400596 SkCanvas canvas(outputBitmap, SkCanvas::ColorBehavior::kLegacy);
Stan Iliev7aedf6f2017-12-20 12:22:59 -0500597 canvas.scale(scaleX, scaleY);
Mike Reed7994a312021-01-28 18:06:26 -0500598 decodingBitmap.setImmutable(); // so .asImage() doesn't make a copy
599 canvas.drawImage(decodingBitmap.asImage(), 0.0f, 0.0f,
600 SkSamplingOptions(SkFilterMode::kLinear), &paint);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700601 } else {
John Reckf29ed282015-04-07 07:32:03 -0700602 outputBitmap.swap(decodingBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700603 }
604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 if (padding) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400606 peeker.getPadding(env, padding);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500609 // If we get here, the outputBitmap should have an installed pixelref.
John Reckf29ed282015-04-07 07:32:03 -0700610 if (outputBitmap.pixelRef() == NULL) {
Marco Nelissenb2fe3be2012-05-07 11:24:13 -0700611 return nullObjectReturn("Got null SkPixelRef");
612 }
Romain Guy23610982011-01-17 12:51:55 -0800613
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000614 bool hasGainmap = false;
615 SkGainmapInfo gainmapInfo;
616 std::unique_ptr<SkStream> gainmapStream = nullptr;
617 sp<uirenderer::Gainmap> gainmap = nullptr;
618 if (result == SkCodec::kSuccess) {
619 hasGainmap = codec->getAndroidGainmap(&gainmapInfo, &gainmapStream);
620 }
621
622 if (hasGainmap) {
623 hasGainmap =
624 decodeGainmap(std::move(gainmapStream), gainmapInfo, &gainmap, sampleSize, scale);
625 }
626
Chris Craik7e8c03c2013-06-03 13:53:36 -0700627 if (!isMutable && javaBitmap == NULL) {
Romain Guy23610982011-01-17 12:51:55 -0800628 // promise we will never change our pixels (great for sharing and pictures)
John Reckf29ed282015-04-07 07:32:03 -0700629 outputBitmap.setImmutable();
Romain Guy23610982011-01-17 12:51:55 -0800630 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800631
Matt Sarettb8adc9a2015-12-02 13:35:22 -0500632 bool isPremultiplied = !requireUnpremultiplied;
633 if (javaBitmap != nullptr) {
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000634 if (hasGainmap) {
635 reuseBitmap->setGainmap(std::move(gainmap));
636 }
sergeyvc69853c2016-10-07 14:14:09 -0700637 bitmap::reinitBitmap(env, javaBitmap, outputBitmap.info(), isPremultiplied);
John Reckf29ed282015-04-07 07:32:03 -0700638 outputBitmap.notifyPixelsChanged();
Chet Haase37f74ca2010-12-08 17:56:36 -0800639 // If a java bitmap was passed in for reuse, pass it back
640 return javaBitmap;
641 }
Chris Craik1abf5d62013-08-16 12:47:03 -0700642
643 int bitmapCreateFlags = 0x0;
sergeyvc69853c2016-10-07 14:14:09 -0700644 if (isMutable) bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Mutable;
645 if (isPremultiplied) bitmapCreateFlags |= android::bitmap::kBitmapCreateFlag_Premultiplied;
Chris Craik1abf5d62013-08-16 12:47:03 -0700646
sergeyvda6c8ffc2016-11-22 18:28:54 -0800647 if (isHardware) {
648 sk_sp<Bitmap> hardwareBitmap = Bitmap::allocateHardwareBitmap(outputBitmap);
sergeyvd67bb1e2017-06-28 12:44:03 -0700649 if (!hardwareBitmap.get()) {
650 return nullObjectReturn("Failed to allocate a hardware bitmap");
651 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000652 if (hasGainmap) {
Sally Qi587fb572023-03-03 15:50:06 -0800653 auto gm = uirenderer::Gainmap::allocateHardwareGainmap(gainmap);
654 if (gm) {
655 hardwareBitmap->setGainmap(std::move(gm));
656 }
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000657 }
658
sergeyvda6c8ffc2016-11-22 18:28:54 -0800659 return bitmap::createBitmap(env, hardwareBitmap.release(), bitmapCreateFlags,
660 ninePatchChunk, ninePatchInsets, -1);
661 }
662
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000663 Bitmap* heapBitmap = defaultAllocator.getStorageObjAndReset();
664 if (hasGainmap && heapBitmap != nullptr) {
665 heapBitmap->setGainmap(std::move(gainmap));
666 }
667
Mike Reedc70e06b2009-04-24 11:09:12 -0400668 // now create the java bitmap
Fyodor Kyslov45b0a0f2023-02-04 00:41:47 +0000669 return bitmap::createBitmap(env, heapBitmap, bitmapCreateFlags, ninePatchChunk, ninePatchInsets,
670 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671}
672
Chris Craik905e8242013-06-05 09:59:05 -0700673static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400674 jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 jobject bitmap = NULL;
Ben Wagner60126ef2015-08-07 12:13:48 -0400677 std::unique_ptr<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678
Leon Scroggins IIIca320212013-08-20 17:59:39 -0400679 if (stream.get()) {
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400680 std::unique_ptr<SkStreamRewindable> bufferedStream(skia::FrontBufferedStream::Make(
681 std::move(stream), SkCodec::MinBufferedBytesNeeded()));
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400682 SkASSERT(bufferedStream.get() != NULL);
Leon Scroggins III71fae622019-03-26 16:28:41 -0400683 bitmap = doDecode(env, std::move(bufferedStream), padding, options, inBitmapHandle,
684 colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686 return bitmap;
687}
688
Romain Guy7b2f8b82012-03-19 17:18:54 -0700689static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400690 jobject padding, jobject bitmapFactoryOptions, jlong inBitmapHandle, jlong colorSpaceHandle) {
Michael Hoisiea7e2e592024-05-21 00:05:11 +0000691#ifdef _WIN32 // LayoutLib for Windows does not support F_DUPFD_CLOEXEC
692 return nullObjectReturn("Not supported on Windows");
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400693#else
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
695
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400696 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Mike Reedc70e06b2009-04-24 11:09:12 -0400697
Derek Sollenberger5827cb52013-07-26 14:58:06 -0400698 struct stat fdStat;
699 if (fstat(descriptor, &fdStat) == -1) {
700 doThrowIOE(env, "broken file descriptor");
701 return nullObjectReturn("fstat return -1");
702 }
703
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400704 // Restore the descriptor's offset on exiting this function. Even though
705 // we dup the descriptor, both the original and dup refer to the same open
706 // file description and changes to the file offset in one impact the other.
Jérôme Poichetd29c9022014-09-26 18:59:11 +0000707 AutoFDSeek autoRestore(descriptor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400709 // Duplicate the descriptor here to prevent leaking memory. A leak occurs
710 // if we only close the file descriptor and not the file object it is used to
711 // create. If we don't explicitly clean up the file (which in turn closes the
712 // descriptor) the buffers allocated internally by fseek will be leaked.
Nick Kralevich4b3a08c2019-01-28 10:39:10 -0800713 int dupDescriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, 0);
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400714
715 FILE* file = fdopen(dupDescriptor, "r");
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500716 if (file == NULL) {
Derek Sollenberger5cb769d2014-09-24 09:20:09 -0400717 // cleanup the duplicated descriptor since it will not be closed when the
718 // file is cleaned up (fclose).
719 close(dupDescriptor);
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500720 return nullObjectReturn("Could not open file");
Leon Scroggins IIIf65183f2013-10-07 16:32:14 -0400721 }
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500722
Leon Scroggins IIIdd3c06c2017-03-10 10:50:33 -0500723 std::unique_ptr<SkFILEStream> fileStream(new SkFILEStream(file));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100725 // If there is no offset for the file descriptor, we use SkFILEStream directly.
726 if (::lseek(descriptor, 0, SEEK_CUR) == 0) {
727 assert(isSeekable(dupDescriptor));
Leon Scroggins III0e443d12018-12-19 11:38:35 -0500728 return doDecode(env, std::move(fileStream), padding, bitmapFactoryOptions,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400729 inBitmapHandle, colorSpaceHandle);
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100730 }
731
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400732 // Use a buffered stream. Although an SkFILEStream can be rewound, this
733 // ensures that SkImageDecoder::Factory never rewinds beyond the
734 // current position of the file descriptor.
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400735 std::unique_ptr<SkStreamRewindable> stream(skia::FrontBufferedStream::Make(
736 std::move(fileStream), SkCodec::MinBufferedBytesNeeded()));
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500737
Leon Scroggins III71fae622019-03-26 16:28:41 -0400738 return doDecode(env, std::move(stream), padding, bitmapFactoryOptions, inBitmapHandle,
739 colorSpaceHandle);
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400740#endif
Mike Reedc70e06b2009-04-24 11:09:12 -0400741}
742
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000743static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400744 jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700745
Mike Reedc70e06b2009-04-24 11:09:12 -0400746 Asset* asset = reinterpret_cast<Asset*>(native_asset);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400747 // since we know we'll be done with the asset when we return, we can
748 // just use a simple wrapper
Mike Reed3cf42822019-12-12 11:59:49 -0500749 return doDecode(env, std::make_unique<AssetStreamAdaptor>(asset), padding, options,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400750 inBitmapHandle, colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751}
752
753static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
Leon Scroggins III71fae622019-03-26 16:28:41 -0400754 jint offset, jint length, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700755
Mike Reedc70e06b2009-04-24 11:09:12 -0400756 AutoJavaByteArray ar(env, byteArray);
Mike Reed3cf42822019-12-12 11:59:49 -0500757 return doDecode(env, std::make_unique<SkMemoryStream>(ar.ptr() + offset, length, false),
Leon Scroggins III71fae622019-03-26 16:28:41 -0400758 nullptr, options, inBitmapHandle, colorSpaceHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759}
760
Owen Lina9d0d472011-01-18 17:39:15 +0800761static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700762 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Yujie Qinc1d7b7f2016-02-29 14:00:29 +0100763 return isSeekable(descriptor) ? JNI_TRUE : JNI_FALSE;
Owen Lina9d0d472011-01-18 17:39:15 +0800764}
765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766///////////////////////////////////////////////////////////////////////////////
767
Daniel Micay76f6a862015-09-19 17:31:01 -0400768static const JNINativeMethod gMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 { "nativeDecodeStream",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400770 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 (void*)nativeDecodeStream
772 },
773
774 { "nativeDecodeFileDescriptor",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400775 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 (void*)nativeDecodeFileDescriptor
777 },
778
779 { "nativeDecodeAsset",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400780 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 (void*)nativeDecodeAsset
782 },
783
784 { "nativeDecodeByteArray",
Leon Scroggins III71fae622019-03-26 16:28:41 -0400785 "([BIILandroid/graphics/BitmapFactory$Options;JJ)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 (void*)nativeDecodeByteArray
787 },
788
Owen Lina9d0d472011-01-18 17:39:15 +0800789 { "nativeIsSeekable",
790 "(Ljava/io/FileDescriptor;)Z",
791 (void*)nativeIsSeekable
792 },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793};
794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795int register_android_graphics_BitmapFactory(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800796 jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options");
797 gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap",
Chris Craik47cd8e92014-07-08 17:13:08 -0700798 "Landroid/graphics/Bitmap;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800799 gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z");
800 gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I");
801 gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 "Landroid/graphics/Bitmap$Config;");
Romain Guy95648b82017-04-13 18:43:42 -0700803 gOptions_colorSpaceFieldID = GetFieldIDOrDie(env, options_class, "inPreferredColorSpace",
804 "Landroid/graphics/ColorSpace;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800805 gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z");
806 gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z");
807 gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z");
808 gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class,
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800809 "inPreferQualityOverSpeed", "Z");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800810 gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z");
811 gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I");
812 gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I");
813 gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I");
814 gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I");
815 gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I");
816 gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;");
Romain Guye8d2ebb2017-02-09 18:38:47 -0800817 gOptions_outConfigFieldID = GetFieldIDOrDie(env, options_class, "outConfig",
818 "Landroid/graphics/Bitmap$Config;");
Romain Guy90fc43b2017-03-30 12:35:26 -0700819 gOptions_outColorSpaceFieldID = GetFieldIDOrDie(env, options_class, "outColorSpace",
820 "Landroid/graphics/ColorSpace;");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800821 gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800823 jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap");
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800824 gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets",
Chris Craik47cd8e92014-07-08 17:13:08 -0700825 "Landroid/graphics/NinePatch$InsetStruct;");
826
Romain Guye8d2ebb2017-02-09 18:38:47 -0800827 gBitmapConfig_class = MakeGlobalRefOrDie(env, FindClassOrDie(env,
828 "android/graphics/Bitmap$Config"));
829 gBitmapConfig_nativeToConfigMethodID = GetStaticMethodIDOrDie(env, gBitmapConfig_class,
830 "nativeToConfig", "(I)Landroid/graphics/Bitmap$Config;");
831
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800832 return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory",
833 gMethods, NELEM(gMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834}