1 // #define LOG_NDEBUG 0
2 #include "Bitmap.h"
3
4 #include <android-base/unique_fd.h>
5 #include <hwui/Bitmap.h>
6 #include <hwui/Paint.h>
7 #include <inttypes.h>
8 #include <renderthread/RenderProxy.h>
9 #include <string.h>
10
11 #include <memory>
12
13 #include "CreateJavaOutputStreamAdaptor.h"
14 #include "Gainmap.h"
15 #include "GraphicsJNI.h"
16 #include "HardwareBufferHelpers.h"
17 #include "ScopedParcel.h"
18 #include "SkBitmap.h"
19 #include "SkBlendMode.h"
20 #include "SkCanvas.h"
21 #include "SkColor.h"
22 #include "SkColorSpace.h"
23 #include "SkData.h"
24 #include "SkImageInfo.h"
25 #include "SkPaint.h"
26 #include "SkPixmap.h"
27 #include "SkPoint.h"
28 #include "SkRefCnt.h"
29 #include "SkStream.h"
30 #include "SkTypes.h"
31 #include "android_nio_utils.h"
32
33 #define DEBUG_PARCEL 0
34
35 static jclass gBitmap_class;
36 static jfieldID gBitmap_nativePtr;
37 static jmethodID gBitmap_constructorMethodID;
38 static jmethodID gBitmap_reinitMethodID;
39
40 namespace android {
41
42 jobject Gainmap_extractFromBitmap(JNIEnv* env, const Bitmap& bitmap);
43
44 class BitmapWrapper {
45 public:
BitmapWrapper(Bitmap * bitmap)46 explicit BitmapWrapper(Bitmap* bitmap)
47 : mBitmap(bitmap) { }
48
freePixels()49 void freePixels() {
50 mInfo = mBitmap->info();
51 mHasHardwareMipMap = mBitmap->hasHardwareMipMap();
52 mAllocationSize = mBitmap->getAllocationByteCount();
53 mRowBytes = mBitmap->rowBytes();
54 mGenerationId = mBitmap->getGenerationID();
55 mIsHardware = mBitmap->isHardware();
56 mBitmap.reset();
57 }
58
valid()59 bool valid() {
60 return mBitmap != nullptr;
61 }
62
bitmap()63 Bitmap& bitmap() {
64 assertValid();
65 return *mBitmap;
66 }
67
assertValid()68 void assertValid() {
69 LOG_ALWAYS_FATAL_IF(!valid(), "Error, cannot access an invalid/free'd bitmap here!");
70 }
71
getSkBitmap(SkBitmap * outBitmap)72 void getSkBitmap(SkBitmap* outBitmap) {
73 assertValid();
74 mBitmap->getSkBitmap(outBitmap);
75 }
76
hasHardwareMipMap()77 bool hasHardwareMipMap() {
78 if (mBitmap) {
79 return mBitmap->hasHardwareMipMap();
80 }
81 return mHasHardwareMipMap;
82 }
83
setHasHardwareMipMap(bool hasMipMap)84 void setHasHardwareMipMap(bool hasMipMap) {
85 assertValid();
86 mBitmap->setHasHardwareMipMap(hasMipMap);
87 }
88
setAlphaType(SkAlphaType alphaType)89 void setAlphaType(SkAlphaType alphaType) {
90 assertValid();
91 mBitmap->setAlphaType(alphaType);
92 }
93
setColorSpace(sk_sp<SkColorSpace> colorSpace)94 void setColorSpace(sk_sp<SkColorSpace> colorSpace) {
95 assertValid();
96 mBitmap->setColorSpace(colorSpace);
97 }
98
info()99 const SkImageInfo& info() {
100 if (mBitmap) {
101 return mBitmap->info();
102 }
103 return mInfo;
104 }
105
getAllocationByteCount() const106 size_t getAllocationByteCount() const {
107 if (mBitmap) {
108 return mBitmap->getAllocationByteCount();
109 }
110 return mAllocationSize;
111 }
112
rowBytes() const113 size_t rowBytes() const {
114 if (mBitmap) {
115 return mBitmap->rowBytes();
116 }
117 return mRowBytes;
118 }
119
getGenerationID() const120 uint32_t getGenerationID() const {
121 if (mBitmap) {
122 return mBitmap->getGenerationID();
123 }
124 return mGenerationId;
125 }
126
isHardware()127 bool isHardware() {
128 if (mBitmap) {
129 return mBitmap->isHardware();
130 }
131 return mIsHardware;
132 }
133
~BitmapWrapper()134 ~BitmapWrapper() { }
135
136 private:
137 sk_sp<Bitmap> mBitmap;
138 SkImageInfo mInfo;
139 bool mHasHardwareMipMap;
140 size_t mAllocationSize;
141 size_t mRowBytes;
142 uint32_t mGenerationId;
143 bool mIsHardware;
144 };
145
146 // Convenience class that does not take a global ref on the pixels, relying
147 // on the caller already having a local JNI ref
148 class LocalScopedBitmap {
149 public:
LocalScopedBitmap(jlong bitmapHandle)150 explicit LocalScopedBitmap(jlong bitmapHandle)
151 : mBitmapWrapper(reinterpret_cast<BitmapWrapper*>(bitmapHandle)) {}
152
operator ->()153 BitmapWrapper* operator->() {
154 return mBitmapWrapper;
155 }
156
pixels()157 void* pixels() {
158 return mBitmapWrapper->bitmap().pixels();
159 }
160
valid()161 bool valid() {
162 return mBitmapWrapper && mBitmapWrapper->valid();
163 }
164
165 private:
166 BitmapWrapper* mBitmapWrapper;
167 };
168
169 namespace bitmap {
170
171 // Assert that bitmap's SkAlphaType is consistent with isPremultiplied.
assert_premultiplied(const SkImageInfo & info,bool isPremultiplied)172 static void assert_premultiplied(const SkImageInfo& info, bool isPremultiplied) {
173 // kOpaque_SkAlphaType and kIgnore_SkAlphaType mean that isPremultiplied is
174 // irrelevant. This just tests to ensure that the SkAlphaType is not
175 // opposite of isPremultiplied.
176 if (isPremultiplied) {
177 SkASSERT(info.alphaType() != kUnpremul_SkAlphaType);
178 } else {
179 SkASSERT(info.alphaType() != kPremul_SkAlphaType);
180 }
181 }
182
reinitBitmap(JNIEnv * env,jobject javaBitmap,const SkImageInfo & info,bool isPremultiplied)183 void reinitBitmap(JNIEnv* env, jobject javaBitmap, const SkImageInfo& info,
184 bool isPremultiplied)
185 {
186 // The caller needs to have already set the alpha type properly, so the
187 // native SkBitmap stays in sync with the Java Bitmap.
188 assert_premultiplied(info, isPremultiplied);
189
190 env->CallVoidMethod(javaBitmap, gBitmap_reinitMethodID,
191 info.width(), info.height(), isPremultiplied);
192 }
193
createBitmap(JNIEnv * env,Bitmap * bitmap,int bitmapCreateFlags,jbyteArray ninePatchChunk,jobject ninePatchInsets,int density)194 jobject createBitmap(JNIEnv* env, Bitmap* bitmap,
195 int bitmapCreateFlags, jbyteArray ninePatchChunk, jobject ninePatchInsets,
196 int density) {
197 bool isMutable = bitmapCreateFlags & kBitmapCreateFlag_Mutable;
198 bool isPremultiplied = bitmapCreateFlags & kBitmapCreateFlag_Premultiplied;
199 // The caller needs to have already set the alpha type properly, so the
200 // native SkBitmap stays in sync with the Java Bitmap.
201 assert_premultiplied(bitmap->info(), isPremultiplied);
202 bool fromMalloc = bitmap->pixelStorageType() == PixelStorageType::Heap;
203 BitmapWrapper* bitmapWrapper = new BitmapWrapper(bitmap);
204 if (!isMutable) {
205 bitmapWrapper->bitmap().setImmutable();
206 }
207 jobject obj = env->NewObject(gBitmap_class, gBitmap_constructorMethodID,
208 reinterpret_cast<jlong>(bitmapWrapper), bitmap->width(), bitmap->height(), density,
209 isPremultiplied, ninePatchChunk, ninePatchInsets, fromMalloc);
210
211 if (env->ExceptionCheck() != 0) {
212 ALOGE("*** Uncaught exception returned from Java call!\n");
213 env->ExceptionDescribe();
214 }
215 return obj;
216 }
217
toSkBitmap(jlong bitmapHandle,SkBitmap * outBitmap)218 void toSkBitmap(jlong bitmapHandle, SkBitmap* outBitmap) {
219 LocalScopedBitmap bitmap(bitmapHandle);
220 bitmap->getSkBitmap(outBitmap);
221 }
222
toBitmap(jlong bitmapHandle)223 Bitmap& toBitmap(jlong bitmapHandle) {
224 LocalScopedBitmap localBitmap(bitmapHandle);
225 return localBitmap->bitmap();
226 }
227
228 } // namespace bitmap
229
230 } // namespace android
231
232 using namespace android;
233 using namespace android::bitmap;
234
getNativeBitmap(JNIEnv * env,jobject bitmap)235 Bitmap* GraphicsJNI::getNativeBitmap(JNIEnv* env, jobject bitmap) {
236 SkASSERT(env);
237 SkASSERT(bitmap);
238 SkASSERT(env->IsInstanceOf(bitmap, gBitmap_class));
239 jlong bitmapHandle = env->GetLongField(bitmap, gBitmap_nativePtr);
240 LocalScopedBitmap localBitmap(bitmapHandle);
241 return localBitmap.valid() ? &localBitmap->bitmap() : nullptr;
242 }
243
getBitmapInfo(JNIEnv * env,jobject bitmap,uint32_t * outRowBytes,bool * isHardware)244 SkImageInfo GraphicsJNI::getBitmapInfo(JNIEnv* env, jobject bitmap, uint32_t* outRowBytes,
245 bool* isHardware) {
246 SkASSERT(env);
247 SkASSERT(bitmap);
248 SkASSERT(env->IsInstanceOf(bitmap, gBitmap_class));
249 jlong bitmapHandle = env->GetLongField(bitmap, gBitmap_nativePtr);
250 LocalScopedBitmap localBitmap(bitmapHandle);
251 if (outRowBytes) {
252 *outRowBytes = localBitmap->rowBytes();
253 }
254 if (isHardware) {
255 *isHardware = localBitmap->isHardware();
256 }
257 return localBitmap->info();
258 }
259
SetPixels(JNIEnv * env,jintArray srcColors,int srcOffset,int srcStride,int x,int y,int width,int height,SkBitmap * dstBitmap)260 bool GraphicsJNI::SetPixels(JNIEnv* env, jintArray srcColors, int srcOffset, int srcStride,
261 int x, int y, int width, int height, SkBitmap* dstBitmap) {
262 const jint* array = env->GetIntArrayElements(srcColors, NULL);
263 const SkColor* src = (const SkColor*)array + srcOffset;
264
265 auto sRGB = SkColorSpace::MakeSRGB();
266 SkImageInfo srcInfo = SkImageInfo::Make(
267 width, height, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType, sRGB);
268 SkPixmap srcPM(srcInfo, src, srcStride * 4);
269
270 dstBitmap->writePixels(srcPM, x, y);
271
272 env->ReleaseIntArrayElements(srcColors, const_cast<jint*>(array), JNI_ABORT);
273 return true;
274 }
275
276 ///////////////////////////////////////////////////////////////////////////////
277 ///////////////////////////////////////////////////////////////////////////////
278
getPremulBitmapCreateFlags(bool isMutable)279 static int getPremulBitmapCreateFlags(bool isMutable) {
280 int flags = android::bitmap::kBitmapCreateFlag_Premultiplied;
281 if (isMutable) flags |= android::bitmap::kBitmapCreateFlag_Mutable;
282 return flags;
283 }
284
Bitmap_creator(JNIEnv * env,jobject,jintArray jColors,jint offset,jint stride,jint width,jint height,jint configHandle,jboolean isMutable,jlong colorSpacePtr)285 static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
286 jint offset, jint stride, jint width, jint height,
287 jint configHandle, jboolean isMutable,
288 jlong colorSpacePtr) {
289 SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
290 if (NULL != jColors) {
291 size_t n = env->GetArrayLength(jColors);
292 if (n < SkAbs32(stride) * (size_t)height) {
293 doThrowAIOOBE(env);
294 return NULL;
295 }
296 }
297
298 // ARGB_4444 is a deprecated format, convert automatically to 8888
299 if (colorType == kARGB_4444_SkColorType) {
300 colorType = kN32_SkColorType;
301 }
302
303 sk_sp<SkColorSpace> colorSpace;
304 if (colorType == kAlpha_8_SkColorType) {
305 colorSpace = nullptr;
306 } else {
307 colorSpace = GraphicsJNI::getNativeColorSpace(colorSpacePtr);
308 }
309
310 SkBitmap bitmap;
311 bitmap.setInfo(SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType,
312 colorSpace));
313
314 sk_sp<Bitmap> nativeBitmap = Bitmap::allocateHeapBitmap(&bitmap);
315 if (!nativeBitmap) {
316 ALOGE("OOM allocating Bitmap with dimensions %i x %i", width, height);
317 doThrowOOME(env);
318 return NULL;
319 }
320
321 if (jColors != NULL) {
322 GraphicsJNI::SetPixels(env, jColors, offset, stride, 0, 0, width, height, &bitmap);
323 }
324
325 return createBitmap(env, nativeBitmap.release(), getPremulBitmapCreateFlags(isMutable));
326 }
327
bitmapCopyTo(SkBitmap * dst,SkColorType dstCT,const SkBitmap & src,SkBitmap::Allocator * alloc)328 static bool bitmapCopyTo(SkBitmap* dst, SkColorType dstCT, const SkBitmap& src,
329 SkBitmap::Allocator* alloc) {
330 SkPixmap srcPM;
331 if (!src.peekPixels(&srcPM)) {
332 return false;
333 }
334
335 SkImageInfo dstInfo = srcPM.info().makeColorType(dstCT);
336 switch (dstCT) {
337 case kRGB_565_SkColorType:
338 dstInfo = dstInfo.makeAlphaType(kOpaque_SkAlphaType);
339 break;
340 case kAlpha_8_SkColorType:
341 dstInfo = dstInfo.makeColorSpace(nullptr);
342 break;
343 default:
344 break;
345 }
346
347 if (!dstInfo.colorSpace() && dstCT != kAlpha_8_SkColorType) {
348 dstInfo = dstInfo.makeColorSpace(SkColorSpace::MakeSRGB());
349 }
350
351 if (!dst->setInfo(dstInfo)) {
352 return false;
353 }
354 if (!dst->tryAllocPixels(alloc)) {
355 return false;
356 }
357
358 SkPixmap dstPM;
359 if (!dst->peekPixels(&dstPM)) {
360 return false;
361 }
362
363 return srcPM.readPixels(dstPM);
364 }
365
Bitmap_copy(JNIEnv * env,jobject,jlong srcHandle,jint dstConfigHandle,jboolean isMutable)366 static jobject Bitmap_copy(JNIEnv* env, jobject, jlong srcHandle, jint dstConfigHandle,
367 jboolean isMutable) {
368 LocalScopedBitmap bitmapHolder(srcHandle);
369 if (!bitmapHolder.valid()) {
370 return NULL;
371 }
372 const Bitmap& original = bitmapHolder->bitmap();
373 const bool hasGainmap = original.hasGainmap();
374 SkBitmap src;
375 bitmapHolder->getSkBitmap(&src);
376
377 if (dstConfigHandle == GraphicsJNI::hardwareLegacyBitmapConfig()) {
378 sk_sp<Bitmap> bitmap(Bitmap::allocateHardwareBitmap(src));
379 if (!bitmap.get()) {
380 return NULL;
381 }
382 if (hasGainmap) {
383 auto gm = uirenderer::Gainmap::allocateHardwareGainmap(original.gainmap());
384 if (gm) {
385 bitmap->setGainmap(std::move(gm));
386 }
387 }
388 return createBitmap(env, bitmap.release(), getPremulBitmapCreateFlags(isMutable));
389 }
390
391 SkColorType dstCT = GraphicsJNI::legacyBitmapConfigToColorType(dstConfigHandle);
392 SkBitmap result;
393 HeapAllocator allocator;
394
395 if (!bitmapCopyTo(&result, dstCT, src, &allocator)) {
396 return NULL;
397 }
398 auto bitmap = allocator.getStorageObjAndReset();
399 if (hasGainmap) {
400 auto gainmap = sp<uirenderer::Gainmap>::make();
401 gainmap->info = original.gainmap()->info;
402 const SkBitmap skSrcBitmap = original.gainmap()->bitmap->getSkBitmap();
403 SkBitmap skDestBitmap;
404 HeapAllocator destAllocator;
405 if (!bitmapCopyTo(&skDestBitmap, dstCT, skSrcBitmap, &destAllocator)) {
406 return NULL;
407 }
408 gainmap->bitmap = sk_sp<Bitmap>(destAllocator.getStorageObjAndReset());
409 bitmap->setGainmap(std::move(gainmap));
410 }
411 return createBitmap(env, bitmap, getPremulBitmapCreateFlags(isMutable));
412 }
413
Bitmap_copyAshmemImpl(JNIEnv * env,SkBitmap & src,SkColorType & dstCT)414 static Bitmap* Bitmap_copyAshmemImpl(JNIEnv* env, SkBitmap& src, SkColorType& dstCT) {
415 SkBitmap result;
416
417 AshmemPixelAllocator allocator(env);
418 if (!bitmapCopyTo(&result, dstCT, src, &allocator)) {
419 return NULL;
420 }
421 auto bitmap = allocator.getStorageObjAndReset();
422 bitmap->setImmutable();
423 return bitmap;
424 }
425
Bitmap_copyAshmem(JNIEnv * env,jobject,jlong srcHandle)426 static jobject Bitmap_copyAshmem(JNIEnv* env, jobject, jlong srcHandle) {
427 SkBitmap src;
428 reinterpret_cast<BitmapWrapper*>(srcHandle)->getSkBitmap(&src);
429 SkColorType dstCT = src.colorType();
430 auto bitmap = Bitmap_copyAshmemImpl(env, src, dstCT);
431 jobject ret = createBitmap(env, bitmap, getPremulBitmapCreateFlags(false));
432 return ret;
433 }
434
Bitmap_copyAshmemConfig(JNIEnv * env,jobject,jlong srcHandle,jint dstConfigHandle)435 static jobject Bitmap_copyAshmemConfig(JNIEnv* env, jobject, jlong srcHandle, jint dstConfigHandle) {
436 SkBitmap src;
437 reinterpret_cast<BitmapWrapper*>(srcHandle)->getSkBitmap(&src);
438 SkColorType dstCT = GraphicsJNI::legacyBitmapConfigToColorType(dstConfigHandle);
439 auto bitmap = Bitmap_copyAshmemImpl(env, src, dstCT);
440 jobject ret = createBitmap(env, bitmap, getPremulBitmapCreateFlags(false));
441 return ret;
442 }
443
Bitmap_getAshmemFd(JNIEnv * env,jobject,jlong bitmapHandle)444 static jint Bitmap_getAshmemFd(JNIEnv* env, jobject, jlong bitmapHandle) {
445 LocalScopedBitmap bitmap(bitmapHandle);
446 return (bitmap.valid()) ? bitmap->bitmap().getAshmemFd() : -1;
447 }
448
Bitmap_destruct(BitmapWrapper * bitmap)449 static void Bitmap_destruct(BitmapWrapper* bitmap) {
450 delete bitmap;
451 }
452
Bitmap_getNativeFinalizer(JNIEnv *,jobject)453 static jlong Bitmap_getNativeFinalizer(JNIEnv*, jobject) {
454 return static_cast<jlong>(reinterpret_cast<uintptr_t>(&Bitmap_destruct));
455 }
456
Bitmap_recycle(JNIEnv * env,jobject,jlong bitmapHandle)457 static void Bitmap_recycle(JNIEnv* env, jobject, jlong bitmapHandle) {
458 LocalScopedBitmap bitmap(bitmapHandle);
459 bitmap->freePixels();
460 }
461
Bitmap_reconfigure(JNIEnv * env,jobject clazz,jlong bitmapHandle,jint width,jint height,jint configHandle,jboolean requestPremul)462 static void Bitmap_reconfigure(JNIEnv* env, jobject clazz, jlong bitmapHandle,
463 jint width, jint height, jint configHandle, jboolean requestPremul) {
464 LocalScopedBitmap bitmap(bitmapHandle);
465 bitmap->assertValid();
466 SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
467
468 // ARGB_4444 is a deprecated format, convert automatically to 8888
469 if (colorType == kARGB_4444_SkColorType) {
470 colorType = kN32_SkColorType;
471 }
472 size_t requestedSize = width * height * SkColorTypeBytesPerPixel(colorType);
473 if (requestedSize > bitmap->getAllocationByteCount()) {
474 // done in native as there's no way to get BytesPerPixel in Java
475 doThrowIAE(env, "Bitmap not large enough to support new configuration");
476 return;
477 }
478 SkAlphaType alphaType;
479 if (bitmap->info().colorType() != kRGB_565_SkColorType
480 && bitmap->info().alphaType() == kOpaque_SkAlphaType) {
481 // If the original bitmap was set to opaque, keep that setting, unless it
482 // was 565, which is required to be opaque.
483 alphaType = kOpaque_SkAlphaType;
484 } else {
485 // Otherwise respect the premultiplied request.
486 alphaType = requestPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
487 }
488 bitmap->bitmap().reconfigure(SkImageInfo::Make(width, height, colorType, alphaType,
489 sk_ref_sp(bitmap->info().colorSpace())));
490 }
491
Bitmap_compress(JNIEnv * env,jobject clazz,jlong bitmapHandle,jint format,jint quality,jobject jstream,jbyteArray jstorage)492 static jboolean Bitmap_compress(JNIEnv* env, jobject clazz, jlong bitmapHandle,
493 jint format, jint quality,
494 jobject jstream, jbyteArray jstorage) {
495 LocalScopedBitmap bitmap(bitmapHandle);
496 if (!bitmap.valid()) {
497 return JNI_FALSE;
498 }
499
500 std::unique_ptr<SkWStream> strm(CreateJavaOutputStreamAdaptor(env, jstream, jstorage));
501 if (!strm.get()) {
502 return JNI_FALSE;
503 }
504
505 auto fm = static_cast<Bitmap::JavaCompressFormat>(format);
506 return bitmap->bitmap().compress(fm, quality, strm.get()) ? JNI_TRUE : JNI_FALSE;
507 }
508
bitmapErase(SkBitmap bitmap,const SkColor4f & color,const sk_sp<SkColorSpace> & colorSpace)509 static inline void bitmapErase(SkBitmap bitmap, const SkColor4f& color,
510 const sk_sp<SkColorSpace>& colorSpace) {
511 SkPaint p;
512 p.setColor4f(color, colorSpace.get());
513 p.setBlendMode(SkBlendMode::kSrc);
514 SkCanvas canvas(bitmap);
515 canvas.drawPaint(p);
516 }
517
Bitmap_erase(JNIEnv * env,jobject,jlong bitmapHandle,jint color)518 static void Bitmap_erase(JNIEnv* env, jobject, jlong bitmapHandle, jint color) {
519 LocalScopedBitmap bitmap(bitmapHandle);
520 SkBitmap skBitmap;
521 bitmap->getSkBitmap(&skBitmap);
522 bitmapErase(skBitmap, SkColor4f::FromColor(color), SkColorSpace::MakeSRGB());
523 }
524
Bitmap_eraseLong(JNIEnv * env,jobject,jlong bitmapHandle,jlong colorSpaceHandle,jlong colorLong)525 static void Bitmap_eraseLong(JNIEnv* env, jobject, jlong bitmapHandle,
526 jlong colorSpaceHandle, jlong colorLong) {
527 LocalScopedBitmap bitmap(bitmapHandle);
528 SkBitmap skBitmap;
529 bitmap->getSkBitmap(&skBitmap);
530
531 SkColor4f color = GraphicsJNI::convertColorLong(colorLong);
532 sk_sp<SkColorSpace> cs = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
533 bitmapErase(skBitmap, color, cs);
534 }
535
Bitmap_rowBytes(JNIEnv * env,jobject,jlong bitmapHandle)536 static jint Bitmap_rowBytes(JNIEnv* env, jobject, jlong bitmapHandle) {
537 LocalScopedBitmap bitmap(bitmapHandle);
538 return static_cast<jint>(bitmap->rowBytes());
539 }
540
Bitmap_config(JNIEnv * env,jobject,jlong bitmapHandle)541 static jint Bitmap_config(JNIEnv* env, jobject, jlong bitmapHandle) {
542 LocalScopedBitmap bitmap(bitmapHandle);
543 if (bitmap->isHardware()) {
544 return GraphicsJNI::hardwareLegacyBitmapConfig();
545 }
546 return GraphicsJNI::colorTypeToLegacyBitmapConfig(bitmap->info().colorType());
547 }
548
Bitmap_getGenerationId(JNIEnv * env,jobject,jlong bitmapHandle)549 static jint Bitmap_getGenerationId(JNIEnv* env, jobject, jlong bitmapHandle) {
550 LocalScopedBitmap bitmap(bitmapHandle);
551 return static_cast<jint>(bitmap->getGenerationID());
552 }
553
Bitmap_isPremultiplied(JNIEnv * env,jobject,jlong bitmapHandle)554 static jboolean Bitmap_isPremultiplied(JNIEnv* env, jobject, jlong bitmapHandle) {
555 LocalScopedBitmap bitmap(bitmapHandle);
556 if (bitmap->info().alphaType() == kPremul_SkAlphaType) {
557 return JNI_TRUE;
558 }
559 return JNI_FALSE;
560 }
561
Bitmap_hasAlpha(JNIEnv * env,jobject,jlong bitmapHandle)562 static jboolean Bitmap_hasAlpha(JNIEnv* env, jobject, jlong bitmapHandle) {
563 LocalScopedBitmap bitmap(bitmapHandle);
564 return !bitmap->info().isOpaque() ? JNI_TRUE : JNI_FALSE;
565 }
566
Bitmap_setHasAlpha(JNIEnv * env,jobject,jlong bitmapHandle,jboolean hasAlpha,jboolean requestPremul)567 static void Bitmap_setHasAlpha(JNIEnv* env, jobject, jlong bitmapHandle,
568 jboolean hasAlpha, jboolean requestPremul) {
569 LocalScopedBitmap bitmap(bitmapHandle);
570 if (hasAlpha) {
571 bitmap->setAlphaType(
572 requestPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType);
573 } else {
574 bitmap->setAlphaType(kOpaque_SkAlphaType);
575 }
576 }
577
Bitmap_setPremultiplied(JNIEnv * env,jobject,jlong bitmapHandle,jboolean isPremul)578 static void Bitmap_setPremultiplied(JNIEnv* env, jobject, jlong bitmapHandle,
579 jboolean isPremul) {
580 LocalScopedBitmap bitmap(bitmapHandle);
581 if (!bitmap->info().isOpaque()) {
582 if (isPremul) {
583 bitmap->setAlphaType(kPremul_SkAlphaType);
584 } else {
585 bitmap->setAlphaType(kUnpremul_SkAlphaType);
586 }
587 }
588 }
589
Bitmap_hasMipMap(JNIEnv * env,jobject,jlong bitmapHandle)590 static jboolean Bitmap_hasMipMap(JNIEnv* env, jobject, jlong bitmapHandle) {
591 LocalScopedBitmap bitmap(bitmapHandle);
592 return bitmap->hasHardwareMipMap() ? JNI_TRUE : JNI_FALSE;
593 }
594
Bitmap_setHasMipMap(JNIEnv * env,jobject,jlong bitmapHandle,jboolean hasMipMap)595 static void Bitmap_setHasMipMap(JNIEnv* env, jobject, jlong bitmapHandle,
596 jboolean hasMipMap) {
597 LocalScopedBitmap bitmap(bitmapHandle);
598 bitmap->setHasHardwareMipMap(hasMipMap);
599 }
600
601 ///////////////////////////////////////////////////////////////////////////////
602
603 // TODO: Move somewhere else
604 #ifdef __ANDROID__ // Layoutlib does not support parcel
605 #define ON_ERROR_RETURN(X) \
606 if ((error = (X)) != STATUS_OK) return error
607
608 template <typename T, typename U>
readBlob(AParcel * parcel,T inPlaceCallback,U ashmemCallback)609 static binder_status_t readBlob(AParcel* parcel, T inPlaceCallback, U ashmemCallback) {
610 binder_status_t error = STATUS_OK;
611 BlobType type;
612 static_assert(sizeof(BlobType) == sizeof(int32_t));
613 ON_ERROR_RETURN(AParcel_readInt32(parcel, (int32_t*)&type));
614 if (type == BlobType::IN_PLACE) {
615 struct Data {
616 std::unique_ptr<int8_t[]> ptr = nullptr;
617 int32_t size = 0;
618 } data;
619 ON_ERROR_RETURN(
620 AParcel_readByteArray(parcel, &data,
621 [](void* arrayData, int32_t length, int8_t** outBuffer) {
622 Data* data = reinterpret_cast<Data*>(arrayData);
623 if (length > 0) {
624 data->ptr = std::make_unique<int8_t[]>(length);
625 data->size = length;
626 *outBuffer = data->ptr.get();
627 }
628 return data->ptr != nullptr;
629 }));
630 return inPlaceCallback(std::move(data.ptr), data.size);
631 } else if (type == BlobType::ASHMEM) {
632 int rawFd = -1;
633 int32_t size = 0;
634 ON_ERROR_RETURN(AParcel_readInt32(parcel, &size));
635 ON_ERROR_RETURN(AParcel_readParcelFileDescriptor(parcel, &rawFd));
636 android::base::unique_fd fd(rawFd);
637 return ashmemCallback(std::move(fd), size);
638 } else {
639 // Although the above if/else was "exhaustive" guard against unknown types
640 return STATUS_UNKNOWN_ERROR;
641 }
642 }
643
644 static constexpr size_t BLOB_INPLACE_LIMIT = 12 * 1024;
645 // Fail fast if we can't use ashmem and the size exceeds this limit - the binder transaction
646 // wouldn't go through, anyway
647 // TODO: Can we get this from somewhere?
648 static constexpr size_t BLOB_MAX_INPLACE_LIMIT = 1 * 1024 * 1024;
shouldUseAshmem(AParcel * parcel,int32_t size)649 static constexpr bool shouldUseAshmem(AParcel* parcel, int32_t size) {
650 return size > BLOB_INPLACE_LIMIT && AParcel_getAllowFds(parcel);
651 }
652
writeBlobFromFd(AParcel * parcel,int32_t size,int fd)653 static binder_status_t writeBlobFromFd(AParcel* parcel, int32_t size, int fd) {
654 binder_status_t error = STATUS_OK;
655 ON_ERROR_RETURN(AParcel_writeInt32(parcel, static_cast<int32_t>(BlobType::ASHMEM)));
656 ON_ERROR_RETURN(AParcel_writeInt32(parcel, size));
657 ON_ERROR_RETURN(AParcel_writeParcelFileDescriptor(parcel, fd));
658 return STATUS_OK;
659 }
660
writeBlob(AParcel * parcel,const int32_t size,const void * data,bool immutable)661 static binder_status_t writeBlob(AParcel* parcel, const int32_t size, const void* data, bool immutable) {
662 if (size <= 0 || data == nullptr) {
663 return STATUS_NOT_ENOUGH_DATA;
664 }
665 binder_status_t error = STATUS_OK;
666 if (shouldUseAshmem(parcel, size)) {
667 // Create new ashmem region with read/write priv
668 base::unique_fd fd(ashmem_create_region("bitmap", size));
669 if (fd.get() < 0) {
670 return STATUS_NO_MEMORY;
671 }
672
673 {
674 void* dest = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0);
675 if (dest == MAP_FAILED) {
676 return STATUS_NO_MEMORY;
677 }
678 memcpy(dest, data, size);
679 munmap(dest, size);
680 }
681
682 if (immutable && ashmem_set_prot_region(fd.get(), PROT_READ) < 0) {
683 return STATUS_UNKNOWN_ERROR;
684 }
685 // Workaround b/149851140 in AParcel_writeParcelFileDescriptor
686 int rawFd = fd.release();
687 error = writeBlobFromFd(parcel, size, rawFd);
688 close(rawFd);
689 return error;
690 } else {
691 if (size > BLOB_MAX_INPLACE_LIMIT) {
692 return STATUS_FAILED_TRANSACTION;
693 }
694 ON_ERROR_RETURN(AParcel_writeInt32(parcel, static_cast<int32_t>(BlobType::IN_PLACE)));
695 ON_ERROR_RETURN(AParcel_writeByteArray(parcel, static_cast<const int8_t*>(data), size));
696 return STATUS_OK;
697 }
698 }
699
700 #undef ON_ERROR_RETURN
701
702 #endif // __ANDROID__ // Layoutlib does not support parcel
703
704 // This is the maximum possible size because the SkColorSpace must be
705 // representable (and therefore serializable) using a matrix and numerical
706 // transfer function. If we allow more color space representations in the
707 // framework, we may need to update this maximum size.
708 static constexpr size_t kMaxColorSpaceSerializedBytes = 80;
709
710 static constexpr auto BadParcelableException = "android/os/BadParcelableException";
711
validateImageInfo(const SkImageInfo & info,int32_t rowBytes)712 static bool validateImageInfo(const SkImageInfo& info, int32_t rowBytes) {
713 // TODO: Can we avoid making a SkBitmap for this?
714 return SkBitmap().setInfo(info, rowBytes);
715 }
716
Bitmap_createFromParcel(JNIEnv * env,jobject,jobject parcel)717 static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
718 #ifdef __ANDROID__ // Layoutlib does not support parcel
719 if (parcel == NULL) {
720 jniThrowNullPointerException(env, "parcel cannot be null");
721 return NULL;
722 }
723
724 ScopedParcel p(env, parcel);
725
726 const bool isMutable = p.readInt32();
727 const SkColorType colorType = static_cast<SkColorType>(p.readInt32());
728 const SkAlphaType alphaType = static_cast<SkAlphaType>(p.readInt32());
729 sk_sp<SkColorSpace> colorSpace;
730 const auto optColorSpaceData = p.readData();
731 if (optColorSpaceData) {
732 const auto& colorSpaceData = *optColorSpaceData;
733 if (colorSpaceData->size() > kMaxColorSpaceSerializedBytes) {
734 ALOGD("Bitmap_createFromParcel: Serialized SkColorSpace is larger than expected: "
735 "%zu bytes (max: %zu)\n",
736 colorSpaceData->size(), kMaxColorSpaceSerializedBytes);
737 }
738
739 colorSpace = SkColorSpace::Deserialize(colorSpaceData->data(), colorSpaceData->size());
740 }
741 const int32_t width = p.readInt32();
742 const int32_t height = p.readInt32();
743 const int32_t rowBytes = p.readInt32();
744 const int32_t density = p.readInt32();
745
746 if (kN32_SkColorType != colorType &&
747 kRGBA_F16_SkColorType != colorType &&
748 kRGB_565_SkColorType != colorType &&
749 kARGB_4444_SkColorType != colorType &&
750 kAlpha_8_SkColorType != colorType) {
751 jniThrowExceptionFmt(env, BadParcelableException,
752 "Bitmap_createFromParcel unknown colortype: %d\n", colorType);
753 return NULL;
754 }
755
756 auto imageInfo = SkImageInfo::Make(width, height, colorType, alphaType, colorSpace);
757 size_t allocationSize = 0;
758 if (!validateImageInfo(imageInfo, rowBytes)) {
759 jniThrowRuntimeException(env, "Received bad SkImageInfo");
760 return NULL;
761 }
762 if (!Bitmap::computeAllocationSize(rowBytes, height, &allocationSize)) {
763 jniThrowExceptionFmt(env, BadParcelableException,
764 "Received bad bitmap size: width=%d, height=%d, rowBytes=%d", width,
765 height, rowBytes);
766 return NULL;
767 }
768 sk_sp<Bitmap> nativeBitmap;
769 binder_status_t error = readBlob(
770 p.get(),
771 // In place callback
772 [&](std::unique_ptr<int8_t[]> buffer, int32_t size) {
773 if (allocationSize > size) {
774 android_errorWriteLog(0x534e4554, "213169612");
775 return STATUS_BAD_VALUE;
776 }
777 nativeBitmap = Bitmap::allocateHeapBitmap(allocationSize, imageInfo, rowBytes);
778 if (nativeBitmap) {
779 memcpy(nativeBitmap->pixels(), buffer.get(), allocationSize);
780 return STATUS_OK;
781 }
782 return STATUS_NO_MEMORY;
783 },
784 // Ashmem callback
785 [&](android::base::unique_fd fd, int32_t size) {
786 if (allocationSize > size) {
787 android_errorWriteLog(0x534e4554, "213169612");
788 return STATUS_BAD_VALUE;
789 }
790 int flags = PROT_READ;
791 if (isMutable) {
792 flags |= PROT_WRITE;
793 }
794 void* addr = mmap(nullptr, size, flags, MAP_SHARED, fd.get(), 0);
795 if (addr == MAP_FAILED) {
796 const int err = errno;
797 ALOGW("mmap failed, error %d (%s)", err, strerror(err));
798 return STATUS_NO_MEMORY;
799 }
800 nativeBitmap =
801 Bitmap::createFrom(imageInfo, rowBytes, fd.release(), addr, size, !isMutable);
802 return STATUS_OK;
803 });
804
805 if (error != STATUS_OK && error != STATUS_NO_MEMORY) {
806 // TODO: Stringify the error, see signalExceptionForError in android_util_Binder.cpp
807 jniThrowExceptionFmt(env, BadParcelableException, "Failed to read from Parcel, error=%d",
808 error);
809 return nullptr;
810 }
811 if (error == STATUS_NO_MEMORY || !nativeBitmap) {
812 jniThrowRuntimeException(env, "Could not allocate bitmap data.");
813 return nullptr;
814 }
815
816 return createBitmap(env, nativeBitmap.release(), getPremulBitmapCreateFlags(isMutable), nullptr,
817 nullptr, density);
818 #else
819 jniThrowRuntimeException(env, "Cannot use parcels outside of Android");
820 return NULL;
821 #endif
822 }
823
Bitmap_writeToParcel(JNIEnv * env,jobject,jlong bitmapHandle,jint density,jobject parcel)824 static jboolean Bitmap_writeToParcel(JNIEnv* env, jobject,
825 jlong bitmapHandle, jint density, jobject parcel) {
826 #ifdef __ANDROID__ // Layoutlib does not support parcel
827 if (parcel == NULL) {
828 ALOGD("------- writeToParcel null parcel\n");
829 return JNI_FALSE;
830 }
831
832 ScopedParcel p(env, parcel);
833 SkBitmap bitmap;
834
835 auto bitmapWrapper = reinterpret_cast<BitmapWrapper*>(bitmapHandle);
836 bitmapWrapper->getSkBitmap(&bitmap);
837
838 p.writeInt32(!bitmap.isImmutable());
839 p.writeInt32(bitmap.colorType());
840 p.writeInt32(bitmap.alphaType());
841 SkColorSpace* colorSpace = bitmap.colorSpace();
842 if (colorSpace != nullptr) {
843 p.writeData(colorSpace->serialize());
844 } else {
845 p.writeData(std::nullopt);
846 }
847 p.writeInt32(bitmap.width());
848 p.writeInt32(bitmap.height());
849 p.writeInt32(bitmap.rowBytes());
850 p.writeInt32(density);
851
852 // Transfer the underlying ashmem region if we have one and it's immutable.
853 binder_status_t status;
854 int fd = bitmapWrapper->bitmap().getAshmemFd();
855 if (fd >= 0 && p.allowFds() && bitmap.isImmutable()) {
856 #if DEBUG_PARCEL
857 ALOGD("Bitmap.writeToParcel: transferring immutable bitmap's ashmem fd as "
858 "immutable blob (fds %s)",
859 p.allowFds() ? "allowed" : "forbidden");
860 #endif
861
862 status = writeBlobFromFd(p.get(), bitmapWrapper->bitmap().getAllocationByteCount(), fd);
863 if (status != STATUS_OK) {
864 doThrowRE(env, "Could not write bitmap blob file descriptor.");
865 return JNI_FALSE;
866 }
867 return JNI_TRUE;
868 }
869
870 // Copy the bitmap to a new blob.
871 #if DEBUG_PARCEL
872 ALOGD("Bitmap.writeToParcel: copying bitmap into new blob (fds %s)",
873 p.allowFds() ? "allowed" : "forbidden");
874 #endif
875
876 size_t size = bitmap.computeByteSize();
877 status = writeBlob(p.get(), size, bitmap.getPixels(), bitmap.isImmutable());
878 if (status) {
879 doThrowRE(env, "Could not copy bitmap to parcel blob.");
880 return JNI_FALSE;
881 }
882 return JNI_TRUE;
883 #else
884 doThrowRE(env, "Cannot use parcels outside of Android");
885 return JNI_FALSE;
886 #endif
887 }
888
Bitmap_extractAlpha(JNIEnv * env,jobject clazz,jlong srcHandle,jlong paintHandle,jintArray offsetXY)889 static jobject Bitmap_extractAlpha(JNIEnv* env, jobject clazz,
890 jlong srcHandle, jlong paintHandle,
891 jintArray offsetXY) {
892 SkBitmap src;
893 reinterpret_cast<BitmapWrapper*>(srcHandle)->getSkBitmap(&src);
894 const android::Paint* paint = reinterpret_cast<android::Paint*>(paintHandle);
895 SkIPoint offset;
896 SkBitmap dst;
897 HeapAllocator allocator;
898
899 src.extractAlpha(&dst, paint, &allocator, &offset);
900 // If Skia can't allocate pixels for destination bitmap, it resets
901 // it, that is set its pixels buffer to NULL, and zero width and height.
902 if (dst.getPixels() == NULL && src.getPixels() != NULL) {
903 doThrowOOME(env, "failed to allocate pixels for alpha");
904 return NULL;
905 }
906 if (offsetXY != 0 && env->GetArrayLength(offsetXY) >= 2) {
907 int* array = env->GetIntArrayElements(offsetXY, NULL);
908 array[0] = offset.fX;
909 array[1] = offset.fY;
910 env->ReleaseIntArrayElements(offsetXY, array, 0);
911 }
912
913 return createBitmap(env, allocator.getStorageObjAndReset(),
914 getPremulBitmapCreateFlags(true));
915 }
916
917 ///////////////////////////////////////////////////////////////////////////////
918
Bitmap_isSRGB(JNIEnv * env,jobject,jlong bitmapHandle)919 static jboolean Bitmap_isSRGB(JNIEnv* env, jobject, jlong bitmapHandle) {
920 LocalScopedBitmap bitmapHolder(bitmapHandle);
921 if (!bitmapHolder.valid()) return JNI_TRUE;
922
923 SkColorSpace* colorSpace = bitmapHolder->info().colorSpace();
924 return colorSpace == nullptr || colorSpace->isSRGB();
925 }
926
Bitmap_isSRGBLinear(JNIEnv * env,jobject,jlong bitmapHandle)927 static jboolean Bitmap_isSRGBLinear(JNIEnv* env, jobject, jlong bitmapHandle) {
928 LocalScopedBitmap bitmapHolder(bitmapHandle);
929 if (!bitmapHolder.valid()) return JNI_FALSE;
930
931 SkColorSpace* colorSpace = bitmapHolder->info().colorSpace();
932 sk_sp<SkColorSpace> srgbLinear = SkColorSpace::MakeSRGBLinear();
933 return colorSpace == srgbLinear.get() ? JNI_TRUE : JNI_FALSE;
934 }
935
Bitmap_computeColorSpace(JNIEnv * env,jobject,jlong bitmapHandle)936 static jobject Bitmap_computeColorSpace(JNIEnv* env, jobject, jlong bitmapHandle) {
937 LocalScopedBitmap bitmapHolder(bitmapHandle);
938 if (!bitmapHolder.valid()) return nullptr;
939
940 SkColorSpace* colorSpace = bitmapHolder->info().colorSpace();
941 if (colorSpace == nullptr) return nullptr;
942
943 return GraphicsJNI::getColorSpace(env, colorSpace, bitmapHolder->info().colorType());
944 }
945
Bitmap_setColorSpace(JNIEnv * env,jobject,jlong bitmapHandle,jlong colorSpacePtr)946 static void Bitmap_setColorSpace(JNIEnv* env, jobject, jlong bitmapHandle, jlong colorSpacePtr) {
947 LocalScopedBitmap bitmapHolder(bitmapHandle);
948 sk_sp<SkColorSpace> cs = GraphicsJNI::getNativeColorSpace(colorSpacePtr);
949 bitmapHolder->setColorSpace(cs);
950 }
951
952 ///////////////////////////////////////////////////////////////////////////////
953
Bitmap_getPixel(JNIEnv * env,jobject,jlong bitmapHandle,jint x,jint y)954 static jint Bitmap_getPixel(JNIEnv* env, jobject, jlong bitmapHandle,
955 jint x, jint y) {
956 SkBitmap bitmap;
957 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
958
959 auto sRGB = SkColorSpace::MakeSRGB();
960 SkImageInfo dstInfo = SkImageInfo::Make(
961 1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType, sRGB);
962
963 SkColor dst;
964 bitmap.readPixels(dstInfo, &dst, dstInfo.minRowBytes(), x, y);
965 return static_cast<jint>(dst);
966 }
967
Bitmap_getColor(JNIEnv * env,jobject,jlong bitmapHandle,jint x,jint y)968 static jlong Bitmap_getColor(JNIEnv* env, jobject, jlong bitmapHandle,
969 jint x, jint y) {
970 SkBitmap bitmap;
971 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
972
973 SkImageInfo dstInfo = SkImageInfo::Make(
974 1, 1, kRGBA_F16_SkColorType, kUnpremul_SkAlphaType, bitmap.refColorSpace());
975
976 uint64_t dst;
977 bitmap.readPixels(dstInfo, &dst, dstInfo.minRowBytes(), x, y);
978 return static_cast<jlong>(dst);
979 }
980
Bitmap_getPixels(JNIEnv * env,jobject,jlong bitmapHandle,jintArray pixelArray,jint offset,jint stride,jint x,jint y,jint width,jint height)981 static void Bitmap_getPixels(JNIEnv* env, jobject, jlong bitmapHandle,
982 jintArray pixelArray, jint offset, jint stride,
983 jint x, jint y, jint width, jint height) {
984 SkBitmap bitmap;
985 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
986
987 auto sRGB = SkColorSpace::MakeSRGB();
988 SkImageInfo dstInfo = SkImageInfo::Make(
989 width, height, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType, sRGB);
990
991 jint* dst = env->GetIntArrayElements(pixelArray, NULL);
992 bitmap.readPixels(dstInfo, dst + offset, stride * 4, x, y);
993 env->ReleaseIntArrayElements(pixelArray, dst, 0);
994 }
995
996 ///////////////////////////////////////////////////////////////////////////////
997
Bitmap_setPixel(JNIEnv * env,jobject,jlong bitmapHandle,jint x,jint y,jint colorHandle)998 static void Bitmap_setPixel(JNIEnv* env, jobject, jlong bitmapHandle,
999 jint x, jint y, jint colorHandle) {
1000 SkBitmap bitmap;
1001 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
1002 SkColor color = static_cast<SkColor>(colorHandle);
1003
1004 auto sRGB = SkColorSpace::MakeSRGB();
1005 SkImageInfo srcInfo = SkImageInfo::Make(
1006 1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType, sRGB);
1007 SkPixmap srcPM(srcInfo, &color, srcInfo.minRowBytes());
1008
1009 bitmap.writePixels(srcPM, x, y);
1010 }
1011
Bitmap_setPixels(JNIEnv * env,jobject,jlong bitmapHandle,jintArray pixelArray,jint offset,jint stride,jint x,jint y,jint width,jint height)1012 static void Bitmap_setPixels(JNIEnv* env, jobject, jlong bitmapHandle,
1013 jintArray pixelArray, jint offset, jint stride,
1014 jint x, jint y, jint width, jint height) {
1015 SkBitmap bitmap;
1016 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
1017 GraphicsJNI::SetPixels(env, pixelArray, offset, stride,
1018 x, y, width, height, &bitmap);
1019 }
1020
Bitmap_copyPixelsToBuffer(JNIEnv * env,jobject,jlong bitmapHandle,jobject jbuffer)1021 static void Bitmap_copyPixelsToBuffer(JNIEnv* env, jobject,
1022 jlong bitmapHandle, jobject jbuffer) {
1023 SkBitmap bitmap;
1024 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
1025 const void* src = bitmap.getPixels();
1026
1027 if (NULL != src) {
1028 android::AutoBufferPointer abp(env, jbuffer, JNI_TRUE);
1029
1030 // the java side has already checked that buffer is large enough
1031 memcpy(abp.pointer(), src, bitmap.computeByteSize());
1032 }
1033 }
1034
Bitmap_copyPixelsFromBuffer(JNIEnv * env,jobject,jlong bitmapHandle,jobject jbuffer)1035 static void Bitmap_copyPixelsFromBuffer(JNIEnv* env, jobject,
1036 jlong bitmapHandle, jobject jbuffer) {
1037 SkBitmap bitmap;
1038 reinterpret_cast<BitmapWrapper*>(bitmapHandle)->getSkBitmap(&bitmap);
1039 void* dst = bitmap.getPixels();
1040
1041 if (NULL != dst) {
1042 android::AutoBufferPointer abp(env, jbuffer, JNI_FALSE);
1043 // the java side has already checked that buffer is large enough
1044 memcpy(dst, abp.pointer(), bitmap.computeByteSize());
1045 bitmap.notifyPixelsChanged();
1046 }
1047 }
1048
Bitmap_sameAs(JNIEnv * env,jobject,jlong bm0Handle,jlong bm1Handle)1049 static jboolean Bitmap_sameAs(JNIEnv* env, jobject, jlong bm0Handle, jlong bm1Handle) {
1050 SkBitmap bm0;
1051 SkBitmap bm1;
1052
1053 LocalScopedBitmap bitmap0(bm0Handle);
1054 LocalScopedBitmap bitmap1(bm1Handle);
1055
1056 // Paying the price for making Hardware Bitmap as Config:
1057 // later check for colorType will pass successfully,
1058 // because Hardware Config internally may be RGBA8888 or smth like that.
1059 if (bitmap0->isHardware() != bitmap1->isHardware()) {
1060 return JNI_FALSE;
1061 }
1062
1063 bitmap0->bitmap().getSkBitmap(&bm0);
1064 bitmap1->bitmap().getSkBitmap(&bm1);
1065 if (bm0.width() != bm1.width()
1066 || bm0.height() != bm1.height()
1067 || bm0.colorType() != bm1.colorType()
1068 || bm0.alphaType() != bm1.alphaType()
1069 || !SkColorSpace::Equals(bm0.colorSpace(), bm1.colorSpace())) {
1070 return JNI_FALSE;
1071 }
1072
1073 // if we can't load the pixels, return false
1074 if (NULL == bm0.getPixels() || NULL == bm1.getPixels()) {
1075 return JNI_FALSE;
1076 }
1077
1078 // now compare each scanline. We can't do the entire buffer at once,
1079 // since we don't care about the pixel values that might extend beyond
1080 // the width (since the scanline might be larger than the logical width)
1081 const int h = bm0.height();
1082 const size_t size = bm0.width() * bm0.bytesPerPixel();
1083 for (int y = 0; y < h; y++) {
1084 // SkBitmap::getAddr(int, int) may return NULL due to unrecognized config
1085 // (ex: kRLE_Index8_Config). This will cause memcmp method to crash. Since bm0
1086 // and bm1 both have pixel data() (have passed NULL == getPixels() check),
1087 // those 2 bitmaps should be valid (only unrecognized), we return JNI_FALSE
1088 // to warn user those 2 unrecognized config bitmaps may be different.
1089 void *bm0Addr = bm0.getAddr(0, y);
1090 void *bm1Addr = bm1.getAddr(0, y);
1091
1092 if(bm0Addr == NULL || bm1Addr == NULL) {
1093 return JNI_FALSE;
1094 }
1095
1096 if (memcmp(bm0Addr, bm1Addr, size) != 0) {
1097 return JNI_FALSE;
1098 }
1099 }
1100 return JNI_TRUE;
1101 }
1102
Bitmap_prepareToDraw(JNIEnv * env,jobject,jlong bitmapPtr)1103 static void Bitmap_prepareToDraw(JNIEnv* env, jobject, jlong bitmapPtr) {
1104 LocalScopedBitmap bitmapHandle(bitmapPtr);
1105 if (!bitmapHandle.valid()) return;
1106 android::uirenderer::renderthread::RenderProxy::prepareToDraw(bitmapHandle->bitmap());
1107 }
1108
Bitmap_getAllocationByteCount(JNIEnv * env,jobject,jlong bitmapPtr)1109 static jint Bitmap_getAllocationByteCount(JNIEnv* env, jobject, jlong bitmapPtr) {
1110 LocalScopedBitmap bitmapHandle(bitmapPtr);
1111 return static_cast<jint>(bitmapHandle->getAllocationByteCount());
1112 }
1113
Bitmap_copyPreserveInternalConfig(JNIEnv * env,jobject,jlong bitmapPtr)1114 static jobject Bitmap_copyPreserveInternalConfig(JNIEnv* env, jobject, jlong bitmapPtr) {
1115 LocalScopedBitmap bitmapHandle(bitmapPtr);
1116 LOG_ALWAYS_FATAL_IF(!bitmapHandle->isHardware(),
1117 "Hardware config is only supported config in Bitmap_nativeCopyPreserveInternalConfig");
1118 Bitmap& hwuiBitmap = bitmapHandle->bitmap();
1119 SkBitmap src;
1120 hwuiBitmap.getSkBitmap(&src);
1121
1122 if (src.pixelRef() == nullptr) {
1123 doThrowRE(env, "Could not copy a hardware bitmap.");
1124 return NULL;
1125 }
1126
1127 sk_sp<Bitmap> bitmap = Bitmap::createFrom(src.info(), *src.pixelRef());
1128 return createBitmap(env, bitmap.release(), getPremulBitmapCreateFlags(false));
1129 }
1130
Bitmap_wrapHardwareBufferBitmap(JNIEnv * env,jobject,jobject hardwareBuffer,jlong colorSpacePtr)1131 static jobject Bitmap_wrapHardwareBufferBitmap(JNIEnv* env, jobject, jobject hardwareBuffer,
1132 jlong colorSpacePtr) {
1133 #ifdef __ANDROID__ // Layoutlib does not support graphic buffer
1134 AHardwareBuffer* buffer = uirenderer::HardwareBufferHelpers::AHardwareBuffer_fromHardwareBuffer(
1135 env, hardwareBuffer);
1136 sk_sp<Bitmap> bitmap = Bitmap::createFrom(buffer,
1137 GraphicsJNI::getNativeColorSpace(colorSpacePtr));
1138 if (!bitmap.get()) {
1139 ALOGW("failed to create hardware bitmap from hardware buffer");
1140 return NULL;
1141 }
1142 return bitmap::createBitmap(env, bitmap.release(), getPremulBitmapCreateFlags(false));
1143 #else
1144 return NULL;
1145 #endif
1146 }
1147
Bitmap_getHardwareBuffer(JNIEnv * env,jobject,jlong bitmapPtr)1148 static jobject Bitmap_getHardwareBuffer(JNIEnv* env, jobject, jlong bitmapPtr) {
1149 #ifdef __ANDROID__ // Layoutlib does not support graphic buffer
1150 LocalScopedBitmap bitmapHandle(bitmapPtr);
1151 if (!bitmapHandle->isHardware()) {
1152 jniThrowException(env, "java/lang/IllegalStateException",
1153 "Hardware config is only supported config in Bitmap_getHardwareBuffer");
1154 return nullptr;
1155 }
1156
1157 Bitmap& bitmap = bitmapHandle->bitmap();
1158 return uirenderer::HardwareBufferHelpers::AHardwareBuffer_toHardwareBuffer(
1159 env, bitmap.hardwareBuffer());
1160 #else
1161 return nullptr;
1162 #endif
1163 }
1164
Bitmap_isImmutable(CRITICAL_JNI_PARAMS_COMMA jlong bitmapHandle)1165 static jboolean Bitmap_isImmutable(CRITICAL_JNI_PARAMS_COMMA jlong bitmapHandle) {
1166 LocalScopedBitmap bitmapHolder(bitmapHandle);
1167 if (!bitmapHolder.valid()) return JNI_FALSE;
1168
1169 return bitmapHolder->bitmap().isImmutable() ? JNI_TRUE : JNI_FALSE;
1170 }
1171
Bitmap_isBackedByAshmem(CRITICAL_JNI_PARAMS_COMMA jlong bitmapHandle)1172 static jboolean Bitmap_isBackedByAshmem(CRITICAL_JNI_PARAMS_COMMA jlong bitmapHandle) {
1173 LocalScopedBitmap bitmapHolder(bitmapHandle);
1174 if (!bitmapHolder.valid()) return JNI_FALSE;
1175
1176 return bitmapHolder->bitmap().pixelStorageType() == PixelStorageType::Ashmem ? JNI_TRUE
1177 : JNI_FALSE;
1178 }
1179
Bitmap_setImmutable(JNIEnv * env,jobject,jlong bitmapHandle)1180 static void Bitmap_setImmutable(JNIEnv* env, jobject, jlong bitmapHandle) {
1181 LocalScopedBitmap bitmapHolder(bitmapHandle);
1182 if (!bitmapHolder.valid()) return;
1183
1184 return bitmapHolder->bitmap().setImmutable();
1185 }
1186
Bitmap_hasGainmap(CRITICAL_JNI_PARAMS_COMMA jlong bitmapHandle)1187 static jboolean Bitmap_hasGainmap(CRITICAL_JNI_PARAMS_COMMA jlong bitmapHandle) {
1188 LocalScopedBitmap bitmapHolder(bitmapHandle);
1189 if (!bitmapHolder.valid()) return false;
1190
1191 return bitmapHolder->bitmap().hasGainmap();
1192 }
1193
Bitmap_extractGainmap(JNIEnv * env,jobject,jlong bitmapHandle)1194 static jobject Bitmap_extractGainmap(JNIEnv* env, jobject, jlong bitmapHandle) {
1195 LocalScopedBitmap bitmapHolder(bitmapHandle);
1196 if (!bitmapHolder.valid()) return nullptr;
1197 if (!bitmapHolder->bitmap().hasGainmap()) return nullptr;
1198
1199 return Gainmap_extractFromBitmap(env, bitmapHolder->bitmap());
1200 }
1201
Bitmap_setGainmap(JNIEnv *,jobject,jlong bitmapHandle,jlong gainmapPtr)1202 static void Bitmap_setGainmap(JNIEnv*, jobject, jlong bitmapHandle, jlong gainmapPtr) {
1203 LocalScopedBitmap bitmapHolder(bitmapHandle);
1204 if (!bitmapHolder.valid()) return;
1205 uirenderer::Gainmap* gainmap = reinterpret_cast<uirenderer::Gainmap*>(gainmapPtr);
1206 bitmapHolder->bitmap().setGainmap(sp<uirenderer::Gainmap>::fromExisting(gainmap));
1207 }
1208
1209 ///////////////////////////////////////////////////////////////////////////////
1210
1211 static const JNINativeMethod gBitmapMethods[] = {
1212 {"nativeCreate", "([IIIIIIZJ)Landroid/graphics/Bitmap;", (void*)Bitmap_creator},
1213 {"nativeCopy", "(JIZ)Landroid/graphics/Bitmap;", (void*)Bitmap_copy},
1214 {"nativeCopyAshmem", "(J)Landroid/graphics/Bitmap;", (void*)Bitmap_copyAshmem},
1215 {"nativeCopyAshmemConfig", "(JI)Landroid/graphics/Bitmap;", (void*)Bitmap_copyAshmemConfig},
1216 {"nativeGetAshmemFD", "(J)I", (void*)Bitmap_getAshmemFd},
1217 {"nativeGetNativeFinalizer", "()J", (void*)Bitmap_getNativeFinalizer},
1218 {"nativeRecycle", "(J)V", (void*)Bitmap_recycle},
1219 {"nativeReconfigure", "(JIIIZ)V", (void*)Bitmap_reconfigure},
1220 {"nativeCompress", "(JIILjava/io/OutputStream;[B)Z", (void*)Bitmap_compress},
1221 {"nativeErase", "(JI)V", (void*)Bitmap_erase},
1222 {"nativeErase", "(JJJ)V", (void*)Bitmap_eraseLong},
1223 {"nativeRowBytes", "(J)I", (void*)Bitmap_rowBytes},
1224 {"nativeConfig", "(J)I", (void*)Bitmap_config},
1225 {"nativeHasAlpha", "(J)Z", (void*)Bitmap_hasAlpha},
1226 {"nativeIsPremultiplied", "(J)Z", (void*)Bitmap_isPremultiplied},
1227 {"nativeSetHasAlpha", "(JZZ)V", (void*)Bitmap_setHasAlpha},
1228 {"nativeSetPremultiplied", "(JZ)V", (void*)Bitmap_setPremultiplied},
1229 {"nativeHasMipMap", "(J)Z", (void*)Bitmap_hasMipMap},
1230 {"nativeSetHasMipMap", "(JZ)V", (void*)Bitmap_setHasMipMap},
1231 {"nativeCreateFromParcel", "(Landroid/os/Parcel;)Landroid/graphics/Bitmap;",
1232 (void*)Bitmap_createFromParcel},
1233 {"nativeWriteToParcel", "(JILandroid/os/Parcel;)Z", (void*)Bitmap_writeToParcel},
1234 {"nativeExtractAlpha", "(JJ[I)Landroid/graphics/Bitmap;", (void*)Bitmap_extractAlpha},
1235 {"nativeGenerationId", "(J)I", (void*)Bitmap_getGenerationId},
1236 {"nativeGetPixel", "(JII)I", (void*)Bitmap_getPixel},
1237 {"nativeGetColor", "(JII)J", (void*)Bitmap_getColor},
1238 {"nativeGetPixels", "(J[IIIIIII)V", (void*)Bitmap_getPixels},
1239 {"nativeSetPixel", "(JIII)V", (void*)Bitmap_setPixel},
1240 {"nativeSetPixels", "(J[IIIIIII)V", (void*)Bitmap_setPixels},
1241 {"nativeCopyPixelsToBuffer", "(JLjava/nio/Buffer;)V", (void*)Bitmap_copyPixelsToBuffer},
1242 {"nativeCopyPixelsFromBuffer", "(JLjava/nio/Buffer;)V", (void*)Bitmap_copyPixelsFromBuffer},
1243 {"nativeSameAs", "(JJ)Z", (void*)Bitmap_sameAs},
1244 {"nativePrepareToDraw", "(J)V", (void*)Bitmap_prepareToDraw},
1245 {"nativeGetAllocationByteCount", "(J)I", (void*)Bitmap_getAllocationByteCount},
1246 {"nativeCopyPreserveInternalConfig", "(J)Landroid/graphics/Bitmap;",
1247 (void*)Bitmap_copyPreserveInternalConfig},
1248 {"nativeWrapHardwareBufferBitmap",
1249 "(Landroid/hardware/HardwareBuffer;J)Landroid/graphics/Bitmap;",
1250 (void*)Bitmap_wrapHardwareBufferBitmap},
1251 {"nativeGetHardwareBuffer", "(J)Landroid/hardware/HardwareBuffer;",
1252 (void*)Bitmap_getHardwareBuffer},
1253 {"nativeComputeColorSpace", "(J)Landroid/graphics/ColorSpace;",
1254 (void*)Bitmap_computeColorSpace},
1255 {"nativeSetColorSpace", "(JJ)V", (void*)Bitmap_setColorSpace},
1256 {"nativeIsSRGB", "(J)Z", (void*)Bitmap_isSRGB},
1257 {"nativeIsSRGBLinear", "(J)Z", (void*)Bitmap_isSRGBLinear},
1258 {"nativeSetImmutable", "(J)V", (void*)Bitmap_setImmutable},
1259 {"nativeExtractGainmap", "(J)Landroid/graphics/Gainmap;", (void*)Bitmap_extractGainmap},
1260 {"nativeSetGainmap", "(JJ)V", (void*)Bitmap_setGainmap},
1261
1262 // ------------ @CriticalNative ----------------
1263 {"nativeIsImmutable", "(J)Z", (void*)Bitmap_isImmutable},
1264 {"nativeIsBackedByAshmem", "(J)Z", (void*)Bitmap_isBackedByAshmem},
1265 {"nativeHasGainmap", "(J)Z", (void*)Bitmap_hasGainmap},
1266
1267 };
1268
register_android_graphics_Bitmap(JNIEnv * env)1269 int register_android_graphics_Bitmap(JNIEnv* env)
1270 {
1271 gBitmap_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/Bitmap"));
1272 gBitmap_nativePtr = GetFieldIDOrDie(env, gBitmap_class, "mNativePtr", "J");
1273 gBitmap_constructorMethodID = GetMethodIDOrDie(env, gBitmap_class, "<init>", "(JIIIZ[BLandroid/graphics/NinePatch$InsetStruct;Z)V");
1274 gBitmap_reinitMethodID = GetMethodIDOrDie(env, gBitmap_class, "reinit", "(IIZ)V");
1275 uirenderer::HardwareBufferHelpers::init();
1276 return android::RegisterMethodsOrDie(env, "android/graphics/Bitmap", gBitmapMethods,
1277 NELEM(gBitmapMethods));
1278 }
1279