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