| /* | |
| * Copyright (C) 2026 The Android Open Source Project | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| #define LOG_TAG "ImageDecoderService" | |
| #include <SkAndroidCodec.h> | |
| #include <SkBitmap.h> | |
| #include <SkCodec.h> | |
| #include <SkColorSpace.h> | |
| #include <SkStream.h> | |
| #include <SkString.h> | |
| #include <Gainmap.h> | |
| #include <aidl/android/graphics/BnImageDecoder.h> | |
| #include <aidl/android/graphics/BnImageDecoderService.h> | |
| #include <aidl/android/graphics/DecodedBitmap.h> | |
| #include <aidl/android/graphics/ImageDecoderInfo.h> | |
| #include <aidl/android/graphics/NinePatchInfo.h> | |
| #include <android/binder_ibinder.h> | |
| #include <android/native_service.h> | |
| #include <cinttypes> | |
| #include <cutils/ashmem.h> | |
| #include <fcntl.h> | |
| #include <hwui/Bitmap.h> | |
| #include <hwui/CodecRegistration.h> | |
| #include <hwui/ImageDecoder.h> | |
| #include <hwui/ImageDecoderCommon.h> | |
| #include <hwui/NinePatchPeeker.h> | |
| #include <linux/memfd.h> | |
| #include <log/log.h> | |
| #include <mutex> | |
| #include <optional> | |
| #include <sys/mman.h> | |
| #include <sys/syscall.h> | |
| #include <unistd.h> | |
| #include <utils/MimeType.h> | |
| using namespace aidl::android::graphics; | |
| using namespace android; | |
| static std::vector<uint8_t> serializeColorSpace(const SkColorSpace* colorSpace) { | |
| if (!colorSpace) { | |
| return {}; | |
| } | |
| auto data = colorSpace->serialize(); | |
| if (!data || data->size() == 0) { | |
| return {}; | |
| } | |
| return std::vector<uint8_t>( | |
| static_cast<const uint8_t*>(data->data()), | |
| static_cast<const uint8_t*>(data->data()) + data->size()); | |
| } | |
| static std::optional<NinePatchInfo> extractNinePatchInfo(const NinePatchPeeker* peeker) { | |
| if (!peeker || !peeker->mPatch) { | |
| return std::nullopt; | |
| } | |
| NinePatchInfo info; | |
| info.ninePatchChunk = std::vector<uint8_t>( | |
| reinterpret_cast<const uint8_t*>(peeker->mPatch), | |
| reinterpret_cast<const uint8_t*>(peeker->mPatch) + peeker->mPatchSize); | |
| info.padding = { | |
| .left = peeker->mPatch->paddingLeft, | |
| .top = peeker->mPatch->paddingTop, | |
| .right = peeker->mPatch->paddingRight, | |
| .bottom = peeker->mPatch->paddingBottom | |
| }; | |
| if (peeker->mHasInsets) { | |
| info.opticalInsets = { | |
| .left = peeker->mOpticalInsets[0], | |
| .top = peeker->mOpticalInsets[1], | |
| .right = peeker->mOpticalInsets[2], | |
| .bottom = peeker->mOpticalInsets[3] | |
| }; | |
| info.outlineInsets = { | |
| .left = peeker->mOutlineInsets[0], | |
| .top = peeker->mOutlineInsets[1], | |
| .right = peeker->mOutlineInsets[2], | |
| .bottom = peeker->mOutlineInsets[3] | |
| }; | |
| info.outlineRadius = peeker->mOutlineRadius; | |
| info.outlineAlpha = static_cast<int32_t>(peeker->mOutlineAlpha); | |
| } | |
| return info; | |
| } | |
| class ImageDecoderHandle : public BnImageDecoder { | |
| public: | |
| ImageDecoderHandle(std::unique_ptr<ImageDecoder> decoder) | |
| : mDecoder(std::move(decoder)) {} | |
| virtual ~ImageDecoderHandle() = default; | |
| ImageDecoder* getDecoder() { return mDecoder.get(); } | |
| ndk::ScopedAStatus getSampledSize(int32_t sampleSize, | |
| aidl::android::gui::Size* aidlReturn) override { | |
| std::lock_guard<std::mutex> lock(mMutex); | |
| SkISize size = mDecoder->getSampledDimensions(sampleSize); | |
| aidlReturn->width = size.width(); | |
| aidlReturn->height = size.height(); | |
| return ndk::ScopedAStatus::ok(); | |
| } | |
| ndk::ScopedAStatus decodeBitmap( | |
| int32_t targetWidth, int32_t targetHeight, | |
| const std::optional<aidl::android::gui::ARect>& cropRect, int32_t allocator, | |
| int32_t flags, const std::optional<std::vector<uint8_t>>& desiredColorSpaceData, | |
| int64_t allocationLimit, DecodedBitmap* aidlReturn) override { | |
| std::lock_guard<std::mutex> lock(mMutex); | |
| ImageDecoder* decoder = mDecoder.get(); | |
| ftl::Flags<DecodeOptions> opts(static_cast<DecodeOptions>(flags)); | |
| const bool mutableRequired = opts.test(DecodeOptions::MutableRequired); | |
| const bool preferRamOverQuality = opts.test(DecodeOptions::PreferRamOverQuality); | |
| const bool willPostProcess = opts.test(DecodeOptions::HasPostProcess); | |
| sk_sp<SkColorSpace> desiredColorSpace; | |
| if (desiredColorSpaceData.has_value() && !desiredColorSpaceData->empty()) { | |
| desiredColorSpace = SkColorSpace::Deserialize(desiredColorSpaceData->data(), | |
| desiredColorSpaceData->size()); | |
| } | |
| SkIRect crop; | |
| if (cropRect.has_value()) { | |
| crop = SkIRect::MakeLTRB(cropRect->left, cropRect->top, | |
| cropRect->right, cropRect->bottom); | |
| } | |
| auto preppedBitmap = decoder->prepareForDecode(targetWidth, targetHeight, | |
| static_cast<ImageDecoderAllocator>(allocator), | |
| opts, allocationLimit, desiredColorSpace, | |
| cropRect.has_value() ? &crop : nullptr); | |
| if (preppedBitmap.error.has_value()) { | |
| return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(*preppedBitmap.error), preppedBitmap.errorMessage.c_str()); | |
| } | |
| SkBitmap skBitmap = preppedBitmap.bitmap; | |
| const bool readOnly = !mutableRequired && !willPostProcess; | |
| sk_sp<Bitmap> nativeBitmap = Bitmap::allocateAshmemBitmap(&skBitmap, readOnly); | |
| if (!nativeBitmap) { | |
| SkString msg; | |
| msg.printf("OOM allocating Bitmap with dimensions %i x %i", | |
| skBitmap.width(), skBitmap.height()); | |
| return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kOutOfMemory), msg.c_str()); | |
| } | |
| SkCodec::Result result = decoder->decode(nativeBitmap->pixels(), nativeBitmap->rowBytes()); | |
| int onPartialImageError = 0; | |
| switch (result) { | |
| case SkCodec::kSuccess: | |
| break; | |
| case SkCodec::kIncompleteInput: | |
| onPartialImageError = static_cast<int32_t>(DecodeException::kSourceIncomplete); | |
| break; | |
| case SkCodec::kErrorInInput: | |
| onPartialImageError = static_cast<int32_t>(DecodeException::kSourceMalformedData); | |
| break; | |
| default: | |
| SkString msg; | |
| msg.printf("getPixels failed with error %s", SkCodec::ResultToString(result)); | |
| return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kInputOutput), msg.c_str()); | |
| } | |
| aidlReturn->onPartialImageError = onPartialImageError; | |
| if (result == SkCodec::kSuccess && !willPostProcess && !preferRamOverQuality) { | |
| SkCodec::Result gmResult = decoder->extractGainmap(nativeBitmap.get(), true); | |
| if (!nativeBitmap->hasGainmap()) { | |
| // no gainmap, nothing to do | |
| } else if (gmResult != SkCodec::kSuccess) { | |
| aidlReturn->onPartialImageError = | |
| static_cast<int32_t>(DecodeException::kGainmapExtractionFailed); | |
| } else { | |
| auto gainmap = nativeBitmap->gainmap(); | |
| auto gmBitmap = gainmap->bitmap; | |
| DecodedGainmap decodedGainmap; | |
| decodedGainmap.width = gmBitmap->width(); | |
| decodedGainmap.height = gmBitmap->height(); | |
| decodedGainmap.colorType = static_cast<int32_t>(gmBitmap->info().colorType()); | |
| decodedGainmap.alphaType = static_cast<int32_t>(gmBitmap->info().alphaType()); | |
| int gmFd = gmBitmap->getAshmemFd(); | |
| if (gmFd >= 0) { | |
| decodedGainmap.ashmemPfd = ndk::ScopedFileDescriptor(dup(gmFd)); | |
| } | |
| const auto& gainmapInfo = gainmap->info; | |
| if (gainmapInfo.fGainmapMathColorSpace) { | |
| auto altColorSpaceData = serializeColorSpace( | |
| gainmapInfo.fGainmapMathColorSpace.get()); | |
| if (!altColorSpaceData.empty()) { | |
| decodedGainmap.alternativeColorSpaceData = std::move(altColorSpaceData); | |
| } | |
| } | |
| decodedGainmap.gainmapRatioMin = {gainmapInfo.fGainmapRatioMin.fR, | |
| gainmapInfo.fGainmapRatioMin.fG, | |
| gainmapInfo.fGainmapRatioMin.fB}; | |
| decodedGainmap.gainmapRatioMax = {gainmapInfo.fGainmapRatioMax.fR, | |
| gainmapInfo.fGainmapRatioMax.fG, | |
| gainmapInfo.fGainmapRatioMax.fB}; | |
| decodedGainmap.gainmapGamma = {gainmapInfo.fGainmapGamma.fR, | |
| gainmapInfo.fGainmapGamma.fG, | |
| gainmapInfo.fGainmapGamma.fB}; | |
| decodedGainmap.epsilonSdr = {gainmapInfo.fEpsilonSdr.fR, | |
| gainmapInfo.fEpsilonSdr.fG, | |
| gainmapInfo.fEpsilonSdr.fB}; | |
| decodedGainmap.epsilonHdr = {gainmapInfo.fEpsilonHdr.fR, | |
| gainmapInfo.fEpsilonHdr.fG, | |
| gainmapInfo.fEpsilonHdr.fB}; | |
| decodedGainmap.displayRatioSdr = gainmapInfo.fDisplayRatioSdr; | |
| decodedGainmap.displayRatioHdr = gainmapInfo.fDisplayRatioHdr; | |
| decodedGainmap.baseImageType = static_cast<int32_t>(gainmapInfo.fBaseImageType); | |
| aidlReturn->gainmap = std::make_optional(std::move(decodedGainmap)); | |
| } | |
| } | |
| aidlReturn->width = skBitmap.width(); | |
| aidlReturn->height = skBitmap.height(); | |
| aidlReturn->colorType = static_cast<int32_t>(skBitmap.colorType()); | |
| aidlReturn->alphaType = static_cast<int32_t>(skBitmap.alphaType()); | |
| aidlReturn->colorSpaceData = serializeColorSpace(skBitmap.colorSpace()); | |
| if (decoder->mPeeker) { | |
| aidlReturn->ninePatchInfo = extractNinePatchInfo( | |
| static_cast<NinePatchPeeker*>(decoder->mPeeker.get())); | |
| } | |
| int fd = nativeBitmap->getAshmemFd(); | |
| if (fd >= 0) { | |
| aidlReturn->ashmemPfd = ndk::ScopedFileDescriptor(dup(fd)); | |
| } | |
| return ndk::ScopedAStatus::ok(); | |
| } | |
| private: | |
| std::mutex mMutex; | |
| std::unique_ptr<ImageDecoder> mDecoder GUARDED_BY(mMutex); | |
| }; | |
| class ImageDecoderService : public BnImageDecoderService { | |
| public: | |
| virtual ~ImageDecoderService() = default; | |
| ndk::ScopedAStatus ping() override { | |
| ALOGI("%s", __func__); | |
| return ndk::ScopedAStatus::ok(); | |
| } | |
| ndk::ScopedAStatus crash() override { | |
| ALOGI("ImageDecoderService::crash - intentional abort for testing"); | |
| abort(); | |
| return ndk::ScopedAStatus::ok(); | |
| } | |
| ndk::ScopedAStatus createDecoder(const ndk::ScopedFileDescriptor& pfd, int64_t offset, | |
| int64_t length, bool preferAnimation, | |
| ImageDecoderInfo* aidlReturn) override { | |
| ndk::ScopedAStatus streamError; | |
| auto fileStream = createStreamFromPfd(pfd, offset, length, streamError); | |
| if (!fileStream) { | |
| return streamError; | |
| } | |
| sk_sp<NinePatchPeeker> peeker(new NinePatchPeeker); | |
| SkCodec::Result result; | |
| auto codec = SkCodec::MakeFromStream( | |
| std::move(fileStream), &result, peeker.get(), | |
| preferAnimation ? SkCodec::SelectionPolicy::kPreferAnimation | |
| : SkCodec::SelectionPolicy::kPreferStillImage); | |
| if (!codec) { | |
| switch (result) { | |
| case SkCodec::kIncompleteInput: | |
| return ndk::ScopedAStatus::fromServiceSpecificError( | |
| static_cast<int32_t>(SandboxError::kSourceIncomplete)); | |
| default: | |
| SkString msg; | |
| msg.printf("Service: Failed to create image decoder with message '%s'", | |
| SkCodec::ResultToString(result)); | |
| return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), | |
| msg.c_str()); | |
| } | |
| } | |
| const auto format = codec->getEncodedFormat(); | |
| const char* mimeType = getMimeType(format); | |
| if (mimeType) { | |
| aidlReturn->mimeType = std::string(mimeType); | |
| if (std::string(mimeType) == "image/heif" || std::string(mimeType) == "image/avif") { | |
| // fall back to MediaCodec decoder | |
| // (file is closed in SkStream destructor) | |
| ALOGI("createDecoder detected heif/avif image, falling back to mediacodec decoder"); | |
| return ndk::ScopedAStatus::fromServiceSpecificError( | |
| static_cast<int32_t>(SandboxError::kHeifAvifImageFormat)); | |
| } | |
| } | |
| const bool animated = codec->getFrameCount() > 1; | |
| auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec)); | |
| if (!androidCodec.get()) { | |
| return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), | |
| "Failed to create android codec"); | |
| } | |
| aidlReturn->ninePatchInfo = extractNinePatchInfo(peeker.get()); | |
| aidlReturn->colorSpaceData = {}; | |
| auto colorType = androidCodec->computeOutputColorType(kN32_SkColorType); | |
| sk_sp<SkColorSpace> colorSpace = androidCodec->computeOutputColorSpace(colorType, nullptr); | |
| aidlReturn->colorSpaceData = serializeColorSpace(colorSpace.get()); | |
| aidlReturn->colorType = static_cast<int32_t>(colorType); | |
| std::unique_ptr<ImageDecoder> decoder = std::make_unique<ImageDecoder>( | |
| std::move(androidCodec), std::move(peeker), SkCodec::kYes_ZeroInitialized); | |
| int width = decoder->width(); | |
| int height = decoder->height(); | |
| auto handle = ndk::SharedRefBase::make<ImageDecoderHandle>(std::move(decoder)); | |
| aidlReturn->handle = handle; | |
| aidlReturn->width = width; | |
| aidlReturn->height = height; | |
| aidlReturn->isAnimated = animated; | |
| ALOGI("createDecoder successful: %dx%d, animated=%d, ninePatch=%d, mimeType=%s", | |
| width, height, animated, aidlReturn->ninePatchInfo.has_value(), | |
| aidlReturn->mimeType.c_str()); | |
| return ndk::ScopedAStatus::ok(); | |
| } | |
| private: | |
| // negative offsets are not allowed | |
| static std::unique_ptr<SkFILEStream> createStreamFromPfd( | |
| const ndk::ScopedFileDescriptor& pfd, int64_t offset, int64_t length, | |
| ndk::ScopedAStatus& outError) { | |
| int descriptor = pfd.get(); | |
| if (descriptor < 0) { | |
| outError = ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), | |
| "Invalid file descriptor"); | |
| return nullptr; | |
| } | |
| if (offset < 0) { | |
| outError = ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), | |
| "Invalid negative offset"); | |
| return nullptr; | |
| } | |
| int dupDescriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, 0); | |
| if (dupDescriptor < 0) { | |
| SkString msg; | |
| msg.printf("Failed to dup file descriptor: %s", strerror(errno)); | |
| outError = ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), msg.c_str()); | |
| return nullptr; | |
| } | |
| if (offset > 0 && lseek(dupDescriptor, offset, SEEK_SET) == -1) { | |
| SkString msg; | |
| msg.printf("Failed to seek file descriptor to offset %" PRId64 ": %s", offset, | |
| strerror(errno)); | |
| close(dupDescriptor); | |
| outError = ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), msg.c_str()); | |
| return nullptr; | |
| } | |
| FILE* file = fdopen(dupDescriptor, "r"); | |
| if (file == nullptr) { | |
| SkString msg; | |
| msg.printf("Could not open file from descriptor: %s", strerror(errno)); | |
| close(dupDescriptor); | |
| outError = ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( | |
| static_cast<int32_t>(SandboxError::kSourceMalformedData), msg.c_str()); | |
| return nullptr; | |
| } | |
| if (length <= 0) { | |
| return std::make_unique<SkFILEStream>(file); | |
| } else { | |
| return std::make_unique<SkFILEStream>(file, static_cast<size_t>(length)); | |
| } | |
| } | |
| }; | |
| extern "C" AIBinder* native_service_onBind(ANativeService* /*service*/, uint64_t /*bindToken*/, | |
| char const* /*action*/, char const* /*data*/) { | |
| std::shared_ptr<ImageDecoderService> service = ndk::SharedRefBase::make<ImageDecoderService>(); | |
| if (!service) { | |
| ALOGE("%s: Failed to create ImageDecoderService instance!", __func__); | |
| return nullptr; | |
| } | |
| ndk::SpAIBinder binder = service->asBinder(); | |
| if (!binder.get()) { | |
| ALOGE("%s: service->asBinder() returned null!", __func__); | |
| return nullptr; | |
| } | |
| ALOGI("%s: successful. binder=%p", __func__, binder.get()); | |
| AIBinder* rawBinder = binder.get(); | |
| AIBinder_incStrong(rawBinder); | |
| return rawBinder; | |
| } | |
| extern "C" void native_service_createService(ANativeService* service) { | |
| ALOGI("%s", __func__); | |
| EnsureDecodersRegistered(); | |
| ANativeService_setOnBindCallback(service, native_service_onBind); | |
| } |