blob: a890eb4b5bf954cae2c719adf8ee0209e019c69a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001#define LOG_TAG "BitmapFactory"
2
Joseph Wenf1f48bc2010-07-19 16:59:51 +08003#include "BitmapFactory.h"
Leon Scrogginsa06d86a2011-03-02 16:56:54 -05004#include "NinePatchPeeker.h"
Leon Scroggins III7315f1b2013-09-10 20:26:05 -04005#include "SkFrontBufferedStream.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006#include "SkImageDecoder.h"
Leon Scroggins46cb9bd2014-03-06 15:36:39 -05007#include "SkMath.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008#include "SkPixelRef.h"
9#include "SkStream.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010#include "SkTemplates.h"
11#include "SkUtils.h"
12#include "CreateJavaOutputStreamAdaptor.h"
Joseph Wenf1f48bc2010-07-19 16:59:51 +080013#include "AutoDecodeCancel.h"
Wei-Ta Chen6b849e22010-09-07 17:32:18 +080014#include "Utils.h"
Elliott Hughesa3804cf2011-04-11 16:50:19 -070015#include "JNIHelp.h"
Chris Craik1abf5d62013-08-16 12:47:03 -070016#include "GraphicsJNI.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017
18#include <android_runtime/AndroidRuntime.h>
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080019#include <androidfw/Asset.h>
20#include <androidfw/ResourceTypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021#include <netinet/in.h>
Leon Scroggins III0102f8a2014-01-14 15:14:57 -050022#include <stdio.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023#include <sys/mman.h>
Joseph Wen2dcfbef2010-09-10 10:15:09 +080024#include <sys/stat.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
Joseph Wenf1f48bc2010-07-19 16:59:51 +080026jfieldID gOptions_justBoundsFieldID;
27jfieldID gOptions_sampleSizeFieldID;
28jfieldID gOptions_configFieldID;
Chris Craik1abf5d62013-08-16 12:47:03 -070029jfieldID gOptions_premultipliedFieldID;
Romain Guy23610982011-01-17 12:51:55 -080030jfieldID gOptions_mutableFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080031jfieldID gOptions_ditherFieldID;
Wei-Ta Chen953f9092010-12-03 14:06:18 -080032jfieldID gOptions_preferQualityOverSpeedFieldID;
Chris Craik905e8242013-06-05 09:59:05 -070033jfieldID gOptions_scaledFieldID;
34jfieldID gOptions_densityFieldID;
35jfieldID gOptions_screenDensityFieldID;
36jfieldID gOptions_targetDensityFieldID;
Joseph Wenf1f48bc2010-07-19 16:59:51 +080037jfieldID gOptions_widthFieldID;
38jfieldID gOptions_heightFieldID;
39jfieldID gOptions_mimeFieldID;
40jfieldID gOptions_mCancelID;
Chet Haase37f74ca2010-12-08 17:56:36 -080041jfieldID gOptions_bitmapFieldID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
Chris Craik47cd8e92014-07-08 17:13:08 -070043jfieldID gBitmap_nativeBitmapFieldID;
44jfieldID gBitmap_ninePatchInsetsFieldID;
45
46jclass gInsetStruct_class;
47jmethodID gInsetStruct_constructorMethodID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049using namespace android;
50
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051static inline int32_t validOrNeg1(bool isValid, int32_t value) {
52// return isValid ? value : -1;
53 SkASSERT((int)isValid == 0 || (int)isValid == 1);
54 return ((int32_t)isValid - 1) | value;
55}
56
Joseph Wenf1f48bc2010-07-19 16:59:51 +080057jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 static const struct {
59 SkImageDecoder::Format fFormat;
60 const char* fMimeType;
61 } gMimeTypes[] = {
62 { SkImageDecoder::kBMP_Format, "image/bmp" },
63 { SkImageDecoder::kGIF_Format, "image/gif" },
64 { SkImageDecoder::kICO_Format, "image/x-ico" },
65 { SkImageDecoder::kJPEG_Format, "image/jpeg" },
66 { SkImageDecoder::kPNG_Format, "image/png" },
Chris Craik95587f92013-07-12 19:46:19 -070067 { SkImageDecoder::kWEBP_Format, "image/webp" },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" }
69 };
Elliott Hughesa3804cf2011-04-11 16:50:19 -070070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 const char* cstr = NULL;
72 for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) {
73 if (gMimeTypes[i].fFormat == format) {
74 cstr = gMimeTypes[i].fMimeType;
75 break;
76 }
77 }
78
79 jstring jstr = 0;
80 if (NULL != cstr) {
81 jstr = env->NewStringUTF(cstr);
82 }
83 return jstr;
84}
85
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +000086static bool optionsJustBounds(JNIEnv* env, jobject options) {
Romain Guycaf813f2012-03-15 18:57:48 -070087 return options != NULL && env->GetBooleanField(options, gOptions_justBoundsFieldID);
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +000088}
89
Romain Guy7b2f8b82012-03-19 17:18:54 -070090static void scaleNinePatchChunk(android::Res_png_9patch* chunk, float scale) {
91 chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f);
92 chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f);
93 chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f);
94 chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f);
95
Narayan Kamath6381dd42014-03-03 17:12:03 +000096 int32_t* xDivs = chunk->getXDivs();
Romain Guy7b2f8b82012-03-19 17:18:54 -070097 for (int i = 0; i < chunk->numXDivs; i++) {
Narayan Kamath6381dd42014-03-03 17:12:03 +000098 xDivs[i] = int32_t(xDivs[i] * scale + 0.5f);
99 if (i > 0 && xDivs[i] == xDivs[i - 1]) {
100 xDivs[i]++;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700101 }
102 }
103
Narayan Kamath42a51ae2014-03-11 16:50:30 +0000104 int32_t* yDivs = chunk->getYDivs();
Romain Guy7b2f8b82012-03-19 17:18:54 -0700105 for (int i = 0; i < chunk->numYDivs; i++) {
Narayan Kamath6381dd42014-03-03 17:12:03 +0000106 yDivs[i] = int32_t(yDivs[i] * scale + 0.5f);
107 if (i > 0 && yDivs[i] == yDivs[i - 1]) {
108 yDivs[i]++;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700109 }
110 }
111}
112
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500113static SkColorType colorTypeForScaledOutput(SkColorType colorType) {
114 switch (colorType) {
115 case kUnknown_SkColorType:
116 case kIndex_8_SkColorType:
Mike Reed4a9c3892014-07-07 15:44:40 -0400117 return kN32_SkColorType;
Chris Craik905e8242013-06-05 09:59:05 -0700118 default:
119 break;
120 }
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500121 return colorType;
Chris Craik905e8242013-06-05 09:59:05 -0700122}
123
124class ScaleCheckingAllocator : public SkBitmap::HeapAllocator {
125public:
126 ScaleCheckingAllocator(float scale, int size)
127 : mScale(scale), mSize(size) {
128 }
129
130 virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
131 // accounts for scale in final allocation, using eventual size and config
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500132 const int bytesPerPixel = SkColorTypeBytesPerPixel(
133 colorTypeForScaledOutput(bitmap->colorType()));
Chris Craik905e8242013-06-05 09:59:05 -0700134 const int requestedSize = bytesPerPixel *
135 int(bitmap->width() * mScale + 0.5f) *
136 int(bitmap->height() * mScale + 0.5f);
137 if (requestedSize > mSize) {
138 ALOGW("bitmap for alloc reuse (%d bytes) can't fit scaled bitmap (%d bytes)",
139 mSize, requestedSize);
140 return false;
141 }
142 return SkBitmap::HeapAllocator::allocPixelRef(bitmap, ctable);
143 }
144private:
145 const float mScale;
146 const int mSize;
147};
148
Chris Craik7e8c03c2013-06-03 13:53:36 -0700149class RecyclingPixelAllocator : public SkBitmap::Allocator {
150public:
151 RecyclingPixelAllocator(SkPixelRef* pixelRef, unsigned int size)
Chris Craik905e8242013-06-05 09:59:05 -0700152 : mPixelRef(pixelRef), mSize(size) {
Chris Craik7e8c03c2013-06-03 13:53:36 -0700153 SkSafeRef(mPixelRef);
154 }
155
156 ~RecyclingPixelAllocator() {
157 SkSafeUnref(mPixelRef);
158 }
159
160 virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500161 const SkImageInfo& info = bitmap->info();
162 if (info.fColorType == kUnknown_SkColorType) {
163 ALOGW("unable to reuse a bitmap as the target has an unknown bitmap configuration");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700164 return false;
165 }
Chris Craikcd0ba712013-09-06 14:40:30 -0700166
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500167 const int64_t size64 = info.getSafeSize64(bitmap->rowBytes());
168 if (!sk_64_isS32(size64)) {
169 ALOGW("bitmap is too large");
170 return false;
171 }
172
173 const size_t size = sk_64_asS32(size64);
174 if (size > mSize) {
175 ALOGW("bitmap marked for reuse (%d bytes) can't fit new bitmap (%d bytes)",
176 mSize, size);
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500177 return false;
178 }
179
Chris Craikcd0ba712013-09-06 14:40:30 -0700180 // Create a new pixelref with the new ctable that wraps the previous pixelref
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500181 SkPixelRef* pr = new AndroidPixelRef(*static_cast<AndroidPixelRef*>(mPixelRef),
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500182 info, bitmap->rowBytes(), ctable);
Chris Craikcd0ba712013-09-06 14:40:30 -0700183
184 bitmap->setPixelRef(pr)->unref();
185 // since we're already allocated, we lockPixels right away
186 // HeapAllocator/JavaPixelAllocator behaves this way too
Chris Craik7e8c03c2013-06-03 13:53:36 -0700187 bitmap->lockPixels();
188 return true;
189 }
190
191private:
192 SkPixelRef* const mPixelRef;
193 const unsigned int mSize;
194};
195
Chris Craik47cd8e92014-07-08 17:13:08 -0700196static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 int sampleSize = 1;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700199
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400200 SkImageDecoder::Mode decodeMode = SkImageDecoder::kDecodePixels_Mode;
Mike Reed42a1d082014-07-07 18:06:18 -0400201 SkColorType prefColorType = kN32_SkColorType;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 bool doDither = true;
Romain Guy23610982011-01-17 12:51:55 -0800204 bool isMutable = false;
Chris Craik905e8242013-06-05 09:59:05 -0700205 float scale = 1.0f;
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800206 bool preferQualityOverSpeed = false;
Chris Craik1abf5d62013-08-16 12:47:03 -0700207 bool requireUnpremultiplied = false;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700208
Chet Haase37f74ca2010-12-08 17:56:36 -0800209 jobject javaBitmap = NULL;
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700210
Romain Guy7b2f8b82012-03-19 17:18:54 -0700211 if (options != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
Bryan Mawhinney2a3d7542010-11-03 17:23:57 +0000213 if (optionsJustBounds(env, options)) {
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400214 decodeMode = SkImageDecoder::kDecodeBounds_Mode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // initialize these, in case we fail later on
218 env->SetIntField(options, gOptions_widthFieldID, -1);
219 env->SetIntField(options, gOptions_heightFieldID, -1);
220 env->SetObjectField(options, gOptions_mimeFieldID, 0);
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
Mike Reed42a1d082014-07-07 18:06:18 -0400223 prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
Romain Guy23610982011-01-17 12:51:55 -0800224 isMutable = env->GetBooleanField(options, gOptions_mutableFieldID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800226 preferQualityOverSpeed = env->GetBooleanField(options,
227 gOptions_preferQualityOverSpeedFieldID);
Chris Craik1abf5d62013-08-16 12:47:03 -0700228 requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
Chet Haase37f74ca2010-12-08 17:56:36 -0800229 javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
Chris Craik905e8242013-06-05 09:59:05 -0700230
231 if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
232 const int density = env->GetIntField(options, gOptions_densityFieldID);
233 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
234 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
235 if (density != 0 && targetDensity != 0 && density != screenDensity) {
236 scale = (float) targetDensity / density;
237 }
238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
240
Chris Craik905e8242013-06-05 09:59:05 -0700241 const bool willScale = scale != 1.0f;
Romain Guy7b2f8b82012-03-19 17:18:54 -0700242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700244 if (decoder == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400245 return nullObjectReturn("SkImageDecoder::Factory returned null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 decoder->setSampleSize(sampleSize);
249 decoder->setDitherImage(doDither);
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800250 decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
Chris Craik1abf5d62013-08-16 12:47:03 -0700251 decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
Chris Craik7e8c03c2013-06-03 13:53:36 -0700253 SkBitmap* outputBitmap = NULL;
Chris Craik9f583612013-05-20 18:13:47 -0700254 unsigned int existingBufferSize = 0;
Chris Craik7e8c03c2013-06-03 13:53:36 -0700255 if (javaBitmap != NULL) {
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000256 outputBitmap = (SkBitmap*) env->GetLongField(javaBitmap, gBitmap_nativeBitmapFieldID);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700257 if (outputBitmap->isImmutable()) {
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400258 ALOGW("Unable to reuse an immutable bitmap as an image decoder target.");
Chris Craik7e8c03c2013-06-03 13:53:36 -0700259 javaBitmap = NULL;
260 outputBitmap = NULL;
261 } else {
262 existingBufferSize = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
Derek Sollenberger2a6ecae2012-08-31 14:03:51 -0400263 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265
Chris Craik7e8c03c2013-06-03 13:53:36 -0700266 SkAutoTDelete<SkBitmap> adb(outputBitmap == NULL ? new SkBitmap : NULL);
267 if (outputBitmap == NULL) outputBitmap = adb.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
Chris Craik7e8c03c2013-06-03 13:53:36 -0700269 NinePatchPeeker peeker(decoder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 decoder->setPeeker(&peeker);
Mike Reedc70e06b2009-04-24 11:09:12 -0400271
Chris Craik905e8242013-06-05 09:59:05 -0700272 JavaPixelAllocator javaAllocator(env);
273 RecyclingPixelAllocator recyclingAllocator(outputBitmap->pixelRef(), existingBufferSize);
274 ScaleCheckingAllocator scaleCheckingAllocator(scale, existingBufferSize);
275 SkBitmap::Allocator* outputAllocator = (javaBitmap != NULL) ?
276 (SkBitmap::Allocator*)&recyclingAllocator : (SkBitmap::Allocator*)&javaAllocator;
277 if (decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
278 if (!willScale) {
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400279 // If the java allocator is being used to allocate the pixel memory, the decoder
280 // need not write zeroes, since the memory is initialized to 0.
281 decoder->setSkipWritingZeroes(outputAllocator == &javaAllocator);
Chris Craik905e8242013-06-05 09:59:05 -0700282 decoder->setAllocator(outputAllocator);
283 } else if (javaBitmap != NULL) {
284 // check for eventual scaled bounds at allocation time, so we don't decode the bitmap
285 // only to find the scaled result too large to fit in the allocation
286 decoder->setAllocator(&scaleCheckingAllocator);
287 }
288 }
289
Derek Sollenberger6b0437c2013-06-24 15:40:54 -0400290 // Only setup the decoder to be deleted after its stack-based, refcounted
291 // components (allocators, peekers, etc) are declared. This prevents RefCnt
292 // asserts from firing due to the order objects are deleted from the stack.
293 SkAutoTDelete<SkImageDecoder> add(decoder);
294
295 AutoDecoderCancel adc(options, decoder);
296
297 // To fix the race condition in case "requestCancelDecode"
298 // happens earlier than AutoDecoderCancel object is added
299 // to the gAutoDecoderCancelMutex linked list.
300 if (options != NULL && env->GetBooleanField(options, gOptions_mCancelID)) {
301 return nullObjectReturn("gOptions_mCancelID");
302 }
303
Chris Craik7e8c03c2013-06-03 13:53:36 -0700304 SkBitmap decodingBitmap;
Mike Reed42a1d082014-07-07 18:06:18 -0400305 if (!decoder->decode(stream, &decodingBitmap, prefColorType, decodeMode)) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400306 return nullObjectReturn("decoder->decode returned false");
307 }
308
Chris Craik7e8c03c2013-06-03 13:53:36 -0700309 int scaledWidth = decodingBitmap.width();
310 int scaledHeight = decodingBitmap.height();
Romain Guy7b2f8b82012-03-19 17:18:54 -0700311
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400312 if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700313 scaledWidth = int(scaledWidth * scale + 0.5f);
314 scaledHeight = int(scaledHeight * scale + 0.5f);
315 }
316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 // update options (if any)
Romain Guy7b2f8b82012-03-19 17:18:54 -0700318 if (options != NULL) {
319 env->SetIntField(options, gOptions_widthFieldID, scaledWidth);
320 env->SetIntField(options, gOptions_heightFieldID, scaledHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 env->SetObjectField(options, gOptions_mimeFieldID,
Romain Guy7b2f8b82012-03-19 17:18:54 -0700322 getMimeTypeString(env, decoder->getFormat()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
Mike Reedc70e06b2009-04-24 11:09:12 -0400324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 // if we're in justBounds mode, return now (skip the java bitmap)
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400326 if (decodeMode == SkImageDecoder::kDecodeBounds_Mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 return NULL;
328 }
329
330 jbyteArray ninePatchChunk = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -0700331 if (peeker.mPatch != NULL) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700332 if (willScale) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700333 scaleNinePatchChunk(peeker.mPatch, scale);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700334 }
335
Chris Craik47cd8e92014-07-08 17:13:08 -0700336 size_t ninePatchArraySize = peeker.mPatch->serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700338 if (ninePatchChunk == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400339 return nullObjectReturn("ninePatchChunk == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700341
342 jbyte* array = (jbyte*) env->GetPrimitiveArrayCritical(ninePatchChunk, NULL);
343 if (array == NULL) {
Mike Reedc70e06b2009-04-24 11:09:12 -0400344 return nullObjectReturn("primitive array == null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700346
Chris Craik47cd8e92014-07-08 17:13:08 -0700347 memcpy(array, peeker.mPatch, peeker.mPatchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 env->ReleasePrimitiveArrayCritical(ninePatchChunk, array, 0);
349 }
350
Chris Craik47cd8e92014-07-08 17:13:08 -0700351 jobject ninePatchInsets = NULL;
352 if (peeker.mHasInsets) {
353 ninePatchInsets = env->NewObject(gInsetStruct_class, gInsetStruct_constructorMethodID,
354 peeker.mOpticalInsets[0], peeker.mOpticalInsets[1], peeker.mOpticalInsets[2], peeker.mOpticalInsets[3],
355 peeker.mOutlineInsets[0], peeker.mOutlineInsets[1], peeker.mOutlineInsets[2], peeker.mOutlineInsets[3],
356 peeker.mOutlineRadius, peeker.mOutlineFilled, scale);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700357 if (javaBitmap != NULL) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700358 env->SetObjectField(javaBitmap, gBitmap_ninePatchInsetsFieldID, ninePatchInsets);
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700359 }
360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361
Romain Guy7b2f8b82012-03-19 17:18:54 -0700362 if (willScale) {
363 // This is weird so let me explain: we could use the scale parameter
364 // directly, but for historical reasons this is how the corresponding
365 // Dalvik code has always behaved. We simply recreate the behavior here.
366 // The result is slightly different from simply using scale because of
367 // the 0.5f rounding bias applied when computing the target image size
Chris Craik7e8c03c2013-06-03 13:53:36 -0700368 const float sx = scaledWidth / float(decodingBitmap.width());
369 const float sy = scaledHeight / float(decodingBitmap.height());
Romain Guy7b2f8b82012-03-19 17:18:54 -0700370
Chris Craik905e8242013-06-05 09:59:05 -0700371 // TODO: avoid copying when scaled size equals decodingBitmap size
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500372 SkColorType colorType = colorTypeForScaledOutput(decodingBitmap.colorType());
Leon Scroggins III8790be62013-12-03 16:26:51 -0500373 // FIXME: If the alphaType is kUnpremul and the image has alpha, the
374 // colors may not be correct, since Skia does not yet support drawing
375 // to/from unpremultiplied bitmaps.
Mike Reedb9330552014-06-16 17:31:48 -0400376 outputBitmap->setInfo(SkImageInfo::Make(scaledWidth, scaledHeight,
Leon Scroggins46cb9bd2014-03-06 15:36:39 -0500377 colorType, decodingBitmap.alphaType()));
Chris Craik905e8242013-06-05 09:59:05 -0700378 if (!outputBitmap->allocPixels(outputAllocator, NULL)) {
Raph Levien005bfc62012-09-20 22:51:47 -0700379 return nullObjectReturn("allocation failed for scaled bitmap");
380 }
Leon Scroggins III1ffe7272013-09-19 11:34:06 -0400381
382 // If outputBitmap's pixels are newly allocated by Java, there is no need
383 // to erase to 0, since the pixels were initialized to 0.
384 if (outputAllocator != &javaAllocator) {
385 outputBitmap->eraseColor(0);
386 }
Romain Guy7b2f8b82012-03-19 17:18:54 -0700387
388 SkPaint paint;
Derek Sollenbergerb644a3b2014-01-17 15:45:10 -0500389 paint.setFilterLevel(SkPaint::kLow_FilterLevel);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700390
Chris Craik7e8c03c2013-06-03 13:53:36 -0700391 SkCanvas canvas(*outputBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700392 canvas.scale(sx, sy);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700393 canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
394 } else {
395 outputBitmap->swap(decodingBitmap);
Romain Guy7b2f8b82012-03-19 17:18:54 -0700396 }
397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 if (padding) {
Chris Craik47cd8e92014-07-08 17:13:08 -0700399 if (peeker.mPatch != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 GraphicsJNI::set_jrect(env, padding,
Chris Craik47cd8e92014-07-08 17:13:08 -0700401 peeker.mPatch->paddingLeft, peeker.mPatch->paddingTop,
402 peeker.mPatch->paddingRight, peeker.mPatch->paddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 } else {
404 GraphicsJNI::set_jrect(env, padding, -1, -1, -1, -1);
405 }
406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400408 // if we get here, we're in kDecodePixels_Mode and will therefore
409 // already have a pixelref installed.
410 if (outputBitmap->pixelRef() == NULL) {
Marco Nelissenb2fe3be2012-05-07 11:24:13 -0700411 return nullObjectReturn("Got null SkPixelRef");
412 }
Romain Guy23610982011-01-17 12:51:55 -0800413
Chris Craik7e8c03c2013-06-03 13:53:36 -0700414 if (!isMutable && javaBitmap == NULL) {
Romain Guy23610982011-01-17 12:51:55 -0800415 // promise we will never change our pixels (great for sharing and pictures)
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400416 outputBitmap->setImmutable();
Romain Guy23610982011-01-17 12:51:55 -0800417 }
Chet Haase37f74ca2010-12-08 17:56:36 -0800418
Jeff Brown27d83832012-05-09 17:30:31 -0700419 // detach bitmap from its autodeleter, since we want to own it now
420 adb.detach();
421
Chris Craik7e8c03c2013-06-03 13:53:36 -0700422 if (javaBitmap != NULL) {
Chris Craik1abf5d62013-08-16 12:47:03 -0700423 bool isPremultiplied = !requireUnpremultiplied;
424 GraphicsJNI::reinitBitmap(env, javaBitmap, outputBitmap, isPremultiplied);
Chris Craik7e8c03c2013-06-03 13:53:36 -0700425 outputBitmap->notifyPixelsChanged();
Chet Haase37f74ca2010-12-08 17:56:36 -0800426 // If a java bitmap was passed in for reuse, pass it back
427 return javaBitmap;
428 }
Chris Craik1abf5d62013-08-16 12:47:03 -0700429
430 int bitmapCreateFlags = 0x0;
431 if (isMutable) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
432 if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
433
Mike Reedc70e06b2009-04-24 11:09:12 -0400434 // now create the java bitmap
Chris Craik7e8c03c2013-06-03 13:53:36 -0700435 return GraphicsJNI::createBitmap(env, outputBitmap, javaAllocator.getStorageObj(),
Chris Craik47cd8e92014-07-08 17:13:08 -0700436 bitmapCreateFlags, ninePatchChunk, ninePatchInsets, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437}
438
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500439// Need to buffer enough input to be able to rewind as much as might be read by a decoder
440// trying to determine the stream's format. Currently the most is 64, read by
441// SkImageDecoder_libwebp.
442// FIXME: Get this number from SkImageDecoder
443#define BYTES_TO_BUFFER 64
444
Chris Craik905e8242013-06-05 09:59:05 -0700445static jobject nativeDecodeStream(JNIEnv* env, jobject clazz, jobject is, jbyteArray storage,
446 jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 jobject bitmap = NULL;
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400449 SkAutoTUnref<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450
Leon Scroggins IIIca320212013-08-20 17:59:39 -0400451 if (stream.get()) {
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500452 SkAutoTUnref<SkStreamRewindable> bufferedStream(
453 SkFrontBufferedStream::Create(stream, BYTES_TO_BUFFER));
Leon Scroggins III7315f1b2013-09-10 20:26:05 -0400454 SkASSERT(bufferedStream.get() != NULL);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400455 bitmap = doDecode(env, bufferedStream, padding, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 }
457 return bitmap;
458}
459
Romain Guy7b2f8b82012-03-19 17:18:54 -0700460static jobject nativeDecodeFileDescriptor(JNIEnv* env, jobject clazz, jobject fileDescriptor,
461 jobject padding, jobject bitmapFactoryOptions) {
462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
464
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700465 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Mike Reedc70e06b2009-04-24 11:09:12 -0400466
Derek Sollenberger5827cb52013-07-26 14:58:06 -0400467 struct stat fdStat;
468 if (fstat(descriptor, &fdStat) == -1) {
469 doThrowIOE(env, "broken file descriptor");
470 return nullObjectReturn("fstat return -1");
471 }
472
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500473 // Restore the descriptor's offset on exiting this function.
474 AutoFDSeek autoRestore(descriptor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500476 FILE* file = fdopen(descriptor, "r");
477 if (file == NULL) {
478 return nullObjectReturn("Could not open file");
Leon Scroggins IIIf65183f2013-10-07 16:32:14 -0400479 }
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500480
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500481 SkAutoTUnref<SkFILEStream> fileStream(new SkFILEStream(file,
Leon Scroggins III0102f8a2014-01-14 15:14:57 -0500482 SkFILEStream::kCallerRetains_Ownership));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400484 // Use a buffered stream. Although an SkFILEStream can be rewound, this
485 // ensures that SkImageDecoder::Factory never rewinds beyond the
486 // current position of the file descriptor.
487 SkAutoTUnref<SkStreamRewindable> stream(SkFrontBufferedStream::Create(fileStream,
488 BYTES_TO_BUFFER));
Leon Scroggins III2826e5f2014-02-05 19:46:02 -0500489
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400490 return doDecode(env, stream, padding, bitmapFactoryOptions);
Mike Reedc70e06b2009-04-24 11:09:12 -0400491}
492
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000493static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Chris Craik905e8242013-06-05 09:59:05 -0700494 jobject padding, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700495
Mike Reedc70e06b2009-04-24 11:09:12 -0400496 Asset* asset = reinterpret_cast<Asset*>(native_asset);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400497 // since we know we'll be done with the asset when we return, we can
498 // just use a simple wrapper
499 SkAutoTUnref<SkStreamRewindable> stream(new AssetStreamAdaptor(asset,
500 AssetStreamAdaptor::kNo_OwnAsset, AssetStreamAdaptor::kNo_HasMemoryBase));
501 return doDecode(env, stream, padding, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502}
503
504static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000505 jint offset, jint length, jobject options) {
Romain Guy7b2f8b82012-03-19 17:18:54 -0700506
Mike Reedc70e06b2009-04-24 11:09:12 -0400507 AutoJavaByteArray ar(env, byteArray);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400508 SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, false);
Mike Reedc70e06b2009-04-24 11:09:12 -0400509 SkAutoUnref aur(stream);
Leon Scroggins III0aa39dc2014-06-03 12:19:32 -0400510 return doDecode(env, stream, NULL, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511}
512
513static void nativeRequestCancel(JNIEnv*, jobject joptions) {
514 (void)AutoDecoderCancel::RequestCancel(joptions);
515}
516
Owen Lina9d0d472011-01-18 17:39:15 +0800517static jboolean nativeIsSeekable(JNIEnv* env, jobject, jobject fileDescriptor) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700518 jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
Owen Lina9d0d472011-01-18 17:39:15 +0800519 return ::lseek64(descriptor, 0, SEEK_CUR) != -1 ? JNI_TRUE : JNI_FALSE;
520}
521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522///////////////////////////////////////////////////////////////////////////////
523
524static JNINativeMethod gMethods[] = {
525 { "nativeDecodeStream",
526 "(Ljava/io/InputStream;[BLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
527 (void*)nativeDecodeStream
528 },
529
530 { "nativeDecodeFileDescriptor",
531 "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
532 (void*)nativeDecodeFileDescriptor
533 },
534
535 { "nativeDecodeAsset",
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000536 "(JLandroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 (void*)nativeDecodeAsset
538 },
539
540 { "nativeDecodeByteArray",
541 "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
542 (void*)nativeDecodeByteArray
543 },
544
Owen Lina9d0d472011-01-18 17:39:15 +0800545 { "nativeIsSeekable",
546 "(Ljava/io/FileDescriptor;)Z",
547 (void*)nativeIsSeekable
548 },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549};
550
551static JNINativeMethod gOptionsMethods[] = {
552 { "requestCancel", "()V", (void*)nativeRequestCancel }
553};
554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
556 const char fieldname[], const char type[]) {
557 jfieldID id = env->GetFieldID(clazz, fieldname, type);
558 SkASSERT(id);
559 return id;
560}
561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562int register_android_graphics_BitmapFactory(JNIEnv* env) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700563 jclass options_class = env->FindClass("android/graphics/BitmapFactory$Options");
564 SkASSERT(options_class);
565 gOptions_bitmapFieldID = getFieldIDCheck(env, options_class, "inBitmap",
Chris Craik47cd8e92014-07-08 17:13:08 -0700566 "Landroid/graphics/Bitmap;");
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700567 gOptions_justBoundsFieldID = getFieldIDCheck(env, options_class, "inJustDecodeBounds", "Z");
568 gOptions_sampleSizeFieldID = getFieldIDCheck(env, options_class, "inSampleSize", "I");
569 gOptions_configFieldID = getFieldIDCheck(env, options_class, "inPreferredConfig",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 "Landroid/graphics/Bitmap$Config;");
Chris Craik1abf5d62013-08-16 12:47:03 -0700571 gOptions_premultipliedFieldID = getFieldIDCheck(env, options_class, "inPremultiplied", "Z");
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700572 gOptions_mutableFieldID = getFieldIDCheck(env, options_class, "inMutable", "Z");
573 gOptions_ditherFieldID = getFieldIDCheck(env, options_class, "inDither", "Z");
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700574 gOptions_preferQualityOverSpeedFieldID = getFieldIDCheck(env, options_class,
Wei-Ta Chen953f9092010-12-03 14:06:18 -0800575 "inPreferQualityOverSpeed", "Z");
Chris Craik905e8242013-06-05 09:59:05 -0700576 gOptions_scaledFieldID = getFieldIDCheck(env, options_class, "inScaled", "Z");
577 gOptions_densityFieldID = getFieldIDCheck(env, options_class, "inDensity", "I");
578 gOptions_screenDensityFieldID = getFieldIDCheck(env, options_class, "inScreenDensity", "I");
579 gOptions_targetDensityFieldID = getFieldIDCheck(env, options_class, "inTargetDensity", "I");
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700580 gOptions_widthFieldID = getFieldIDCheck(env, options_class, "outWidth", "I");
581 gOptions_heightFieldID = getFieldIDCheck(env, options_class, "outHeight", "I");
582 gOptions_mimeFieldID = getFieldIDCheck(env, options_class, "outMimeType", "Ljava/lang/String;");
583 gOptions_mCancelID = getFieldIDCheck(env, options_class, "mCancel", "Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700585 jclass bitmap_class = env->FindClass("android/graphics/Bitmap");
586 SkASSERT(bitmap_class);
Ashok Bhat36bef0b2014-01-20 20:08:01 +0000587 gBitmap_nativeBitmapFieldID = getFieldIDCheck(env, bitmap_class, "mNativeBitmap", "J");
Chris Craik47cd8e92014-07-08 17:13:08 -0700588 gBitmap_ninePatchInsetsFieldID = getFieldIDCheck(env, bitmap_class, "mNinePatchInsets",
589 "Landroid/graphics/NinePatch$InsetStruct;");
590
591 gInsetStruct_class = (jclass) env->NewGlobalRef(env->FindClass("android/graphics/NinePatch$InsetStruct"));
592 gInsetStruct_constructorMethodID = env->GetMethodID(gInsetStruct_class, "<init>", "(IIIIIIIIFZF)V");
593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 int ret = AndroidRuntime::registerNativeMethods(env,
595 "android/graphics/BitmapFactory$Options",
596 gOptionsMethods,
597 SK_ARRAY_COUNT(gOptionsMethods));
598 if (ret) {
599 return ret;
600 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -0700601 return android::AndroidRuntime::registerNativeMethods(env, "android/graphics/BitmapFactory",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 gMethods, SK_ARRAY_COUNT(gMethods));
603}