BitmapRegionDecoder.cpp revision ed6b9dff563c5e22f040ff37e12c0d771e0478ae
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "BitmapRegionDecoder"
18
19#include "SkBitmap.h"
20#include "SkData.h"
21#include "SkImageEncoder.h"
22#include "GraphicsJNI.h"
23#include "SkUtils.h"
24#include "SkTemplates.h"
25#include "SkPixelRef.h"
26#include "SkStream.h"
27#include "BitmapFactory.h"
28#include "AutoDecodeCancel.h"
29#include "CreateJavaOutputStreamAdaptor.h"
30#include "Utils.h"
31#include "JNIHelp.h"
32
33#include "core_jni_helpers.h"
34#include "android_util_Binder.h"
35#include "android_nio_utils.h"
36#include "CreateJavaOutputStreamAdaptor.h"
37
38#include <binder/Parcel.h>
39#include <jni.h>
40#include <androidfw/Asset.h>
41#include <sys/stat.h>
42
43using namespace android;
44
45class SkBitmapRegionDecoder {
46public:
47    SkBitmapRegionDecoder(SkImageDecoder* decoder, int width, int height) {
48        fDecoder = decoder;
49        fWidth = width;
50        fHeight = height;
51    }
52    ~SkBitmapRegionDecoder() {
53        SkDELETE(fDecoder);
54    }
55
56    bool decodeRegion(SkBitmap* bitmap, const SkIRect& rect,
57                      SkColorType pref, int sampleSize) {
58        fDecoder->setSampleSize(sampleSize);
59        return fDecoder->decodeSubset(bitmap, rect, pref);
60    }
61
62    SkImageDecoder* getDecoder() const { return fDecoder; }
63    int getWidth() const { return fWidth; }
64    int getHeight() const { return fHeight; }
65
66private:
67    SkImageDecoder* fDecoder;
68    int fWidth;
69    int fHeight;
70};
71
72static jobject createBitmapRegionDecoder(JNIEnv* env, SkStreamRewindable* stream) {
73    SkImageDecoder* decoder = SkImageDecoder::Factory(stream);
74    int width, height;
75    if (NULL == decoder) {
76        doThrowIOE(env, "Image format not supported");
77        return nullObjectReturn("SkImageDecoder::Factory returned null");
78    }
79
80    JavaPixelAllocator *javaAllocator = new JavaPixelAllocator(env);
81    decoder->setAllocator(javaAllocator);
82    javaAllocator->unref();
83
84    if (!decoder->buildTileIndex(stream, &width, &height)) {
85        char msg[100];
86        snprintf(msg, sizeof(msg), "Image failed to decode using %s decoder",
87                decoder->getFormatName());
88        doThrowIOE(env, msg);
89        SkDELETE(decoder);
90        return nullObjectReturn("decoder->buildTileIndex returned false");
91    }
92
93    SkBitmapRegionDecoder *bm = new SkBitmapRegionDecoder(decoder, width, height);
94    return GraphicsJNI::createBitmapRegionDecoder(env, bm);
95}
96
97static jobject nativeNewInstanceFromByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
98                                     jint offset, jint length, jboolean isShareable) {
99    /*  If isShareable we could decide to just wrap the java array and
100        share it, but that means adding a globalref to the java array object
101        For now we just always copy the array's data if isShareable.
102     */
103    AutoJavaByteArray ar(env, byteArray);
104    SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, true);
105
106    jobject brd = createBitmapRegionDecoder(env, stream);
107    SkSafeUnref(stream); // the decoder now holds a reference
108    return brd;
109}
110
111static jobject nativeNewInstanceFromFileDescriptor(JNIEnv* env, jobject clazz,
112                                          jobject fileDescriptor, jboolean isShareable) {
113    NPE_CHECK_RETURN_ZERO(env, fileDescriptor);
114
115    jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
116
117    struct stat fdStat;
118    if (fstat(descriptor, &fdStat) == -1) {
119        doThrowIOE(env, "broken file descriptor");
120        return nullObjectReturn("fstat return -1");
121    }
122
123    SkAutoTUnref<SkData> data(SkData::NewFromFD(descriptor));
124    SkMemoryStream* stream = new SkMemoryStream(data);
125
126    jobject brd = createBitmapRegionDecoder(env, stream);
127    SkSafeUnref(stream); // the decoder now holds a reference
128    return brd;
129}
130
131static jobject nativeNewInstanceFromStream(JNIEnv* env, jobject clazz,
132                                  jobject is,       // InputStream
133                                  jbyteArray storage, // byte[]
134                                  jboolean isShareable) {
135    jobject brd = NULL;
136    // for now we don't allow shareable with java inputstreams
137    SkStreamRewindable* stream = CopyJavaInputStream(env, is, storage);
138
139    if (stream) {
140        brd = createBitmapRegionDecoder(env, stream);
141        stream->unref(); // the decoder now holds a reference
142    }
143    return brd;
144}
145
146static jobject nativeNewInstanceFromAsset(JNIEnv* env, jobject clazz,
147                                 jlong native_asset, // Asset
148                                 jboolean isShareable) {
149    Asset* asset = reinterpret_cast<Asset*>(native_asset);
150    SkAutoTUnref<SkMemoryStream> stream(CopyAssetToStream(asset));
151    if (NULL == stream.get()) {
152        return NULL;
153    }
154
155    jobject brd = createBitmapRegionDecoder(env, stream.get());
156    // The decoder now holds a reference to stream.
157    return brd;
158}
159
160/*
161 * nine patch not supported
162 *
163 * purgeable not supported
164 * reportSizeToVM not supported
165 */
166static jobject nativeDecodeRegion(JNIEnv* env, jobject, jlong brdHandle,
167                                jint start_x, jint start_y, jint width, jint height, jobject options) {
168    SkBitmapRegionDecoder *brd = reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
169    jobject tileBitmap = NULL;
170    SkImageDecoder *decoder = brd->getDecoder();
171    int sampleSize = 1;
172    SkColorType prefColorType = kUnknown_SkColorType;
173    bool doDither = true;
174    bool preferQualityOverSpeed = false;
175    bool requireUnpremultiplied = false;
176
177    if (NULL != options) {
178        sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
179        // initialize these, in case we fail later on
180        env->SetIntField(options, gOptions_widthFieldID, -1);
181        env->SetIntField(options, gOptions_heightFieldID, -1);
182        env->SetObjectField(options, gOptions_mimeFieldID, 0);
183
184        jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
185        prefColorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
186        doDither = env->GetBooleanField(options, gOptions_ditherFieldID);
187        preferQualityOverSpeed = env->GetBooleanField(options,
188                gOptions_preferQualityOverSpeedFieldID);
189        // Get the bitmap for re-use if it exists.
190        tileBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
191        requireUnpremultiplied = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
192    }
193
194    decoder->setDitherImage(doDither);
195    decoder->setPreferQualityOverSpeed(preferQualityOverSpeed);
196    decoder->setRequireUnpremultipliedColors(requireUnpremultiplied);
197    AutoDecoderCancel adc(options, decoder);
198
199    // To fix the race condition in case "requestCancelDecode"
200    // happens earlier than AutoDecoderCancel object is added
201    // to the gAutoDecoderCancelMutex linked list.
202    if (NULL != options && env->GetBooleanField(options, gOptions_mCancelID)) {
203        return nullObjectReturn("gOptions_mCancelID");;
204    }
205
206    SkIRect region;
207    region.fLeft = start_x;
208    region.fTop = start_y;
209    region.fRight = start_x + width;
210    region.fBottom = start_y + height;
211    SkBitmap* bitmap = NULL;
212    SkAutoTDelete<SkBitmap> adb;
213
214    if (tileBitmap != NULL) {
215        // Re-use bitmap.
216        bitmap = GraphicsJNI::getNativeBitmap(env, tileBitmap);
217    }
218    if (bitmap == NULL) {
219        bitmap = new SkBitmap;
220        adb.reset(bitmap);
221    }
222
223    if (!brd->decodeRegion(bitmap, region, prefColorType, sampleSize)) {
224        return nullObjectReturn("decoder->decodeRegion returned false");
225    }
226
227    // update options (if any)
228    if (NULL != options) {
229        env->SetIntField(options, gOptions_widthFieldID, bitmap->width());
230        env->SetIntField(options, gOptions_heightFieldID, bitmap->height());
231        // TODO: set the mimeType field with the data from the codec.
232        // but how to reuse a set of strings, rather than allocating new one
233        // each time?
234        env->SetObjectField(options, gOptions_mimeFieldID,
235                            getMimeTypeString(env, decoder->getFormat()));
236    }
237
238    if (tileBitmap != NULL) {
239        return tileBitmap;
240    }
241
242    // detach bitmap from its autodeleter, since we want to own it now
243    adb.detach();
244
245    JavaPixelAllocator* allocator = (JavaPixelAllocator*) decoder->getAllocator();
246    jbyteArray buff = allocator->getStorageObjAndReset();
247
248    int bitmapCreateFlags = 0;
249    if (!requireUnpremultiplied) bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
250    return GraphicsJNI::createBitmap(env, bitmap, buff, bitmapCreateFlags, NULL, NULL, -1);
251}
252
253static jint nativeGetHeight(JNIEnv* env, jobject, jlong brdHandle) {
254    SkBitmapRegionDecoder *brd = reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
255    return static_cast<jint>(brd->getHeight());
256}
257
258static jint nativeGetWidth(JNIEnv* env, jobject, jlong brdHandle) {
259    SkBitmapRegionDecoder *brd = reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
260    return static_cast<jint>(brd->getWidth());
261}
262
263static void nativeClean(JNIEnv* env, jobject, jlong brdHandle) {
264    SkBitmapRegionDecoder *brd = reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
265    delete brd;
266}
267
268///////////////////////////////////////////////////////////////////////////////
269
270static JNINativeMethod gBitmapRegionDecoderMethods[] = {
271    {   "nativeDecodeRegion",
272        "(JIIIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
273        (void*)nativeDecodeRegion},
274
275    {   "nativeGetHeight", "(J)I", (void*)nativeGetHeight},
276
277    {   "nativeGetWidth", "(J)I", (void*)nativeGetWidth},
278
279    {   "nativeClean", "(J)V", (void*)nativeClean},
280
281    {   "nativeNewInstance",
282        "([BIIZ)Landroid/graphics/BitmapRegionDecoder;",
283        (void*)nativeNewInstanceFromByteArray
284    },
285
286    {   "nativeNewInstance",
287        "(Ljava/io/InputStream;[BZ)Landroid/graphics/BitmapRegionDecoder;",
288        (void*)nativeNewInstanceFromStream
289    },
290
291    {   "nativeNewInstance",
292        "(Ljava/io/FileDescriptor;Z)Landroid/graphics/BitmapRegionDecoder;",
293        (void*)nativeNewInstanceFromFileDescriptor
294    },
295
296    {   "nativeNewInstance",
297        "(JZ)Landroid/graphics/BitmapRegionDecoder;",
298        (void*)nativeNewInstanceFromAsset
299    },
300};
301
302int register_android_graphics_BitmapRegionDecoder(JNIEnv* env)
303{
304    return android::RegisterMethodsOrDie(env, "android/graphics/BitmapRegionDecoder",
305            gBitmapRegionDecoderMethods, NELEM(gBitmapRegionDecoderMethods));
306}
307