blob: fda7080f286431249eaa7070e3d2da6c336edf57 [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>
Kevin Lubick08409e22023-02-14 14:29:25 +000021#include <SkAlphaType.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040022#include <SkAndroidCodec.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050023#include <SkBitmap.h>
Kevin Lubick08409e22023-02-14 14:29:25 +000024#include <SkCodec.h>
25#include <SkCodecAnimation.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050026#include <SkColorSpace.h>
Kevin Lubick08409e22023-02-14 14:29:25 +000027#include <SkColorType.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050028#include <SkImageInfo.h>
29#include <SkRect.h>
Kevin Lubick08409e22023-02-14 14:29:25 +000030#include <SkSize.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040031#include <SkStream.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050032#include <SkString.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040033#include <androidfw/Asset.h>
Derek Sollenbergerc5882c42019-10-25 11:11:32 -040034#include <fcntl.h>
John Reck5bd537e2023-01-24 20:13:45 -050035#include <gui/TraceUtils.h>
36#include <hwui/Bitmap.h>
37#include <hwui/ImageDecoder.h>
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -050038#include <sys/stat.h>
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040039
John Reck5bd537e2023-01-24 20:13:45 -050040#include "Bitmap.h"
41#include "BitmapFactory.h"
42#include "ByteBufferStreamAdaptor.h"
43#include "CreateJavaOutputStreamAdaptor.h"
44#include "Gainmap.h"
45#include "GraphicsJNI.h"
46#include "NinePatchPeeker.h"
47#include "Utils.h"
48
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040049using namespace android;
50
51static jclass gImageDecoder_class;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -050052static jclass gSize_class;
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040053static jclass gDecodeException_class;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040054static jclass gCanvas_class;
55static jmethodID gImageDecoder_constructorMethodID;
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -050056static jmethodID gImageDecoder_postProcessMethodID;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -050057static jmethodID gSize_constructorMethodID;
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040058static jmethodID gDecodeException_constructorMethodID;
Leon Scroggins IIIedf26d62018-01-09 16:55:24 -050059static jmethodID gCallback_onPartialImageMethodID;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -040060static jmethodID gCanvas_constructorMethodID;
61static jmethodID gCanvas_releaseMethodID;
62
Leon Scroggins III753a56f2019-12-11 11:02:15 -050063// These need to stay in sync with ImageDecoder.java's Allocator constants.
64enum Allocator {
65 kDefault_Allocator = 0,
66 kSoftware_Allocator = 1,
67 kSharedMemory_Allocator = 2,
68 kHardware_Allocator = 3,
69};
70
71// These need to stay in sync with ImageDecoder.java's Error constants.
72enum Error {
73 kSourceException = 1,
74 kSourceIncomplete = 2,
75 kSourceMalformedData = 3,
76};
77
78// These need to stay in sync with PixelFormat.java's Format constants.
79enum PixelFormat {
80 kUnknown = 0,
81 kTranslucent = -3,
82 kOpaque = -1,
83};
84
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040085// Clear and return any pending exception for handling other than throwing directly.
86static jthrowable get_and_clear_exception(JNIEnv* env) {
87 jthrowable jexception = env->ExceptionOccurred();
88 if (jexception) {
89 env->ExceptionClear();
90 }
91 return jexception;
92}
93
94// Throw a new ImageDecoder.DecodeException. Returns null for convenience.
Leon Scroggins III753a56f2019-12-11 11:02:15 -050095static jobject throw_exception(JNIEnv* env, Error error, const char* msg,
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -040096 jthrowable cause, jobject source) {
97 jstring jstr = nullptr;
98 if (msg) {
99 jstr = env->NewStringUTF(msg);
100 if (!jstr) {
101 // Out of memory.
102 return nullptr;
103 }
104 }
105 jthrowable exception = (jthrowable) env->NewObject(gDecodeException_class,
106 gDecodeException_constructorMethodID, error, jstr, cause, source);
107 // Only throw if not out of memory.
108 if (exception) {
109 env->Throw(exception);
110 }
111 return nullptr;
112}
113
Chong Zhangcba27922019-07-12 16:38:47 -0700114static jobject native_create(JNIEnv* env, std::unique_ptr<SkStream> stream,
115 jobject source, jboolean preferAnimation) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400116 if (!stream.get()) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500117 return throw_exception(env, kSourceMalformedData, "Failed to create a stream",
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400118 nullptr, source);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400119 }
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500120 sk_sp<NinePatchPeeker> peeker(new NinePatchPeeker);
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500121 SkCodec::Result result;
Chong Zhangcba27922019-07-12 16:38:47 -0700122 auto codec = SkCodec::MakeFromStream(
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500123 std::move(stream), &result, peeker.get(),
Chong Zhangcba27922019-07-12 16:38:47 -0700124 preferAnimation ? SkCodec::SelectionPolicy::kPreferAnimation
125 : SkCodec::SelectionPolicy::kPreferStillImage);
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400126 if (jthrowable jexception = get_and_clear_exception(env)) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500127 return throw_exception(env, kSourceException, "", jexception, source);
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400128 }
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500129 if (!codec) {
130 switch (result) {
131 case SkCodec::kIncompleteInput:
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500132 return throw_exception(env, kSourceIncomplete, "", nullptr, source);
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500133 default:
134 SkString msg;
135 msg.printf("Failed to create image decoder with message '%s'",
136 SkCodec::ResultToString(result));
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500137 return throw_exception(env, kSourceMalformedData, msg.c_str(),
Leon Scroggins IIIcf7294f2018-03-22 09:21:29 -0400138 nullptr, source);
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500139
Leon Scroggins III671cce22018-01-14 16:52:17 -0500140 }
Leon Scroggins IIIc782ad82018-01-14 10:50:45 -0500141 }
142
Leon Scroggins III671cce22018-01-14 16:52:17 -0500143 const bool animated = codec->getFrameCount() > 1;
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400144 if (jthrowable jexception = get_and_clear_exception(env)) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500145 return throw_exception(env, kSourceException, "", jexception, source);
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400146 }
147
Leon Scroggins III139145b2020-12-17 15:43:54 -0500148 auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500149 if (!androidCodec.get()) {
150 return throw_exception(env, kSourceMalformedData, "", nullptr, source);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400151 }
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400152
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500153 const bool isNinePatch = peeker->mPatch != nullptr;
Leon Scroggins III368a7a52020-11-20 12:23:27 -0500154 ImageDecoder* decoder = new ImageDecoder(std::move(androidCodec), std::move(peeker),
155 SkCodec::kYes_ZeroInitialized);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400156 return env->NewObject(gImageDecoder_class, gImageDecoder_constructorMethodID,
Leon Scroggins III139145b2020-12-17 15:43:54 -0500157 reinterpret_cast<jlong>(decoder), decoder->width(), decoder->height(),
Leon Scroggins III7d940ba2018-04-04 16:19:33 -0400158 animated, isNinePatch);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400159}
160
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500161static jobject ImageDecoder_nCreateFd(JNIEnv* env, jobject /*clazz*/,
Leon Scroggins IIIc3fda892020-09-10 14:57:11 -0400162 jobject fileDescriptor, jlong length, jboolean preferAnimation, jobject source) {
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400163#ifndef __ANDROID__ // LayoutLib for Windows does not support F_DUPFD_CLOEXEC
164 return throw_exception(env, kSourceException, "Only supported on Android", nullptr, source);
165#else
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500166 int descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);
167
168 struct stat fdStat;
169 if (fstat(descriptor, &fdStat) == -1) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500170 return throw_exception(env, kSourceMalformedData,
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400171 "broken file descriptor; fstat returned -1", nullptr, source);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500172 }
173
Nick Kralevich4b3a08c2019-01-28 10:39:10 -0800174 int dupDescriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, 0);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500175 FILE* file = fdopen(dupDescriptor, "r");
176 if (file == NULL) {
177 close(dupDescriptor);
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500178 return throw_exception(env, kSourceMalformedData, "Could not open file",
Leon Scroggins IIIcf7294f2018-03-22 09:21:29 -0400179 nullptr, source);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500180 }
Leon Scroggins III0c699ad2018-05-07 16:20:13 -0400181
Leon Scroggins IIIc3fda892020-09-10 14:57:11 -0400182 std::unique_ptr<SkFILEStream> fileStream;
183 if (length == -1) {
184 // -1 corresponds to AssetFileDescriptor.UNKNOWN_LENGTH. Pass no length
185 // so SkFILEStream will figure out the size of the file on its own.
186 fileStream.reset(new SkFILEStream(file));
187 } else {
188 fileStream.reset(new SkFILEStream(file, length));
189 }
Chong Zhangcba27922019-07-12 16:38:47 -0700190 return native_create(env, std::move(fileStream), source, preferAnimation);
Derek Sollenbergerc5882c42019-10-25 11:11:32 -0400191#endif
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500192}
193
194static jobject ImageDecoder_nCreateInputStream(JNIEnv* env, jobject /*clazz*/,
Chong Zhangcba27922019-07-12 16:38:47 -0700195 jobject is, jbyteArray storage, jboolean preferAnimation, jobject source) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500196 std::unique_ptr<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage, false));
197
198 if (!stream.get()) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500199 return throw_exception(env, kSourceMalformedData, "Failed to create a stream",
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400200 nullptr, source);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500201 }
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400202
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500203 std::unique_ptr<SkStream> bufferedStream(
Leon Scroggins III2bcdf6f2020-04-21 14:08:32 -0400204 skia::FrontBufferedStream::Make(std::move(stream), SkCodec::MinBufferedBytesNeeded()));
Chong Zhangcba27922019-07-12 16:38:47 -0700205 return native_create(env, std::move(bufferedStream), source, preferAnimation);
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500206}
207
Chong Zhangcba27922019-07-12 16:38:47 -0700208static jobject ImageDecoder_nCreateAsset(JNIEnv* env, jobject /*clazz*/,
209 jlong assetPtr, jboolean preferAnimation, jobject source) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400210 Asset* asset = reinterpret_cast<Asset*>(assetPtr);
211 std::unique_ptr<SkStream> stream(new AssetStreamAdaptor(asset));
Chong Zhangcba27922019-07-12 16:38:47 -0700212 return native_create(env, std::move(stream), source, preferAnimation);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400213}
214
Chong Zhangcba27922019-07-12 16:38:47 -0700215static jobject ImageDecoder_nCreateByteBuffer(JNIEnv* env, jobject /*clazz*/,
216 jobject jbyteBuffer, jint initialPosition, jint limit,
217 jboolean preferAnimation, jobject source) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400218 std::unique_ptr<SkStream> stream = CreateByteBufferStreamAdaptor(env, jbyteBuffer,
219 initialPosition, limit);
220 if (!stream) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500221 return throw_exception(env, kSourceMalformedData, "Failed to read ByteBuffer",
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400222 nullptr, source);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400223 }
Chong Zhangcba27922019-07-12 16:38:47 -0700224 return native_create(env, std::move(stream), source, preferAnimation);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400225}
226
Chong Zhangcba27922019-07-12 16:38:47 -0700227static jobject ImageDecoder_nCreateByteArray(JNIEnv* env, jobject /*clazz*/,
228 jbyteArray byteArray, jint offset, jint length,
229 jboolean preferAnimation, jobject source) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400230 std::unique_ptr<SkStream> stream(CreateByteArrayStreamAdaptor(env, byteArray, offset, length));
Chong Zhangcba27922019-07-12 16:38:47 -0700231 return native_create(env, std::move(stream), source, preferAnimation);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400232}
233
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500234jint postProcessAndRelease(JNIEnv* env, jobject jimageDecoder, std::unique_ptr<Canvas> canvas) {
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -0500235 jobject jcanvas = env->NewObject(gCanvas_class, gCanvas_constructorMethodID,
236 reinterpret_cast<jlong>(canvas.get()));
237 if (!jcanvas) {
238 doThrowOOME(env, "Failed to create Java Canvas for PostProcess!");
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500239 return kUnknown;
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -0500240 }
241
242 // jcanvas now owns canvas.
243 canvas.release();
244
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500245 return env->CallIntMethod(jimageDecoder, gImageDecoder_postProcessMethodID, jcanvas);
Leon Scroggins III8c9d8f22018-01-14 14:41:46 -0500246}
247
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400248static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400249 jobject jdecoder, jboolean jpostProcess,
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500250 jint targetWidth, jint targetHeight, jobject jsubset,
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400251 jboolean requireMutable, jint allocator,
252 jboolean requireUnpremul, jboolean preferRamOverQuality,
Leon Scroggins III28f3943f2019-02-19 11:03:44 -0500253 jboolean asAlphaMask, jlong colorSpaceHandle,
254 jboolean extended) {
John Reck5bd537e2023-01-24 20:13:45 -0500255 ATRACE_CALL();
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400256 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500257 if (!decoder->setTargetSize(targetWidth, targetHeight)) {
258 doThrowISE(env, "Could not scale to target size!");
259 return nullptr;
260 }
Leon Scroggins III1ade46d2020-01-15 05:41:06 -0500261 if (requireUnpremul && !decoder->setUnpremultipliedRequired(true)) {
Leon Scroggins IIIea978db2018-01-13 11:40:42 -0500262 doThrowISE(env, "Cannot scale unpremultiplied pixels!");
263 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400264 }
265
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400266 SkColorType colorType = kN32_SkColorType;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500267 if (asAlphaMask && decoder->gray()) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400268 // We have to trick Skia to decode this to a single channel.
269 colorType = kGray_8_SkColorType;
270 } else if (preferRamOverQuality) {
271 // FIXME: The post-process might add alpha, which would make a 565
272 // result incorrect. If we call the postProcess before now and record
273 // to a picture, we can know whether alpha was added, and if not, we
274 // can still use 565.
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500275 if (decoder->opaque() && !jpostProcess) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400276 // If the final result will be hardware, decoding to 565 and then
277 // uploading to the gpu as 8888 will not save memory. This still
278 // may save us from using F16, but do not go down to 565.
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500279 if (allocator != kHardware_Allocator &&
280 (allocator != kDefault_Allocator || requireMutable)) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400281 colorType = kRGB_565_SkColorType;
282 }
283 }
284 // Otherwise, stick with N32
Leon Scroggins III28f3943f2019-02-19 11:03:44 -0500285 } else if (extended) {
286 colorType = kRGBA_F16_SkColorType;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400287 } else {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500288 colorType = decoder->mCodec->computeOutputColorType(colorType);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400289 }
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500290
291 const bool isHardware = !requireMutable
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500292 && (allocator == kDefault_Allocator ||
293 allocator == kHardware_Allocator)
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500294 && colorType != kGray_8_SkColorType;
295
296 if (colorType == kRGBA_F16_SkColorType && isHardware &&
297 !uirenderer::HardwareBitmapUploader::hasFP16Support()) {
298 colorType = kN32_SkColorType;
299 }
300
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500301 if (!decoder->setOutColorType(colorType)) {
302 doThrowISE(env, "Failed to set out color type!");
303 return nullptr;
304 }
305
306 {
307 sk_sp<SkColorSpace> colorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
308 colorSpace = decoder->mCodec->computeOutputColorSpace(colorType, colorSpace);
309 decoder->setOutColorSpace(std::move(colorSpace));
310 }
311
312 if (jsubset) {
313 SkIRect subset;
314 GraphicsJNI::jrect_to_irect(env, jsubset, &subset);
315 if (!decoder->setCropRect(&subset)) {
316 doThrowISE(env, "Invalid crop rect!");
317 return nullptr;
318 }
319 }
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400320
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500321 SkImageInfo bitmapInfo = decoder->getOutputInfo();
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400322 if (asAlphaMask && colorType == kGray_8_SkColorType) {
323 bitmapInfo = bitmapInfo.makeColorType(kAlpha_8_SkColorType);
324 }
Leon Scroggins III1ade46d2020-01-15 05:41:06 -0500325
326 SkBitmap bm;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400327 if (!bm.setInfo(bitmapInfo)) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500328 doThrowIOE(env, "Failed to setInfo properly");
329 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400330 }
331
332 sk_sp<Bitmap> nativeBitmap;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500333 if (allocator == kSharedMemory_Allocator) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400334 nativeBitmap = Bitmap::allocateAshmemBitmap(&bm);
335 } else {
336 nativeBitmap = Bitmap::allocateHeapBitmap(&bm);
337 }
338 if (!nativeBitmap) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500339 SkString msg;
340 msg.printf("OOM allocating Bitmap with dimensions %i x %i",
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500341 bitmapInfo.width(), bitmapInfo.height());
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500342 doThrowOOME(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400343 return nullptr;
344 }
345
John Reck5bd537e2023-01-24 20:13:45 -0500346 ATRACE_FORMAT("Decoding %dx%d bitmap", bitmapInfo.width(), bitmapInfo.height());
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500347 SkCodec::Result result = decoder->decode(bm.getPixels(), bm.rowBytes());
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400348 jthrowable jexception = get_and_clear_exception(env);
John Reck5bd537e2023-01-24 20:13:45 -0500349 int onPartialImageError = jexception ? kSourceException : 0; // No error.
350
351 // Only attempt to extract the gainmap if we're not post-processing, as we can't automatically
352 // mimic that to the gainmap and expect it to be meaningful. And also don't extract the gainmap
353 // if we're prioritizing RAM over quality, since the gainmap improves quality at the
354 // cost of RAM
355 if (result == SkCodec::kSuccess && !jpostProcess && !preferRamOverQuality) {
356 // The gainmap costs RAM to improve quality, so skip this if we're prioritizing RAM instead
357 result = decoder->extractGainmap(nativeBitmap.get());
358 jexception = get_and_clear_exception(env);
359 }
360
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400361 switch (result) {
362 case SkCodec::kSuccess:
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500363 // Ignore the exception, since the decode was successful anyway.
364 jexception = nullptr;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500365 onPartialImageError = 0;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400366 break;
367 case SkCodec::kIncompleteInput:
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500368 if (!jexception) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500369 onPartialImageError = kSourceIncomplete;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400370 }
371 break;
372 case SkCodec::kErrorInInput:
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500373 if (!jexception) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500374 onPartialImageError = kSourceMalformedData;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400375 }
376 break;
377 default:
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500378 SkString msg;
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500379 msg.printf("getPixels failed with error %s", SkCodec::ResultToString(result));
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500380 doThrowIOE(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400381 return nullptr;
382 }
383
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400384 if (onPartialImageError) {
385 env->CallVoidMethod(jdecoder, gCallback_onPartialImageMethodID, onPartialImageError,
386 jexception);
Leon Scroggins IIIedf26d62018-01-09 16:55:24 -0500387 if (env->ExceptionCheck()) {
388 return nullptr;
389 }
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400390 }
391
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400392 jbyteArray ninePatchChunk = nullptr;
393 jobject ninePatchInsets = nullptr;
394
395 // Ignore ninepatch when post-processing.
396 if (!jpostProcess) {
397 // FIXME: Share more code with BitmapFactory.cpp.
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500398 auto* peeker = reinterpret_cast<NinePatchPeeker*>(decoder->mPeeker.get());
399 if (peeker->mPatch != nullptr) {
400 size_t ninePatchArraySize = peeker->mPatch->serializedSize();
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400401 ninePatchChunk = env->NewByteArray(ninePatchArraySize);
402 if (ninePatchChunk == nullptr) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500403 doThrowOOME(env, "Failed to allocate nine patch chunk.");
404 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400405 }
406
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500407 env->SetByteArrayRegion(ninePatchChunk, 0, peeker->mPatchSize,
408 reinterpret_cast<jbyte*>(peeker->mPatch));
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400409 }
410
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500411 if (peeker->mHasInsets) {
412 ninePatchInsets = peeker->createNinePatchInsets(env, 1.0f);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400413 if (ninePatchInsets == nullptr) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500414 doThrowOOME(env, "Failed to allocate nine patch insets.");
415 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400416 }
417 }
418 }
419
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400420 if (jpostProcess) {
421 std::unique_ptr<Canvas> canvas(Canvas::create_canvas(bm));
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400422
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400423 jint pixelFormat = postProcessAndRelease(env, jdecoder, std::move(canvas));
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400424 if (env->ExceptionCheck()) {
425 return nullptr;
426 }
427
428 SkAlphaType newAlphaType = bm.alphaType();
429 switch (pixelFormat) {
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500430 case kUnknown:
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400431 break;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500432 case kTranslucent:
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400433 newAlphaType = kPremul_SkAlphaType;
434 break;
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500435 case kOpaque:
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400436 newAlphaType = kOpaque_SkAlphaType;
437 break;
438 default:
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500439 SkString msg;
440 msg.printf("invalid return from postProcess: %i", pixelFormat);
441 doThrowIAE(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400442 return nullptr;
443 }
444
445 if (newAlphaType != bm.alphaType()) {
446 if (!bm.setAlphaType(newAlphaType)) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500447 SkString msg;
448 msg.printf("incompatible return from postProcess: %i", pixelFormat);
449 doThrowIAE(env, msg.c_str());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400450 return nullptr;
451 }
452 nativeBitmap->setAlphaType(newAlphaType);
453 }
454 }
455
456 int bitmapCreateFlags = 0x0;
457 if (!requireUnpremul) {
458 // Even if the image is opaque, setting this flag means that
459 // if alpha is added (e.g. by PostProcess), it will be marked as
460 // premultiplied.
461 bitmapCreateFlags |= bitmap::kBitmapCreateFlag_Premultiplied;
462 }
463
464 if (requireMutable) {
465 bitmapCreateFlags |= bitmap::kBitmapCreateFlag_Mutable;
466 } else {
Leon Scroggins IIIee3bfe72019-01-31 08:42:23 -0500467 if (isHardware) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400468 sk_sp<Bitmap> hwBitmap = Bitmap::allocateHardwareBitmap(bm);
469 if (hwBitmap) {
470 hwBitmap->setImmutable();
John Reck5bd537e2023-01-24 20:13:45 -0500471 if (nativeBitmap->hasGainmap()) {
472 // TODO: Also convert to a HW gainmap image
473 hwBitmap->setGainmap(nativeBitmap->gainmap());
474 }
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400475 return bitmap::createBitmap(env, hwBitmap.release(), bitmapCreateFlags,
476 ninePatchChunk, ninePatchInsets);
477 }
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500478 if (allocator == kHardware_Allocator) {
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500479 doThrowOOME(env, "failed to allocate hardware Bitmap!");
480 return nullptr;
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400481 }
482 // If we failed to create a hardware bitmap, go ahead and create a
483 // software one.
484 }
485
486 nativeBitmap->setImmutable();
487 }
488 return bitmap::createBitmap(env, nativeBitmap.release(), bitmapCreateFlags, ninePatchChunk,
489 ninePatchInsets);
490}
491
492static jobject ImageDecoder_nGetSampledSize(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
493 jint sampleSize) {
494 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III5a5c2ce2021-01-15 14:09:13 -0500495 SkISize size = decoder->getSampledDimensions(sampleSize);
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500496 return env->NewObject(gSize_class, gSize_constructorMethodID, size.width(), size.height());
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400497}
498
499static void ImageDecoder_nGetPadding(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
500 jobject outPadding) {
501 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III753a56f2019-12-11 11:02:15 -0500502 reinterpret_cast<NinePatchPeeker*>(decoder->mPeeker.get())->getPadding(env, outPadding);
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400503}
504
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500505static void ImageDecoder_nClose(JNIEnv* /*env*/, jobject /*clazz*/, jlong nativePtr) {
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400506 delete reinterpret_cast<ImageDecoder*>(nativePtr);
507}
508
Leon Scroggins III1fad09d2017-12-22 12:54:20 -0500509static jstring ImageDecoder_nGetMimeType(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
510 auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
Leon Scroggins III407b5442019-11-22 17:10:20 -0500511 return getMimeTypeAsJavaString(env, decoder->mCodec->getEncodedFormat());
Leon Scroggins III1fad09d2017-12-22 12:54:20 -0500512}
513
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400514static jobject ImageDecoder_nGetColorSpace(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
515 auto* codec = reinterpret_cast<ImageDecoder*>(nativePtr)->mCodec.get();
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500516 auto colorType = codec->computeOutputColorType(kN32_SkColorType);
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400517 sk_sp<SkColorSpace> colorSpace = codec->computeOutputColorSpace(colorType);
Derek Sollenbergerbf3e4642019-01-30 11:28:27 -0500518 return GraphicsJNI::getColorSpace(env, colorSpace.get(), colorType);
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400519}
520
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400521static const JNINativeMethod gImageDecoderMethods[] = {
Chong Zhangcba27922019-07-12 16:38:47 -0700522 { "nCreate", "(JZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateAsset },
523 { "nCreate", "(Ljava/nio/ByteBuffer;IIZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateByteBuffer },
524 { "nCreate", "([BIIZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateByteArray },
525 { "nCreate", "(Ljava/io/InputStream;[BZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateInputStream },
Leon Scroggins IIIc3fda892020-09-10 14:57:11 -0400526 { "nCreate", "(Ljava/io/FileDescriptor;JZLandroid/graphics/ImageDecoder$Source;)Landroid/graphics/ImageDecoder;", (void*) ImageDecoder_nCreateFd },
Leon Scroggins III28f3943f2019-02-19 11:03:44 -0500527 { "nDecodeBitmap", "(JLandroid/graphics/ImageDecoder;ZIILandroid/graphics/Rect;ZIZZZJZ)Landroid/graphics/Bitmap;",
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400528 (void*) ImageDecoder_nDecodeBitmap },
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500529 { "nGetSampledSize","(JI)Landroid/util/Size;", (void*) ImageDecoder_nGetSampledSize },
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400530 { "nGetPadding", "(JLandroid/graphics/Rect;)V", (void*) ImageDecoder_nGetPadding },
Leon Scroggins IIIed074fd2017-12-11 13:47:23 -0500531 { "nClose", "(J)V", (void*) ImageDecoder_nClose},
Leon Scroggins III1fad09d2017-12-22 12:54:20 -0500532 { "nGetMimeType", "(J)Ljava/lang/String;", (void*) ImageDecoder_nGetMimeType },
Leon Scroggins III1a69f452018-03-29 09:48:47 -0400533 { "nGetColorSpace", "(J)Landroid/graphics/ColorSpace;", (void*) ImageDecoder_nGetColorSpace },
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400534};
535
536int register_android_graphics_ImageDecoder(JNIEnv* env) {
537 gImageDecoder_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/ImageDecoder"));
Leon Scroggins III7d940ba2018-04-04 16:19:33 -0400538 gImageDecoder_constructorMethodID = GetMethodIDOrDie(env, gImageDecoder_class, "<init>", "(JIIZZ)V");
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500539 gImageDecoder_postProcessMethodID = GetMethodIDOrDie(env, gImageDecoder_class, "postProcessAndRelease", "(Landroid/graphics/Canvas;)I");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400540
Leon Scroggins IIIe5de9aa2018-01-10 20:56:51 -0500541 gSize_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/util/Size"));
542 gSize_constructorMethodID = GetMethodIDOrDie(env, gSize_class, "<init>", "(II)V");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400543
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400544 gDecodeException_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/ImageDecoder$DecodeException"));
545 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 -0400546
Leon Scroggins III1d2bf2b2018-03-14 16:07:43 -0400547 gCallback_onPartialImageMethodID = GetMethodIDOrDie(env, gImageDecoder_class, "onPartialImage", "(ILjava/lang/Throwable;)V");
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400548
Leon Scroggins III0c01dbf2017-10-20 14:08:11 -0400549 gCanvas_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/graphics/Canvas"));
550 gCanvas_constructorMethodID = GetMethodIDOrDie(env, gCanvas_class, "<init>", "(J)V");
551 gCanvas_releaseMethodID = GetMethodIDOrDie(env, gCanvas_class, "release", "()V");
552
553 return android::RegisterMethodsOrDie(env, "android/graphics/ImageDecoder", gImageDecoderMethods,
554 NELEM(gImageDecoderMethods));
555}