• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "Paint.h"
2 #include "SkBitmap.h"
3 #include "SkPixelRef.h"
4 #include "SkImageEncoder.h"
5 #include "SkImageInfo.h"
6 #include "SkColorPriv.h"
7 #include "GraphicsJNI.h"
8 #include "SkDither.h"
9 #include "SkUnPreMultiply.h"
10 #include "SkStream.h"
11 
12 #include <binder/Parcel.h>
13 #include "android_os_Parcel.h"
14 #include "android_util_Binder.h"
15 #include "android_nio_utils.h"
16 #include "CreateJavaOutputStreamAdaptor.h"
17 
18 #include <jni.h>
19 
20 #include <ResourceCache.h>
21 
22 #if 0
23     #define TRACE_BITMAP(code)  code
24 #else
25     #define TRACE_BITMAP(code)
26 #endif
27 
28 ///////////////////////////////////////////////////////////////////////////////
29 // Conversions to/from SkColor, for get/setPixels, and the create method, which
30 // is basically like setPixels
31 
32 typedef void (*FromColorProc)(void* dst, const SkColor src[], int width,
33                               int x, int y);
34 
FromColor_D32(void * dst,const SkColor src[],int width,int,int)35 static void FromColor_D32(void* dst, const SkColor src[], int width,
36                           int, int) {
37     SkPMColor* d = (SkPMColor*)dst;
38 
39     for (int i = 0; i < width; i++) {
40         *d++ = SkPreMultiplyColor(*src++);
41     }
42 }
43 
FromColor_D32_Raw(void * dst,const SkColor src[],int width,int,int)44 static void FromColor_D32_Raw(void* dst, const SkColor src[], int width,
45                           int, int) {
46     // SkColor's ordering may be different from SkPMColor
47     if (SK_COLOR_MATCHES_PMCOLOR_BYTE_ORDER) {
48         memcpy(dst, src, width * sizeof(SkColor));
49         return;
50     }
51 
52     // order isn't same, repack each pixel manually
53     SkPMColor* d = (SkPMColor*)dst;
54     for (int i = 0; i < width; i++) {
55         SkColor c = *src++;
56         *d++ = SkPackARGB32NoCheck(SkColorGetA(c), SkColorGetR(c),
57                                    SkColorGetG(c), SkColorGetB(c));
58     }
59 }
60 
FromColor_D565(void * dst,const SkColor src[],int width,int x,int y)61 static void FromColor_D565(void* dst, const SkColor src[], int width,
62                            int x, int y) {
63     uint16_t* d = (uint16_t*)dst;
64 
65     DITHER_565_SCAN(y);
66     for (int stop = x + width; x < stop; x++) {
67         SkColor c = *src++;
68         *d++ = SkDitherRGBTo565(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c),
69                                 DITHER_VALUE(x));
70     }
71 }
72 
FromColor_D4444(void * dst,const SkColor src[],int width,int x,int y)73 static void FromColor_D4444(void* dst, const SkColor src[], int width,
74                             int x, int y) {
75     SkPMColor16* d = (SkPMColor16*)dst;
76 
77     DITHER_4444_SCAN(y);
78     for (int stop = x + width; x < stop; x++) {
79         SkPMColor pmc = SkPreMultiplyColor(*src++);
80         *d++ = SkDitherARGB32To4444(pmc, DITHER_VALUE(x));
81 //        *d++ = SkPixel32ToPixel4444(pmc);
82     }
83 }
84 
FromColor_D4444_Raw(void * dst,const SkColor src[],int width,int x,int y)85 static void FromColor_D4444_Raw(void* dst, const SkColor src[], int width,
86                             int x, int y) {
87     SkPMColor16* d = (SkPMColor16*)dst;
88 
89     DITHER_4444_SCAN(y);
90     for (int stop = x + width; x < stop; x++) {
91         SkColor c = *src++;
92 
93         // SkPMColor is used because the ordering is ARGB32, even though the target actually premultiplied
94         SkPMColor pmc = SkPackARGB32NoCheck(SkColorGetA(c), SkColorGetR(c),
95                                             SkColorGetG(c), SkColorGetB(c));
96         *d++ = SkDitherARGB32To4444(pmc, DITHER_VALUE(x));
97 //        *d++ = SkPixel32ToPixel4444(pmc);
98     }
99 }
100 
101 // can return NULL
ChooseFromColorProc(const SkBitmap & bitmap)102 static FromColorProc ChooseFromColorProc(const SkBitmap& bitmap) {
103     switch (bitmap.colorType()) {
104         case kN32_SkColorType:
105             return bitmap.alphaType() == kPremul_SkAlphaType ? FromColor_D32 : FromColor_D32_Raw;
106         case kARGB_4444_SkColorType:
107             return bitmap.alphaType() == kPremul_SkAlphaType ? FromColor_D4444 :
108                     FromColor_D4444_Raw;
109         case kRGB_565_SkColorType:
110             return FromColor_D565;
111         default:
112             break;
113     }
114     return NULL;
115 }
116 
SetPixels(JNIEnv * env,jintArray srcColors,int srcOffset,int srcStride,int x,int y,int width,int height,const SkBitmap & dstBitmap)117 bool GraphicsJNI::SetPixels(JNIEnv* env, jintArray srcColors, int srcOffset, int srcStride,
118         int x, int y, int width, int height, const SkBitmap& dstBitmap) {
119     SkAutoLockPixels alp(dstBitmap);
120     void* dst = dstBitmap.getPixels();
121     FromColorProc proc = ChooseFromColorProc(dstBitmap);
122 
123     if (NULL == dst || NULL == proc) {
124         return false;
125     }
126 
127     const jint* array = env->GetIntArrayElements(srcColors, NULL);
128     const SkColor* src = (const SkColor*)array + srcOffset;
129 
130     // reset to to actual choice from caller
131     dst = dstBitmap.getAddr(x, y);
132     // now copy/convert each scanline
133     for (int y = 0; y < height; y++) {
134         proc(dst, src, width, x, y);
135         src += srcStride;
136         dst = (char*)dst + dstBitmap.rowBytes();
137     }
138 
139     dstBitmap.notifyPixelsChanged();
140 
141     env->ReleaseIntArrayElements(srcColors, const_cast<jint*>(array),
142                                  JNI_ABORT);
143     return true;
144 }
145 
146 //////////////////// ToColor procs
147 
148 typedef void (*ToColorProc)(SkColor dst[], const void* src, int width,
149                             SkColorTable*);
150 
ToColor_S32_Alpha(SkColor dst[],const void * src,int width,SkColorTable *)151 static void ToColor_S32_Alpha(SkColor dst[], const void* src, int width,
152                               SkColorTable*) {
153     SkASSERT(width > 0);
154     const SkPMColor* s = (const SkPMColor*)src;
155     do {
156         *dst++ = SkUnPreMultiply::PMColorToColor(*s++);
157     } while (--width != 0);
158 }
159 
ToColor_S32_Raw(SkColor dst[],const void * src,int width,SkColorTable *)160 static void ToColor_S32_Raw(SkColor dst[], const void* src, int width,
161                               SkColorTable*) {
162     SkASSERT(width > 0);
163     const SkPMColor* s = (const SkPMColor*)src;
164     do {
165         SkPMColor c = *s++;
166         *dst++ = SkColorSetARGB(SkGetPackedA32(c), SkGetPackedR32(c),
167                                 SkGetPackedG32(c), SkGetPackedB32(c));
168     } while (--width != 0);
169 }
170 
ToColor_S32_Opaque(SkColor dst[],const void * src,int width,SkColorTable *)171 static void ToColor_S32_Opaque(SkColor dst[], const void* src, int width,
172                                SkColorTable*) {
173     SkASSERT(width > 0);
174     const SkPMColor* s = (const SkPMColor*)src;
175     do {
176         SkPMColor c = *s++;
177         *dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
178                                SkGetPackedB32(c));
179     } while (--width != 0);
180 }
181 
ToColor_S4444_Alpha(SkColor dst[],const void * src,int width,SkColorTable *)182 static void ToColor_S4444_Alpha(SkColor dst[], const void* src, int width,
183                                 SkColorTable*) {
184     SkASSERT(width > 0);
185     const SkPMColor16* s = (const SkPMColor16*)src;
186     do {
187         *dst++ = SkUnPreMultiply::PMColorToColor(SkPixel4444ToPixel32(*s++));
188     } while (--width != 0);
189 }
190 
ToColor_S4444_Raw(SkColor dst[],const void * src,int width,SkColorTable *)191 static void ToColor_S4444_Raw(SkColor dst[], const void* src, int width,
192                                 SkColorTable*) {
193     SkASSERT(width > 0);
194     const SkPMColor16* s = (const SkPMColor16*)src;
195     do {
196         SkPMColor c = SkPixel4444ToPixel32(*s++);
197         *dst++ = SkColorSetARGB(SkGetPackedA32(c), SkGetPackedR32(c),
198                                 SkGetPackedG32(c), SkGetPackedB32(c));
199     } while (--width != 0);
200 }
201 
ToColor_S4444_Opaque(SkColor dst[],const void * src,int width,SkColorTable *)202 static void ToColor_S4444_Opaque(SkColor dst[], const void* src, int width,
203                                  SkColorTable*) {
204     SkASSERT(width > 0);
205     const SkPMColor16* s = (const SkPMColor16*)src;
206     do {
207         SkPMColor c = SkPixel4444ToPixel32(*s++);
208         *dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
209                                SkGetPackedB32(c));
210     } while (--width != 0);
211 }
212 
ToColor_S565(SkColor dst[],const void * src,int width,SkColorTable *)213 static void ToColor_S565(SkColor dst[], const void* src, int width,
214                          SkColorTable*) {
215     SkASSERT(width > 0);
216     const uint16_t* s = (const uint16_t*)src;
217     do {
218         uint16_t c = *s++;
219         *dst++ =  SkColorSetRGB(SkPacked16ToR32(c), SkPacked16ToG32(c),
220                                 SkPacked16ToB32(c));
221     } while (--width != 0);
222 }
223 
ToColor_SI8_Alpha(SkColor dst[],const void * src,int width,SkColorTable * ctable)224 static void ToColor_SI8_Alpha(SkColor dst[], const void* src, int width,
225                               SkColorTable* ctable) {
226     SkASSERT(width > 0);
227     const uint8_t* s = (const uint8_t*)src;
228     const SkPMColor* colors = ctable->lockColors();
229     do {
230         *dst++ = SkUnPreMultiply::PMColorToColor(colors[*s++]);
231     } while (--width != 0);
232     ctable->unlockColors();
233 }
234 
ToColor_SI8_Raw(SkColor dst[],const void * src,int width,SkColorTable * ctable)235 static void ToColor_SI8_Raw(SkColor dst[], const void* src, int width,
236                               SkColorTable* ctable) {
237     SkASSERT(width > 0);
238     const uint8_t* s = (const uint8_t*)src;
239     const SkPMColor* colors = ctable->lockColors();
240     do {
241         SkPMColor c = colors[*s++];
242         *dst++ = SkColorSetARGB(SkGetPackedA32(c), SkGetPackedR32(c),
243                                 SkGetPackedG32(c), SkGetPackedB32(c));
244     } while (--width != 0);
245     ctable->unlockColors();
246 }
247 
ToColor_SI8_Opaque(SkColor dst[],const void * src,int width,SkColorTable * ctable)248 static void ToColor_SI8_Opaque(SkColor dst[], const void* src, int width,
249                                SkColorTable* ctable) {
250     SkASSERT(width > 0);
251     const uint8_t* s = (const uint8_t*)src;
252     const SkPMColor* colors = ctable->lockColors();
253     do {
254         SkPMColor c = colors[*s++];
255         *dst++ = SkColorSetRGB(SkGetPackedR32(c), SkGetPackedG32(c),
256                                SkGetPackedB32(c));
257     } while (--width != 0);
258     ctable->unlockColors();
259 }
260 
261 // can return NULL
ChooseToColorProc(const SkBitmap & src)262 static ToColorProc ChooseToColorProc(const SkBitmap& src) {
263     switch (src.colorType()) {
264         case kN32_SkColorType:
265             switch (src.alphaType()) {
266                 case kOpaque_SkAlphaType:
267                     return ToColor_S32_Opaque;
268                 case kPremul_SkAlphaType:
269                     return ToColor_S32_Alpha;
270                 case kUnpremul_SkAlphaType:
271                     return ToColor_S32_Raw;
272                 default:
273                     return NULL;
274             }
275         case kARGB_4444_SkColorType:
276             switch (src.alphaType()) {
277                 case kOpaque_SkAlphaType:
278                     return ToColor_S4444_Opaque;
279                 case kPremul_SkAlphaType:
280                     return ToColor_S4444_Alpha;
281                 case kUnpremul_SkAlphaType:
282                     return ToColor_S4444_Raw;
283                 default:
284                     return NULL;
285             }
286         case kRGB_565_SkColorType:
287             return ToColor_S565;
288         case kIndex_8_SkColorType:
289             if (src.getColorTable() == NULL) {
290                 return NULL;
291             }
292             switch (src.alphaType()) {
293                 case kOpaque_SkAlphaType:
294                     return ToColor_SI8_Opaque;
295                 case kPremul_SkAlphaType:
296                     return ToColor_SI8_Alpha;
297                 case kUnpremul_SkAlphaType:
298                     return ToColor_SI8_Raw;
299                 default:
300                     return NULL;
301             }
302         default:
303             break;
304     }
305     return NULL;
306 }
307 
308 ///////////////////////////////////////////////////////////////////////////////
309 ///////////////////////////////////////////////////////////////////////////////
310 
getPremulBitmapCreateFlags(bool isMutable)311 static int getPremulBitmapCreateFlags(bool isMutable) {
312     int flags = GraphicsJNI::kBitmapCreateFlag_Premultiplied;
313     if (isMutable) flags |= GraphicsJNI::kBitmapCreateFlag_Mutable;
314     return flags;
315 }
316 
Bitmap_creator(JNIEnv * env,jobject,jintArray jColors,jint offset,jint stride,jint width,jint height,jint configHandle,jboolean isMutable)317 static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
318                               jint offset, jint stride, jint width, jint height,
319                               jint configHandle, jboolean isMutable) {
320     SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
321     if (NULL != jColors) {
322         size_t n = env->GetArrayLength(jColors);
323         if (n < SkAbs32(stride) * (size_t)height) {
324             doThrowAIOOBE(env);
325             return NULL;
326         }
327     }
328 
329     // ARGB_4444 is a deprecated format, convert automatically to 8888
330     if (colorType == kARGB_4444_SkColorType) {
331         colorType = kN32_SkColorType;
332     }
333 
334     SkBitmap bitmap;
335     bitmap.setInfo(SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType));
336 
337     jbyteArray buff = GraphicsJNI::allocateJavaPixelRef(env, &bitmap, NULL);
338     if (NULL == buff) {
339         return NULL;
340     }
341 
342     if (jColors != NULL) {
343         GraphicsJNI::SetPixels(env, jColors, offset, stride,
344                 0, 0, width, height, bitmap);
345     }
346 
347     return GraphicsJNI::createBitmap(env, new SkBitmap(bitmap), buff,
348             getPremulBitmapCreateFlags(isMutable), NULL, NULL);
349 }
350 
Bitmap_copy(JNIEnv * env,jobject,jlong srcHandle,jint dstConfigHandle,jboolean isMutable)351 static jobject Bitmap_copy(JNIEnv* env, jobject, jlong srcHandle,
352                            jint dstConfigHandle, jboolean isMutable) {
353     const SkBitmap* src = reinterpret_cast<SkBitmap*>(srcHandle);
354     SkColorType dstCT = GraphicsJNI::legacyBitmapConfigToColorType(dstConfigHandle);
355     SkBitmap            result;
356     JavaPixelAllocator  allocator(env);
357 
358     if (!src->copyTo(&result, dstCT, &allocator)) {
359         return NULL;
360     }
361     return GraphicsJNI::createBitmap(env, new SkBitmap(result), allocator.getStorageObj(),
362             getPremulBitmapCreateFlags(isMutable), NULL, NULL);
363 }
364 
Bitmap_destructor(JNIEnv * env,jobject,jlong bitmapHandle)365 static void Bitmap_destructor(JNIEnv* env, jobject, jlong bitmapHandle) {
366     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
367 #ifdef USE_OPENGL_RENDERER
368     if (android::uirenderer::ResourceCache::hasInstance()) {
369         android::uirenderer::ResourceCache::getInstance().destructor(bitmap);
370         return;
371     }
372 #endif // USE_OPENGL_RENDERER
373     delete bitmap;
374 }
375 
Bitmap_recycle(JNIEnv * env,jobject,jlong bitmapHandle)376 static jboolean Bitmap_recycle(JNIEnv* env, jobject, jlong bitmapHandle) {
377     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
378 #ifdef USE_OPENGL_RENDERER
379     if (android::uirenderer::ResourceCache::hasInstance()) {
380         bool result;
381         result = android::uirenderer::ResourceCache::getInstance().recycle(bitmap);
382         return result ? JNI_TRUE : JNI_FALSE;
383     }
384 #endif // USE_OPENGL_RENDERER
385     bitmap->setPixels(NULL, NULL);
386     return JNI_TRUE;
387 }
388 
Bitmap_reconfigure(JNIEnv * env,jobject clazz,jlong bitmapHandle,jint width,jint height,jint configHandle,jint allocSize,jboolean requestPremul)389 static void Bitmap_reconfigure(JNIEnv* env, jobject clazz, jlong bitmapHandle,
390         jint width, jint height, jint configHandle, jint allocSize,
391         jboolean requestPremul) {
392     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
393     SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
394 
395     // ARGB_4444 is a deprecated format, convert automatically to 8888
396     if (colorType == kARGB_4444_SkColorType) {
397         colorType = kN32_SkColorType;
398     }
399 
400     if (width * height * SkColorTypeBytesPerPixel(colorType) > allocSize) {
401         // done in native as there's no way to get BytesPerPixel in Java
402         doThrowIAE(env, "Bitmap not large enough to support new configuration");
403         return;
404     }
405     SkPixelRef* ref = bitmap->pixelRef();
406     ref->ref();
407     SkAlphaType alphaType;
408     if (bitmap->colorType() != kRGB_565_SkColorType
409             && bitmap->alphaType() == kOpaque_SkAlphaType) {
410         // If the original bitmap was set to opaque, keep that setting, unless it
411         // was 565, which is required to be opaque.
412         alphaType = kOpaque_SkAlphaType;
413     } else {
414         // Otherwise respect the premultiplied request.
415         alphaType = requestPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
416     }
417     bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType));
418     // FIXME: Skia thinks of an SkPixelRef as having a constant SkImageInfo (except for
419     // its alphatype), so it would make more sense from Skia's perspective to create a
420     // new SkPixelRef. That said, libhwui uses the pointer to the SkPixelRef as a key
421     // for its cache, so it won't realize this is the same Java Bitmap.
422     SkImageInfo& info = const_cast<SkImageInfo&>(ref->info());
423     // Use the updated from the SkBitmap, which may have corrected an invalid alphatype.
424     // (e.g. 565 non-opaque)
425     info = bitmap->info();
426     bitmap->setPixelRef(ref);
427 
428     // notifyPixelsChanged will increment the generation ID even though the actual pixel data
429     // hasn't been touched. This signals the renderer that the bitmap (including width, height,
430     // colortype and alphatype) has changed.
431     ref->notifyPixelsChanged();
432     ref->unref();
433 }
434 
435 // These must match the int values in Bitmap.java
436 enum JavaEncodeFormat {
437     kJPEG_JavaEncodeFormat = 0,
438     kPNG_JavaEncodeFormat = 1,
439     kWEBP_JavaEncodeFormat = 2
440 };
441 
Bitmap_compress(JNIEnv * env,jobject clazz,jlong bitmapHandle,jint format,jint quality,jobject jstream,jbyteArray jstorage)442 static jboolean Bitmap_compress(JNIEnv* env, jobject clazz, jlong bitmapHandle,
443                                 jint format, jint quality,
444                                 jobject jstream, jbyteArray jstorage) {
445     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
446     SkImageEncoder::Type fm;
447 
448     switch (format) {
449     case kJPEG_JavaEncodeFormat:
450         fm = SkImageEncoder::kJPEG_Type;
451         break;
452     case kPNG_JavaEncodeFormat:
453         fm = SkImageEncoder::kPNG_Type;
454         break;
455     case kWEBP_JavaEncodeFormat:
456         fm = SkImageEncoder::kWEBP_Type;
457         break;
458     default:
459         return JNI_FALSE;
460     }
461 
462     bool success = false;
463     if (NULL != bitmap) {
464         SkAutoLockPixels alp(*bitmap);
465 
466         if (NULL == bitmap->getPixels()) {
467             return JNI_FALSE;
468         }
469 
470         SkWStream* strm = CreateJavaOutputStreamAdaptor(env, jstream, jstorage);
471         if (NULL == strm) {
472             return JNI_FALSE;
473         }
474 
475         SkImageEncoder* encoder = SkImageEncoder::Create(fm);
476         if (NULL != encoder) {
477             success = encoder->encodeStream(strm, *bitmap, quality);
478             delete encoder;
479         }
480         delete strm;
481     }
482     return success ? JNI_TRUE : JNI_FALSE;
483 }
484 
Bitmap_erase(JNIEnv * env,jobject,jlong bitmapHandle,jint color)485 static void Bitmap_erase(JNIEnv* env, jobject, jlong bitmapHandle, jint color) {
486     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
487     bitmap->eraseColor(color);
488 }
489 
Bitmap_rowBytes(JNIEnv * env,jobject,jlong bitmapHandle)490 static jint Bitmap_rowBytes(JNIEnv* env, jobject, jlong bitmapHandle) {
491     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
492     return static_cast<jint>(bitmap->rowBytes());
493 }
494 
Bitmap_config(JNIEnv * env,jobject,jlong bitmapHandle)495 static jint Bitmap_config(JNIEnv* env, jobject, jlong bitmapHandle) {
496     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
497     return GraphicsJNI::colorTypeToLegacyBitmapConfig(bitmap->colorType());
498 }
499 
Bitmap_getGenerationId(JNIEnv * env,jobject,jlong bitmapHandle)500 static jint Bitmap_getGenerationId(JNIEnv* env, jobject, jlong bitmapHandle) {
501     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
502     return static_cast<jint>(bitmap->getGenerationID());
503 }
504 
Bitmap_isPremultiplied(JNIEnv * env,jobject,jlong bitmapHandle)505 static jboolean Bitmap_isPremultiplied(JNIEnv* env, jobject, jlong bitmapHandle) {
506     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
507     if (bitmap->alphaType() == kPremul_SkAlphaType) {
508         return JNI_TRUE;
509     }
510     return JNI_FALSE;
511 }
512 
Bitmap_hasAlpha(JNIEnv * env,jobject,jlong bitmapHandle)513 static jboolean Bitmap_hasAlpha(JNIEnv* env, jobject, jlong bitmapHandle) {
514     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
515     return !bitmap->isOpaque() ? JNI_TRUE : JNI_FALSE;
516 }
517 
Bitmap_setHasAlpha(JNIEnv * env,jobject,jlong bitmapHandle,jboolean hasAlpha,jboolean requestPremul)518 static void Bitmap_setHasAlpha(JNIEnv* env, jobject, jlong bitmapHandle,
519         jboolean hasAlpha, jboolean requestPremul) {
520     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
521     if (hasAlpha) {
522         bitmap->setAlphaType(requestPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType);
523     } else {
524         bitmap->setAlphaType(kOpaque_SkAlphaType);
525     }
526 }
527 
Bitmap_setPremultiplied(JNIEnv * env,jobject,jlong bitmapHandle,jboolean isPremul)528 static void Bitmap_setPremultiplied(JNIEnv* env, jobject, jlong bitmapHandle,
529         jboolean isPremul) {
530     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
531     if (!bitmap->isOpaque()) {
532         if (isPremul) {
533             bitmap->setAlphaType(kPremul_SkAlphaType);
534         } else {
535             bitmap->setAlphaType(kUnpremul_SkAlphaType);
536         }
537     }
538 }
539 
Bitmap_hasMipMap(JNIEnv * env,jobject,jlong bitmapHandle)540 static jboolean Bitmap_hasMipMap(JNIEnv* env, jobject, jlong bitmapHandle) {
541     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
542     return bitmap->hasHardwareMipMap() ? JNI_TRUE : JNI_FALSE;
543 }
544 
Bitmap_setHasMipMap(JNIEnv * env,jobject,jlong bitmapHandle,jboolean hasMipMap)545 static void Bitmap_setHasMipMap(JNIEnv* env, jobject, jlong bitmapHandle,
546                                 jboolean hasMipMap) {
547     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
548     bitmap->setHasHardwareMipMap(hasMipMap);
549 }
550 
551 ///////////////////////////////////////////////////////////////////////////////
552 
Bitmap_createFromParcel(JNIEnv * env,jobject,jobject parcel)553 static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
554     if (parcel == NULL) {
555         SkDebugf("-------- unparcel parcel is NULL\n");
556         return NULL;
557     }
558 
559     android::Parcel* p = android::parcelForJavaObject(env, parcel);
560 
561     const bool        isMutable = p->readInt32() != 0;
562     const SkColorType colorType = (SkColorType)p->readInt32();
563     const SkAlphaType alphaType = (SkAlphaType)p->readInt32();
564     const int         width = p->readInt32();
565     const int         height = p->readInt32();
566     const int         rowBytes = p->readInt32();
567     const int         density = p->readInt32();
568 
569     if (kN32_SkColorType != colorType &&
570             kRGB_565_SkColorType != colorType &&
571             kARGB_4444_SkColorType != colorType &&
572             kIndex_8_SkColorType != colorType &&
573             kAlpha_8_SkColorType != colorType) {
574         SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType);
575         return NULL;
576     }
577 
578     SkAutoTDelete<SkBitmap> bitmap(new SkBitmap);
579 
580     if (!bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes)) {
581         return NULL;
582     }
583 
584     SkColorTable* ctable = NULL;
585     if (colorType == kIndex_8_SkColorType) {
586         int count = p->readInt32();
587         if (count < 0 || count > 256) {
588             // The data is corrupt, since SkColorTable enforces a value between 0 and 256,
589             // inclusive.
590             return NULL;
591         }
592         if (count > 0) {
593             size_t size = count * sizeof(SkPMColor);
594             const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
595             if (src == NULL) {
596                 return NULL;
597             }
598             ctable = new SkColorTable(src, count);
599         }
600     }
601 
602     jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap.get(), ctable);
603     if (NULL == buffer) {
604         SkSafeUnref(ctable);
605         return NULL;
606     }
607 
608     SkSafeUnref(ctable);
609 
610     size_t size = bitmap->getSize();
611 
612     android::Parcel::ReadableBlob blob;
613     android::status_t status = p->readBlob(size, &blob);
614     if (status) {
615         doThrowRE(env, "Could not read bitmap from parcel blob.");
616         return NULL;
617     }
618 
619     bitmap->lockPixels();
620     memcpy(bitmap->getPixels(), blob.data(), size);
621     bitmap->unlockPixels();
622 
623     blob.release();
624 
625     return GraphicsJNI::createBitmap(env, bitmap.detach(), buffer,
626             getPremulBitmapCreateFlags(isMutable), NULL, NULL, density);
627 }
628 
Bitmap_writeToParcel(JNIEnv * env,jobject,jlong bitmapHandle,jboolean isMutable,jint density,jobject parcel)629 static jboolean Bitmap_writeToParcel(JNIEnv* env, jobject,
630                                      jlong bitmapHandle,
631                                      jboolean isMutable, jint density,
632                                      jobject parcel) {
633     const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
634     if (parcel == NULL) {
635         SkDebugf("------- writeToParcel null parcel\n");
636         return JNI_FALSE;
637     }
638 
639     android::Parcel* p = android::parcelForJavaObject(env, parcel);
640 
641     p->writeInt32(isMutable);
642     p->writeInt32(bitmap->colorType());
643     p->writeInt32(bitmap->alphaType());
644     p->writeInt32(bitmap->width());
645     p->writeInt32(bitmap->height());
646     p->writeInt32(bitmap->rowBytes());
647     p->writeInt32(density);
648 
649     if (bitmap->colorType() == kIndex_8_SkColorType) {
650         SkColorTable* ctable = bitmap->getColorTable();
651         if (ctable != NULL) {
652             int count = ctable->count();
653             p->writeInt32(count);
654             memcpy(p->writeInplace(count * sizeof(SkPMColor)),
655                    ctable->lockColors(), count * sizeof(SkPMColor));
656             ctable->unlockColors();
657         } else {
658             p->writeInt32(0);   // indicate no ctable
659         }
660     }
661 
662     size_t size = bitmap->getSize();
663 
664     android::Parcel::WritableBlob blob;
665     android::status_t status = p->writeBlob(size, &blob);
666     if (status) {
667         doThrowRE(env, "Could not write bitmap to parcel blob.");
668         return JNI_FALSE;
669     }
670 
671     bitmap->lockPixels();
672     const void* pSrc =  bitmap->getPixels();
673     if (pSrc == NULL) {
674         memset(blob.data(), 0, size);
675     } else {
676         memcpy(blob.data(), pSrc, size);
677     }
678     bitmap->unlockPixels();
679 
680     blob.release();
681     return JNI_TRUE;
682 }
683 
Bitmap_extractAlpha(JNIEnv * env,jobject clazz,jlong srcHandle,jlong paintHandle,jintArray offsetXY)684 static jobject Bitmap_extractAlpha(JNIEnv* env, jobject clazz,
685                                    jlong srcHandle, jlong paintHandle,
686                                    jintArray offsetXY) {
687     const SkBitmap* src = reinterpret_cast<SkBitmap*>(srcHandle);
688     const android::Paint* paint = reinterpret_cast<android::Paint*>(paintHandle);
689     SkIPoint  offset;
690     SkBitmap* dst = new SkBitmap;
691     JavaPixelAllocator allocator(env);
692 
693     src->extractAlpha(dst, paint, &allocator, &offset);
694     // If Skia can't allocate pixels for destination bitmap, it resets
695     // it, that is set its pixels buffer to NULL, and zero width and height.
696     if (dst->getPixels() == NULL && src->getPixels() != NULL) {
697         delete dst;
698         doThrowOOME(env, "failed to allocate pixels for alpha");
699         return NULL;
700     }
701     if (offsetXY != 0 && env->GetArrayLength(offsetXY) >= 2) {
702         int* array = env->GetIntArrayElements(offsetXY, NULL);
703         array[0] = offset.fX;
704         array[1] = offset.fY;
705         env->ReleaseIntArrayElements(offsetXY, array, 0);
706     }
707 
708     return GraphicsJNI::createBitmap(env, dst, allocator.getStorageObj(),
709             getPremulBitmapCreateFlags(true), NULL, NULL);
710 }
711 
712 ///////////////////////////////////////////////////////////////////////////////
713 
Bitmap_getPixel(JNIEnv * env,jobject,jlong bitmapHandle,jint x,jint y)714 static jint Bitmap_getPixel(JNIEnv* env, jobject, jlong bitmapHandle,
715         jint x, jint y) {
716     const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
717     SkAutoLockPixels alp(*bitmap);
718 
719     ToColorProc proc = ChooseToColorProc(*bitmap);
720     if (NULL == proc) {
721         return 0;
722     }
723     const void* src = bitmap->getAddr(x, y);
724     if (NULL == src) {
725         return 0;
726     }
727 
728     SkColor dst[1];
729     proc(dst, src, 1, bitmap->getColorTable());
730     return static_cast<jint>(dst[0]);
731 }
732 
Bitmap_getPixels(JNIEnv * env,jobject,jlong bitmapHandle,jintArray pixelArray,jint offset,jint stride,jint x,jint y,jint width,jint height)733 static void Bitmap_getPixels(JNIEnv* env, jobject, jlong bitmapHandle,
734         jintArray pixelArray, jint offset, jint stride,
735         jint x, jint y, jint width, jint height) {
736     const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
737     SkAutoLockPixels alp(*bitmap);
738 
739     ToColorProc proc = ChooseToColorProc(*bitmap);
740     if (NULL == proc) {
741         return;
742     }
743     const void* src = bitmap->getAddr(x, y);
744     if (NULL == src) {
745         return;
746     }
747 
748     SkColorTable* ctable = bitmap->getColorTable();
749     jint* dst = env->GetIntArrayElements(pixelArray, NULL);
750     SkColor* d = (SkColor*)dst + offset;
751     while (--height >= 0) {
752         proc(d, src, width, ctable);
753         d += stride;
754         src = (void*)((const char*)src + bitmap->rowBytes());
755     }
756     env->ReleaseIntArrayElements(pixelArray, dst, 0);
757 }
758 
759 ///////////////////////////////////////////////////////////////////////////////
760 
Bitmap_setPixel(JNIEnv * env,jobject,jlong bitmapHandle,jint x,jint y,jint colorHandle)761 static void Bitmap_setPixel(JNIEnv* env, jobject, jlong bitmapHandle,
762         jint x, jint y, jint colorHandle) {
763     const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
764     SkColor color = static_cast<SkColor>(colorHandle);
765     SkAutoLockPixels alp(*bitmap);
766     if (NULL == bitmap->getPixels()) {
767         return;
768     }
769 
770     FromColorProc proc = ChooseFromColorProc(*bitmap);
771     if (NULL == proc) {
772         return;
773     }
774 
775     proc(bitmap->getAddr(x, y), &color, 1, x, y);
776     bitmap->notifyPixelsChanged();
777 }
778 
Bitmap_setPixels(JNIEnv * env,jobject,jlong bitmapHandle,jintArray pixelArray,jint offset,jint stride,jint x,jint y,jint width,jint height)779 static void Bitmap_setPixels(JNIEnv* env, jobject, jlong bitmapHandle,
780         jintArray pixelArray, jint offset, jint stride,
781         jint x, jint y, jint width, jint height) {
782     const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
783     GraphicsJNI::SetPixels(env, pixelArray, offset, stride,
784             x, y, width, height, *bitmap);
785 }
786 
Bitmap_copyPixelsToBuffer(JNIEnv * env,jobject,jlong bitmapHandle,jobject jbuffer)787 static void Bitmap_copyPixelsToBuffer(JNIEnv* env, jobject,
788                                       jlong bitmapHandle, jobject jbuffer) {
789     const SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
790     SkAutoLockPixels alp(*bitmap);
791     const void* src = bitmap->getPixels();
792 
793     if (NULL != src) {
794         android::AutoBufferPointer abp(env, jbuffer, JNI_TRUE);
795 
796         // the java side has already checked that buffer is large enough
797         memcpy(abp.pointer(), src, bitmap->getSize());
798     }
799 }
800 
Bitmap_copyPixelsFromBuffer(JNIEnv * env,jobject,jlong bitmapHandle,jobject jbuffer)801 static void Bitmap_copyPixelsFromBuffer(JNIEnv* env, jobject,
802                                         jlong bitmapHandle, jobject jbuffer) {
803     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
804     SkAutoLockPixels alp(*bitmap);
805     void* dst = bitmap->getPixels();
806 
807     if (NULL != dst) {
808         android::AutoBufferPointer abp(env, jbuffer, JNI_FALSE);
809         // the java side has already checked that buffer is large enough
810         memcpy(dst, abp.pointer(), bitmap->getSize());
811         bitmap->notifyPixelsChanged();
812     }
813 }
814 
Bitmap_sameAs(JNIEnv * env,jobject,jlong bm0Handle,jlong bm1Handle)815 static jboolean Bitmap_sameAs(JNIEnv* env, jobject, jlong bm0Handle,
816                               jlong bm1Handle) {
817     const SkBitmap* bm0 = reinterpret_cast<SkBitmap*>(bm0Handle);
818     const SkBitmap* bm1 = reinterpret_cast<SkBitmap*>(bm1Handle);
819     if (bm0->width() != bm1->width() ||
820         bm0->height() != bm1->height() ||
821         bm0->colorType() != bm1->colorType()) {
822         return JNI_FALSE;
823     }
824 
825     SkAutoLockPixels alp0(*bm0);
826     SkAutoLockPixels alp1(*bm1);
827 
828     // if we can't load the pixels, return false
829     if (NULL == bm0->getPixels() || NULL == bm1->getPixels()) {
830         return JNI_FALSE;
831     }
832 
833     if (bm0->colorType() == kIndex_8_SkColorType) {
834         SkColorTable* ct0 = bm0->getColorTable();
835         SkColorTable* ct1 = bm1->getColorTable();
836         if (NULL == ct0 || NULL == ct1) {
837             return JNI_FALSE;
838         }
839         if (ct0->count() != ct1->count()) {
840             return JNI_FALSE;
841         }
842 
843         SkAutoLockColors alc0(ct0);
844         SkAutoLockColors alc1(ct1);
845         const size_t size = ct0->count() * sizeof(SkPMColor);
846         if (memcmp(alc0.colors(), alc1.colors(), size) != 0) {
847             return JNI_FALSE;
848         }
849     }
850 
851     // now compare each scanline. We can't do the entire buffer at once,
852     // since we don't care about the pixel values that might extend beyond
853     // the width (since the scanline might be larger than the logical width)
854     const int h = bm0->height();
855     const size_t size = bm0->width() * bm0->bytesPerPixel();
856     for (int y = 0; y < h; y++) {
857         // SkBitmap::getAddr(int, int) may return NULL due to unrecognized config
858         // (ex: kRLE_Index8_Config). This will cause memcmp method to crash. Since bm0
859         // and bm1 both have pixel data() (have passed NULL == getPixels() check),
860         // those 2 bitmaps should be valid (only unrecognized), we return JNI_FALSE
861         // to warn user those 2 unrecognized config bitmaps may be different.
862         void *bm0Addr = bm0->getAddr(0, y);
863         void *bm1Addr = bm1->getAddr(0, y);
864 
865         if(bm0Addr == NULL || bm1Addr == NULL) {
866             return JNI_FALSE;
867         }
868 
869         if (memcmp(bm0Addr, bm1Addr, size) != 0) {
870             return JNI_FALSE;
871         }
872     }
873     return JNI_TRUE;
874 }
875 
Bitmap_prepareToDraw(JNIEnv * env,jobject,jlong bitmapHandle)876 static void Bitmap_prepareToDraw(JNIEnv* env, jobject, jlong bitmapHandle) {
877     SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
878     bitmap->lockPixels();
879     bitmap->unlockPixels();
880 }
881 
882 ///////////////////////////////////////////////////////////////////////////////
883 
884 #include <android_runtime/AndroidRuntime.h>
885 
886 static JNINativeMethod gBitmapMethods[] = {
887     {   "nativeCreate",             "([IIIIIIZ)Landroid/graphics/Bitmap;",
888         (void*)Bitmap_creator },
889     {   "nativeCopy",               "(JIZ)Landroid/graphics/Bitmap;",
890         (void*)Bitmap_copy },
891     {   "nativeDestructor",         "(J)V", (void*)Bitmap_destructor },
892     {   "nativeRecycle",            "(J)Z", (void*)Bitmap_recycle },
893     {   "nativeReconfigure",        "(JIIIIZ)V", (void*)Bitmap_reconfigure },
894     {   "nativeCompress",           "(JIILjava/io/OutputStream;[B)Z",
895         (void*)Bitmap_compress },
896     {   "nativeErase",              "(JI)V", (void*)Bitmap_erase },
897     {   "nativeRowBytes",           "(J)I", (void*)Bitmap_rowBytes },
898     {   "nativeConfig",             "(J)I", (void*)Bitmap_config },
899     {   "nativeHasAlpha",           "(J)Z", (void*)Bitmap_hasAlpha },
900     {   "nativeIsPremultiplied",    "(J)Z", (void*)Bitmap_isPremultiplied},
901     {   "nativeSetHasAlpha",        "(JZZ)V", (void*)Bitmap_setHasAlpha},
902     {   "nativeSetPremultiplied",   "(JZ)V", (void*)Bitmap_setPremultiplied},
903     {   "nativeHasMipMap",          "(J)Z", (void*)Bitmap_hasMipMap },
904     {   "nativeSetHasMipMap",       "(JZ)V", (void*)Bitmap_setHasMipMap },
905     {   "nativeCreateFromParcel",
906         "(Landroid/os/Parcel;)Landroid/graphics/Bitmap;",
907         (void*)Bitmap_createFromParcel },
908     {   "nativeWriteToParcel",      "(JZILandroid/os/Parcel;)Z",
909         (void*)Bitmap_writeToParcel },
910     {   "nativeExtractAlpha",       "(JJ[I)Landroid/graphics/Bitmap;",
911         (void*)Bitmap_extractAlpha },
912     {   "nativeGenerationId",       "(J)I", (void*)Bitmap_getGenerationId },
913     {   "nativeGetPixel",           "(JII)I", (void*)Bitmap_getPixel },
914     {   "nativeGetPixels",          "(J[IIIIIII)V", (void*)Bitmap_getPixels },
915     {   "nativeSetPixel",           "(JIII)V", (void*)Bitmap_setPixel },
916     {   "nativeSetPixels",          "(J[IIIIIII)V", (void*)Bitmap_setPixels },
917     {   "nativeCopyPixelsToBuffer", "(JLjava/nio/Buffer;)V",
918                                             (void*)Bitmap_copyPixelsToBuffer },
919     {   "nativeCopyPixelsFromBuffer", "(JLjava/nio/Buffer;)V",
920                                             (void*)Bitmap_copyPixelsFromBuffer },
921     {   "nativeSameAs",             "(JJ)Z", (void*)Bitmap_sameAs },
922     {   "nativePrepareToDraw",      "(J)V", (void*)Bitmap_prepareToDraw },
923 };
924 
925 #define kClassPathName  "android/graphics/Bitmap"
926 
register_android_graphics_Bitmap(JNIEnv * env)927 int register_android_graphics_Bitmap(JNIEnv* env)
928 {
929     return android::AndroidRuntime::registerNativeMethods(env, kClassPathName,
930                                 gBitmapMethods, SK_ARRAY_COUNT(gBitmapMethods));
931 }
932