blob: add62b1f0d6d0bdd9cc9193677863f8632178858 [file] [log] [blame]
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -04001/*
2 * Copyright (C) 2017 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
Leon Scroggins III671cce22018-01-14 16:52:17 -050017#include "ImageDecoder.h"
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040018
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -040019#include <FrontBufferedStream.h>
John Reck5bd537e2023-01-24 20:13:45 -050020#include <HardwareBitmapUploader.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040021#include <SkAndroidCodec.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050022#include <SkBitmap.h>
23#include <SkColorSpace.h>
24#include <SkImageInfo.h>
25#include <SkRect.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040026#include <SkStream.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050027#include <SkString.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040028#include <androidfw/Asset.h>
Derek Sollenbergerc5882c42019-10-25 11:11:32 -040029#include <fcntl.h>
John Reck5bd537e2023-01-24 20:13:45 -050030#include <gui/TraceUtils.h>
31#include <hwui/Bitmap.h>
32#include <hwui/ImageDecoder.h>
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -050033#include <sys/stat.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040034
John Reck5bd537e2023-01-24 20:13:45 -050035#include "Bitmap.h"
36#include "BitmapFactory.h"
37#include "ByteBufferStreamAdaptor.h"
38#include "CreateJavaOutputStreamAdaptor.h"
39#include "Gainmap.h"
40#include "GraphicsJNI.h"
41#include "NinePatchPeeker.h"
42#include "Utils.h"
43
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040044using namespace android;
45
46static jclass gImageDecoder_class;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -050047static jclass gSize_class;
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040048static jclass gDecodeException_class;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040049static jclass gCanvas_class;
50static jmethodID gImageDecoder_constructorMethodID;
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -050051static jmethodID gImageDecoder_postProcessMethodID;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -050052static jmethodID gSize_constructorMethodID;
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040053static jmethodID gDecodeException_constructorMethodID;
Leon Scroggins IIIedf26d62018-01-09 16:55:24 -050054static jmethodID gCallback_onPartialImageMethodID;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040055static jmethodID gCanvas_constructorMethodID;
56static jmethodID gCanvas_releaseMethodID;
57
Leon Scroggins III753a56f2019-12-11 11:02:15 -050058// These need to stay in sync with ImageDecoder.java's Allocator constants.
59enum Allocator {
60 kDefault_Allocator = 0,
61 kSoftware_Allocator = 1,
62 kSharedMemory_Allocator = 2,
63 kHardware_Allocator = 3,
64};
65
66// These need to stay in sync with ImageDecoder.java's Error constants.
67enum Error {
68 kSourceException = 1,
69 kSourceIncomplete = 2,
70 kSourceMalformedData = 3,
71};
72
73// These need to stay in sync with PixelFormat.java's Format constants.
74enum PixelFormat {
75 kUnknown = 0,
76 kTranslucent = -3,
77 kOpaque = -1,
78};
79
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040080// Clear and return any pending exception for handling other than throwing directly.
81static jthrowable get_and_clear_exception(JNIEnv* env) {
82 jthrowable jexception = env->ExceptionOccurred();
83 if (jexception) {
84 env->ExceptionClear();
85 }
86 return jexception;
87}
88
89// Throw a new ImageDecoder.DecodeException. Returns null for convenience.
Leon Scroggins III753a56f2019-12-11 11:02:15 -050090static jobject throw_exception(JNIEnv* env, Error error, const char* msg,
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040091 jthrowable cause, jobject source) {
92 jstring jstr = nullptr;
93 if (msg) {
94 jstr = env->NewStringUTF(msg);
95 if (!jstr) {
96 // Out of memory.
97 return nullptr;
98 }
99 }
100 jthrowable exception = (jthrowable) env->NewObject(gDecodeException_class,
101 gDecodeException_constructorMethodID, error, jstr, cause, source);
102 // Only throw if not out of memory.
103 if (exception) {
104 env->Throw(exception);
105 }
106 return nullptr;
107}
108
Chong Zhangcba27922019-07-12 16:38:47 -0700109static jobject native_create(JNIEnv* env, std::unique_ptr<SkStream> stream,
110 jobject source, jboolean preferAnimation) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400111 if (!stream.get()) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500112 return throw_exception(env, kSourceMalformedData, "Failed to create a stream",
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400113 nullptr, source);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400114 }
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500115 sk_sp<NinePatchPeeker> peeker(new NinePatchPeeker);
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500116 SkCodec::Result result;
Chong Zhangcba27922019-07-12 16:38:47 -0700117 auto codec = SkCodec::MakeFromStream(
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500118 std::move(stream), &result, peeker.get(),
Chong Zhangcba27922019-07-12 16:38:47 -0700119 preferAnimation ? SkCodec::SelectionPolicy::kPreferAnimation
120 : SkCodec::SelectionPolicy::kPreferStillImage);
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400121 if (jthrowable jexception = get_and_clear_exception(env)) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500122 return throw_exception(env, kSourceException, "", jexception, source);
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400123 }
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500124 if (!codec) {
125 switch (result) {
126 case SkCodec::kIncompleteInput:
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500127 return throw_exception(env, kSourceIncomplete, "", nullptr, source);
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500128 default:
129 SkString msg;
130 msg.printf("Failed to create image decoder with message '%s'",
131 SkCodec::ResultToString(result));
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500132 return throw_exception(env, kSourceMalformedData, msg.c_str(),
Leon Scroggins IIIcf7294f2018-03-22 09:21:29 -0400133 nullptr, source);
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500134
Leon Scroggins III671cce22018-01-14 16:52:17 -0500135 }
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500136 }
137
Leon Scroggins III671cce22018-01-14 16:52:17 -0500138 const bool animated = codec->getFrameCount() > 1;
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400139 if (jthrowable jexception = get_and_clear_exception(env)) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500140 return throw_exception(env, kSourceException, "", jexception, source);
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400141 }
142
Leon Scroggins III139145b2020-12-17 15:43:54 -0500143 auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500144 if (!androidCodec.get()) {
145 return throw_exception(env, kSourceMalformedData, "", nullptr, source);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400146 }
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400147
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500148 const bool isNinePatch = peeker->mPatch != nullptr;
Leon Scroggins III368a7a52020-11-20 12:23:27 -0500149 ImageDecoder* decoder = new ImageDecoder(std::move(androidCodec), std::move(peeker),
150 SkCodec::kYes_ZeroInitialized);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400151 return env->NewObject(gImageDecoder_class, gImageDecoder_constructorMethodID,
Leon Scroggins III139145b2020-12-17 15:43:54 -0500152 reinterpret_cast<jlong>(decoder), decoder->width(), decoder->height(),
Leon Scroggins III7d940ba2018-04-04 16:19:33 -0400153 animated, isNinePatch);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400154}
155
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500156static jobject ImageDecoder_nCreateFd(JNIEnv* env, jobject /*clazz*/,
Leon Scroggins IIIc3fda892020-09-10 14:57:11 -0400157 jobject fileDescriptor, jlong length, jboolean preferAnimation, jobject source) {
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400158#ifndef __ANDROID__ // LayoutLib for Windows does not support F_DUPFD_CLOEXEC
159 return throw_exception(env, kSourceException, "Only supported on Android", nullptr, source);
160#else
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500161 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
162
163 struct stat fdStat;
164 if (fstat(descriptor, &fdStat) == -1) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500165 return throw_exception(env, kSourceMalformedData,
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400166 "broken file descriptor; fstat returned -1", nullptr, source);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500167 }
168
Nick Kralevich4b3a08c2019-01-28 10:39:10 -0800169 int dupDescriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, 0);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500170 FILE* file = fdopen(dupDescriptor, "r");
171 if (file == NULL) {
172 close(dupDescriptor);
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500173 return throw_exception(env, kSourceMalformedData, "Could not open file",
Leon Scroggins IIIcf7294f2018-03-22 09:21:29 -0400174 nullptr, source);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500175 }
Leon Scroggins III0c699ad2018-05-07 16:20:13 -0400176
Leon Scroggins IIIc3fda892020-09-10 14:57:11 -0400177 std::unique_ptr<SkFILEStream> fileStream;
178 if (length == -1) {
179 // -1 corresponds to AssetFileDescriptor.UNKNOWN_LENGTH. Pass no length
180 // so SkFILEStream will figure out the size of the file on its own.
181 fileStream.reset(new SkFILEStream(file));
182 } else {
183 fileStream.reset(new SkFILEStream(file, length));
184 }
Chong Zhangcba27922019-07-12 16:38:47 -0700185 return native_create(env, std::move(fileStream), source, preferAnimation);
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400186#endif
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500187}
188
189static jobject ImageDecoder_nCreateInputStream(JNIEnv* env, jobject /*clazz*/,
Chong Zhangcba27922019-07-12 16:38:47 -0700190 jobject is, jbyteArray storage, jboolean preferAnimation, jobject source) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500191 std::unique_ptr<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage, false));
192
193 if (!stream.get()) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500194 return throw_exception(env, kSourceMalformedData, "Failed to create a stream",
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400195 nullptr, source);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500196 }
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400197
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500198 std::unique_ptr<SkStream> bufferedStream(
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400199 skia::FrontBufferedStream::Make(std::move(stream), SkCodec::MinBufferedBytesNeeded()));
Chong Zhangcba27922019-07-12 16:38:47 -0700200 return native_create(env, std::move(bufferedStream), source, preferAnimation);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500201}
202
Chong Zhangcba27922019-07-12 16:38:47 -0700203static jobject ImageDecoder_nCreateAsset(JNIEnv* env, jobject /*clazz*/,
204 jlong assetPtr, jboolean preferAnimation, jobject source) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400205 Asset* asset = reinterpret_cast<Asset*>(assetPtr);
206 std::unique_ptr<SkStream> stream(new AssetStreamAdaptor(asset));
Chong Zhangcba27922019-07-12 16:38:47 -0700207 return native_create(env, std::move(stream), source, preferAnimation);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400208}
209
Chong Zhangcba27922019-07-12 16:38:47 -0700210static jobject ImageDecoder_nCreateByteBuffer(JNIEnv* env, jobject /*clazz*/,
211 jobject jbyteBuffer, jint initialPosition, jint limit,
212 jboolean preferAnimation, jobject source) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400213 std::unique_ptr<SkStream> stream = CreateByteBufferStreamAdaptor(env, jbyteBuffer,
214 initialPosition, limit);
215 if (!stream) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500216 return throw_exception(env, kSourceMalformedData, "Failed to read ByteBuffer",
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400217 nullptr, source);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400218 }
Chong Zhangcba27922019-07-12 16:38:47 -0700219 return native_create(env, std::move(stream), source, preferAnimation);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400220}
221
Chong Zhangcba27922019-07-12 16:38:47 -0700222static jobject ImageDecoder_nCreateByteArray(JNIEnv* env, jobject /*clazz*/,
223 jbyteArray byteArray, jint offset, jint length,
224 jboolean preferAnimation, jobject source) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400225 std::unique_ptr<SkStream> stream(CreateByteArrayStreamAdaptor(env, byteArray, offset, length));
Chong Zhangcba27922019-07-12 16:38:47 -0700226 return native_create(env, std::move(stream), source, preferAnimation);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400227}
228
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500229jint postProcessAndRelease(JNIEnv* env, jobject jimageDecoder, std::unique_ptr<Canvas> canvas) {
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -0500230 jobject jcanvas = env->NewObject(gCanvas_class, gCanvas_constructorMethodID,
231 reinterpret_cast<jlong>(canvas.get()));
232 if (!jcanvas) {
233 doThrowOOME(env, "Failed to create Java Canvas for PostProcess!");
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500234 return kUnknown;
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -0500235 }
236
237 // jcanvas now owns canvas.
238 canvas.release();
239
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500240 return env->CallIntMethod(jimageDecoder, gImageDecoder_postProcessMethodID, jcanvas);
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -0500241}
242
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400243static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400244 jobject jdecoder, jboolean jpostProcess,
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500245 jint targetWidth, jint targetHeight, jobject jsubset,
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400246 jboolean requireMutable, jint allocator,
247 jboolean requireUnpremul, jboolean preferRamOverQuality,
Leon Scroggins III28f3943f2019-02-19 11:03:44 -0500248 jboolean asAlphaMask, jlong colorSpaceHandle,
249 jboolean extended) {
John Reck5bd537e2023-01-24 20:13:45 -0500250 ATRACE_CALL();
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400251 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500252 if (!decoder->setTargetSize(targetWidth, targetHeight)) {
253 doThrowISE(env, "Could not scale to target size!");
254 return nullptr;
255 }
Leon Scroggins III1ade46d2020-01-15 05:41:06 -0500256 if (requireUnpremul && !decoder->setUnpremultipliedRequired(true)) {
Leon Scroggins IIIea978db2018-01-13 11:40:42 -0500257 doThrowISE(env, "Cannot scale unpremultiplied pixels!");
258 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400259 }
260
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400261 SkColorType colorType = kN32_SkColorType;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500262 if (asAlphaMask && decoder->gray()) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400263 // We have to trick Skia to decode this to a single channel.
264 colorType = kGray_8_SkColorType;
265 } else if (preferRamOverQuality) {
266 // FIXME: The post-process might add alpha, which would make a 565
267 // result incorrect. If we call the postProcess before now and record
268 // to a picture, we can know whether alpha was added, and if not, we
269 // can still use 565.
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500270 if (decoder->opaque() && !jpostProcess) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400271 // If the final result will be hardware, decoding to 565 and then
272 // uploading to the gpu as 8888 will not save memory. This still
273 // may save us from using F16, but do not go down to 565.
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500274 if (allocator != kHardware_Allocator &&
275 (allocator != kDefault_Allocator || requireMutable)) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400276 colorType = kRGB_565_SkColorType;
277 }
278 }
279 // Otherwise, stick with N32
Leon Scroggins III28f3943f2019-02-19 11:03:44 -0500280 } else if (extended) {
281 colorType = kRGBA_F16_SkColorType;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400282 } else {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500283 colorType = decoder->mCodec->computeOutputColorType(colorType);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400284 }
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500285
286 const bool isHardware = !requireMutable
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500287 && (allocator == kDefault_Allocator ||
288 allocator == kHardware_Allocator)
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500289 && colorType != kGray_8_SkColorType;
290
291 if (colorType == kRGBA_F16_SkColorType && isHardware &&
292 !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
293 colorType = kN32_SkColorType;
294 }
295
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500296 if (!decoder->setOutColorType(colorType)) {
297 doThrowISE(env, "Failed to set out color type!");
298 return nullptr;
299 }
300
301 {
302 sk_sp<SkColorSpace> colorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
303 colorSpace = decoder->mCodec->computeOutputColorSpace(colorType, colorSpace);
304 decoder->setOutColorSpace(std::move(colorSpace));
305 }
306
307 if (jsubset) {
308 SkIRect subset;
309 GraphicsJNI::jrect_to_irect(env, jsubset, &subset);
310 if (!decoder->setCropRect(&subset)) {
311 doThrowISE(env, "Invalid crop rect!");
312 return nullptr;
313 }
314 }
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400315
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500316 SkImageInfo bitmapInfo = decoder->getOutputInfo();
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400317 if (asAlphaMask && colorType == kGray_8_SkColorType) {
318 bitmapInfo = bitmapInfo.makeColorType(kAlpha_8_SkColorType);
319 }
Leon Scroggins III1ade46d2020-01-15 05:41:06 -0500320
321 SkBitmap bm;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400322 if (!bm.setInfo(bitmapInfo)) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500323 doThrowIOE(env, "Failed to setInfo properly");
324 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400325 }
326
327 sk_sp<Bitmap> nativeBitmap;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500328 if (allocator == kSharedMemory_Allocator) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400329 nativeBitmap = Bitmap::allocateAshmemBitmap(&bm);
330 } else {
331 nativeBitmap = Bitmap::allocateHeapBitmap(&bm);
332 }
333 if (!nativeBitmap) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500334 SkString msg;
335 msg.printf("OOM allocating Bitmap with dimensions %i x %i",
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500336 bitmapInfo.width(), bitmapInfo.height());
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500337 doThrowOOME(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400338 return nullptr;
339 }
340
John Reck5bd537e2023-01-24 20:13:45 -0500341 ATRACE_FORMAT("Decoding %dx%d bitmap", bitmapInfo.width(), bitmapInfo.height());
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500342 SkCodec::Result result = decoder->decode(bm.getPixels(), bm.rowBytes());
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400343 jthrowable jexception = get_and_clear_exception(env);
John Reck5bd537e2023-01-24 20:13:45 -0500344 int onPartialImageError = jexception ? kSourceException : 0; // No error.
345
346 // Only attempt to extract the gainmap if we're not post-processing, as we can't automatically
347 // mimic that to the gainmap and expect it to be meaningful. And also don't extract the gainmap
348 // if we're prioritizing RAM over quality, since the gainmap improves quality at the
349 // cost of RAM
350 if (result == SkCodec::kSuccess && !jpostProcess && !preferRamOverQuality) {
351 // The gainmap costs RAM to improve quality, so skip this if we're prioritizing RAM instead
352 result = decoder->extractGainmap(nativeBitmap.get());
353 jexception = get_and_clear_exception(env);
354 }
355
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400356 switch (result) {
357 case SkCodec::kSuccess:
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500358 // Ignore the exception, since the decode was successful anyway.
359 jexception = nullptr;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500360 onPartialImageError = 0;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400361 break;
362 case SkCodec::kIncompleteInput:
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500363 if (!jexception) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500364 onPartialImageError = kSourceIncomplete;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400365 }
366 break;
367 case SkCodec::kErrorInInput:
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500368 if (!jexception) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500369 onPartialImageError = kSourceMalformedData;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400370 }
371 break;
372 default:
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500373 SkString msg;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500374 msg.printf("getPixels failed with error %s", SkCodec::ResultToString(result));
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500375 doThrowIOE(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400376 return nullptr;
377 }
378
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400379 if (onPartialImageError) {
380 env->CallVoidMethod(jdecoder, gCallback_onPartialImageMethodID, onPartialImageError,
381 jexception);
Leon Scroggins IIIedf26d62018-01-09 16:55:24 -0500382 if (env->ExceptionCheck()) {
383 return nullptr;
384 }
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400385 }
386
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400387 jbyteArray ninePatchChunk = nullptr;
388 jobject ninePatchInsets = nullptr;
389
390 // Ignore ninepatch when post-processing.
391 if (!jpostProcess) {
392 // FIXME: Share more code with BitmapFactory.cpp.
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500393 auto* peeker = reinterpret_cast<NinePatchPeeker*>(decoder->mPeeker.get());
394 if (peeker->mPatch != nullptr) {
395 size_t ninePatchArraySize = peeker->mPatch->serializedSize();
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400396 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
397 if (ninePatchChunk == nullptr) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500398 doThrowOOME(env, "Failed to allocate nine patch chunk.");
399 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400400 }
401
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500402 env->SetByteArrayRegion(ninePatchChunk, 0, peeker->mPatchSize,
403 reinterpret_cast<jbyte*>(peeker->mPatch));
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400404 }
405
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500406 if (peeker->mHasInsets) {
407 ninePatchInsets = peeker->createNinePatchInsets(env, 1.0f);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400408 if (ninePatchInsets == nullptr) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500409 doThrowOOME(env, "Failed to allocate nine patch insets.");
410 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400411 }
412 }
413 }
414
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400415 if (jpostProcess) {
416 std::unique_ptr<Canvas> canvas(Canvas::create_canvas(bm));
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400417
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400418 jint pixelFormat = postProcessAndRelease(env, jdecoder, std::move(canvas));
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400419 if (env->ExceptionCheck()) {
420 return nullptr;
421 }
422
423 SkAlphaType newAlphaType = bm.alphaType();
424 switch (pixelFormat) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500425 case kUnknown:
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400426 break;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500427 case kTranslucent:
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400428 newAlphaType = kPremul_SkAlphaType;
429 break;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500430 case kOpaque:
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400431 newAlphaType = kOpaque_SkAlphaType;
432 break;
433 default:
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500434 SkString msg;
435 msg.printf("invalid return from postProcess: %i", pixelFormat);
436 doThrowIAE(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400437 return nullptr;
438 }
439
440 if (newAlphaType != bm.alphaType()) {
441 if (!bm.setAlphaType(newAlphaType)) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500442 SkString msg;
443 msg.printf("incompatible return from postProcess: %i", pixelFormat);
444 doThrowIAE(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400445 return nullptr;
446 }
447 nativeBitmap->setAlphaType(newAlphaType);
448 }
449 }
450
451 int bitmapCreateFlags = 0x0;
452 if (!requireUnpremul) {
453 // Even if the image is opaque, setting this flag means that
454 // if alpha is added (e.g. by PostProcess), it will be marked as
455 // premultiplied.
456 bitmapCreateFlags |= bitmap::kBitmapCreateFlag_Premultiplied;
457 }
458
459 if (requireMutable) {
460 bitmapCreateFlags |= bitmap::kBitmapCreateFlag_Mutable;
461 } else {
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500462 if (isHardware) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400463 sk_sp<Bitmap> hwBitmap = Bitmap::allocateHardwareBitmap(bm);
464 if (hwBitmap) {
465 hwBitmap->setImmutable();
John Reck5bd537e2023-01-24 20:13:45 -0500466 if (nativeBitmap->hasGainmap()) {
467 // TODO: Also convert to a HW gainmap image
468 hwBitmap->setGainmap(nativeBitmap->gainmap());
469 }
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400470 return bitmap::createBitmap(env, hwBitmap.release(), bitmapCreateFlags,
471 ninePatchChunk, ninePatchInsets);
472 }
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500473 if (allocator == kHardware_Allocator) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500474 doThrowOOME(env, "failed to allocate hardware Bitmap!");
475 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400476 }
477 // If we failed to create a hardware bitmap, go ahead and create a
478 // software one.
479 }
480
481 nativeBitmap->setImmutable();
482 }
483 return bitmap::createBitmap(env, nativeBitmap.release(), bitmapCreateFlags, ninePatchChunk,
484 ninePatchInsets);
485}
486
487static jobject ImageDecoder_nGetSampledSize(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
488 jint sampleSize) {
489 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III5a5c2ce2021-01-15 14:09:13 -0500490 SkISize size = decoder->getSampledDimensions(sampleSize);
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500491 return env->NewObject(gSize_class, gSize_constructorMethodID, size.width(), size.height());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400492}
493
494static void ImageDecoder_nGetPadding(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
495 jobject outPadding) {
496 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500497 reinterpret_cast<NinePatchPeeker*>(decoder->mPeeker.get())->getPadding(env, outPadding);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400498}
499
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500500static void ImageDecoder_nClose(JNIEnv* /*env*/, jobject /*clazz*/, jlong nativePtr) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400501 delete reinterpret_cast<ImageDecoder*>(nativePtr);
502}
503
Leon Scroggins III1fad09d2017-12-22 12:54:20 -0500504static jstring ImageDecoder_nGetMimeType(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
505 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III407b5442019-11-22 17:10:20 -0500506 return getMimeTypeAsJavaString(env, decoder->mCodec->getEncodedFormat());
Leon Scroggins III1fad09d2017-12-22 12:54:20 -0500507}
508
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400509static jobject ImageDecoder_nGetColorSpace(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
510 auto* codec = reinterpret_cast<ImageDecoder*>(nativePtr)->mCodec.get();
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500511 auto colorType = codec->computeOutputColorType(kN32_SkColorType);
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400512 sk_sp<SkColorSpace> colorSpace = codec->computeOutputColorSpace(colorType);
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500513 return GraphicsJNI::getColorSpace(env, colorSpace.get(), colorType);
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400514}
515
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400516static const JNINativeMethod gImageDecoderMethods[] = {
Chong Zhangcba27922019-07-12 16:38:47 -0700517 { "nCreate", "(JZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateAsset },
518 { "nCreate", "(Ljava/nio/ByteBuffer;IIZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateByteBuffer },
519 { "nCreate", "([BIIZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateByteArray },
520 { "nCreate", "(Ljava/io/InputStream;[BZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateInputStream },
Leon Scroggins IIIc3fda892020-09-10 14:57:11 -0400521 { "nCreate", "(Ljava/io/FileDescriptor;JZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateFd },
Leon Scroggins III28f3943f2019-02-19 11:03:44 -0500522 { "nDecodeBitmap", "(JLandroid/graphics/ImageDecoder;ZIILandroid/graphics/Rect;ZIZZZJZ)Landroid/graphics/Bitmap;",
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400523 (void*) ImageDecoder_nDecodeBitmap },
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500524 { "nGetSampledSize","(JI)Landroid/util/Size;", (void*) ImageDecoder_nGetSampledSize },
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400525 { "nGetPadding", "(JLandroid/graphics/Rect;)V", (void*) ImageDecoder_nGetPadding },
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500526 { "nClose", "(J)V", (void*) ImageDecoder_nClose},
Leon Scroggins III1fad09d2017-12-22 12:54:20 -0500527 { "nGetMimeType", "(J)Ljava/lang/String;", (void*) ImageDecoder_nGetMimeType },
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400528 { "nGetColorSpace", "(J)Landroid/graphics/ColorSpace;", (void*) ImageDecoder_nGetColorSpace },
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400529};
530
531int register_android_graphics_ImageDecoder(JNIEnv* env) {
532 gImageDecoder_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/ImageDecoder"));
Leon Scroggins III7d940ba2018-04-04 16:19:33 -0400533 gImageDecoder_constructorMethodID = GetMethodIDOrDie(env, gImageDecoder_class, "<init>", "(JIIZZ)V");
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500534 gImageDecoder_postProcessMethodID = GetMethodIDOrDie(env, gImageDecoder_class, "postProcessAndRelease", "(Landroid/graphics/Canvas;)I");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400535
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500536 gSize_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/util/Size"));
537 gSize_constructorMethodID = GetMethodIDOrDie(env, gSize_class, "<init>", "(II)V");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400538
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400539 gDecodeException_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/ImageDecoder$DecodeException"));
540 gDecodeException_constructorMethodID = GetMethodIDOrDie(env, gDecodeException_class, "<init>", "(ILjava/lang/String;Ljava/lang/Throwable;Landroid/graphics/ImageDecoder$Source;)V");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400541
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400542 gCallback_onPartialImageMethodID = GetMethodIDOrDie(env, gImageDecoder_class, "onPartialImage", "(ILjava/lang/Throwable;)V");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400543
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400544 gCanvas_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/Canvas"));
545 gCanvas_constructorMethodID = GetMethodIDOrDie(env, gCanvas_class, "<init>", "(J)V");
546 gCanvas_releaseMethodID = GetMethodIDOrDie(env, gCanvas_class, "release", "()V");
547
548 return android::RegisterMethodsOrDie(env, "android/graphics/ImageDecoder", gImageDecoderMethods,
549 NELEM(gImageDecoderMethods));
550}