diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart index 02e97ee3d7..6856e4eed4 100644 --- a/engine/src/flutter/lib/ui/painting.dart +++ b/engine/src/flutter/lib/ui/painting.dart @@ -1650,15 +1650,6 @@ class Codec extends NativeFieldWrapperClass2 { /// The data can be for either static or animated images. The following image /// formats are supported: {@macro flutter.dart:ui.imageFormats} /// -/// The [decodedCacheRatioCap] is the default maximum multiple of the compressed -/// image size to cache when decoding animated image frames. For example, -/// setting this to `2.0` means that a 400KB GIF would be allowed at most to use -/// 800KB of memory caching unessential decoded frames. Caching decoded frames -/// saves CPU but can result in out-of-memory crashes when decoding large (or -/// multiple) animated images. Note that GIFs are highly compressed, and it's -/// unlikely that a factor that low will be sufficient to cache all decoded -/// frames. The default value is `25.0`. -/// /// The [targetWidth] and [targetHeight] arguments specify the size of the output /// image, in image pixels. If they are not equal to the intrinsic dimensions of the /// image, then the image will be scaled after being decoded. If exactly one of @@ -1669,12 +1660,11 @@ class Codec extends NativeFieldWrapperClass2 { /// The returned future can complete with an error if the image decoding has /// failed. Future instantiateImageCodec(Uint8List list, { - double decodedCacheRatioCap = 0, int targetWidth, int targetHeight, }) { return _futurize( - (_Callback callback) => _instantiateImageCodec(list, callback, null, decodedCacheRatioCap, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension) + (_Callback callback) => _instantiateImageCodec(list, callback, null, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension) ); } @@ -1689,7 +1679,7 @@ Future instantiateImageCodec(Uint8List list, { /// If both are equal to [_kDoNotResizeDimension], then the image maintains its real size. /// /// Returns an error message if the instantiation has failed, null otherwise. -String _instantiateImageCodec(Uint8List list, _Callback callback, _ImageInfo imageInfo, double decodedCacheRatioCap, int targetWidth, int targetHeight) +String _instantiateImageCodec(Uint8List list, _Callback callback, _ImageInfo imageInfo, int targetWidth, int targetHeight) native 'instantiateImageCodec'; /// Loads a single image frame from a byte array into an [Image] object. @@ -1715,15 +1705,6 @@ Future _decodeImageFromListAsync(Uint8List list, /// data buffer. If unspecified, it defaults to [width] multiplied by the /// number of bytes per pixel in the provided [format]. /// -/// The [decodedCacheRatioCap] is the default maximum multiple of the compressed -/// image size to cache when decoding animated image frames. For example, -/// setting this to `2.0` means that a 400KB GIF would be allowed at most to use -/// 800KB of memory caching unessential decoded frames. Caching decoded frames -/// saves CPU but can result in out-of-memory crashes when decoding large (or -/// multiple) animated images. Note that GIFs are highly compressed, and it's -/// unlikely that a factor that low will be sufficient to cache all decoded -/// frames. The default value is `25.0`. -/// /// The [targetWidth] and [targetHeight] arguments specify the size of the output /// image, in image pixels. If they are not equal to the intrinsic dimensions of the /// image, then the image will be scaled after being decoded. If exactly one of @@ -1736,11 +1717,11 @@ void decodeImageFromPixels( int height, PixelFormat format, ImageDecoderCallback callback, - {int rowBytes, double decodedCacheRatioCap = 0, int targetWidth, int targetHeight} + {int rowBytes, int targetWidth, int targetHeight} ) { final _ImageInfo imageInfo = _ImageInfo(width, height, format.index, rowBytes); final Future codecFuture = _futurize( - (_Callback callback) => _instantiateImageCodec(pixels, callback, imageInfo, decodedCacheRatioCap, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension) + (_Callback callback) => _instantiateImageCodec(pixels, callback, imageInfo, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension) ); codecFuture.then((Codec codec) => codec.getNextFrame()) .then((FrameInfo frameInfo) => callback(frameInfo.image)); diff --git a/engine/src/flutter/lib/ui/painting/codec.cc b/engine/src/flutter/lib/ui/painting/codec.cc index ee072a2d73..1419552351 100644 --- a/engine/src/flutter/lib/ui/painting/codec.cc +++ b/engine/src/flutter/lib/ui/painting/codec.cc @@ -191,7 +191,6 @@ static sk_sp DecodeAndResizeImage(fml::WeakPtr context, fml::RefPtr InitCodec(fml::WeakPtr context, sk_sp buffer, fml::RefPtr unref_queue, - const float decodedCacheRatioCap, const int targetWidth, const int targetHeight, size_t trace_id) { @@ -210,8 +209,7 @@ fml::RefPtr InitCodec(fml::WeakPtr context, return nullptr; } if (skCodec->getFrameCount() > 1) { - return fml::MakeRefCounted(std::move(skCodec), - decodedCacheRatioCap); + return fml::MakeRefCounted(std::move(skCodec)); } auto skImage = DecodeAndResizeImage(context, skCodec, buffer, targetWidth, @@ -232,7 +230,6 @@ fml::RefPtr InitCodecUncompressed( sk_sp buffer, ImageInfo image_info, fml::RefPtr unref_queue, - const float decodedCacheRatioCap, int targetWidth, int targetHeight, size_t trace_id) { @@ -274,19 +271,17 @@ void InitCodecAndInvokeCodecCallback( std::unique_ptr callback, sk_sp buffer, std::unique_ptr image_info, - const float decodedCacheRatioCap, const int targetWidth, const int targetHeight, size_t trace_id) { fml::RefPtr codec; if (image_info) { codec = InitCodecUncompressed(context, std::move(buffer), *image_info, - std::move(unref_queue), decodedCacheRatioCap, - targetWidth, targetHeight, trace_id); + std::move(unref_queue), targetWidth, + targetHeight, trace_id); } else { - codec = - InitCodec(context, std::move(buffer), std::move(unref_queue), - decodedCacheRatioCap, targetWidth, targetHeight, trace_id); + codec = InitCodec(context, std::move(buffer), std::move(unref_queue), + targetWidth, targetHeight, trace_id); } ui_task_runner->PostTask( fml::MakeCopyable([callback = std::move(callback), @@ -404,13 +399,10 @@ void InstantiateImageCodec(Dart_NativeArguments args) { } } - const float decodedCacheRatioCap = - tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 3)); - const int targetWidth = - tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 4)); + tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 3)); const int targetHeight = - tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 5)); + tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 4)); auto buffer = SkData::MakeWithCopy(list.data(), list.num_elements()); @@ -423,12 +415,12 @@ void InstantiateImageCodec(Dart_NativeArguments args) { buffer = std::move(buffer), trace_id, image_info = std::move(image_info), ui_task_runner = task_runners.GetUITaskRunner(), context = dart_state->GetResourceContext(), - queue = UIDartState::Current()->GetSkiaUnrefQueue(), - decodedCacheRatioCap, targetWidth, targetHeight]() mutable { + queue = UIDartState::Current()->GetSkiaUnrefQueue(), targetWidth, + targetHeight]() mutable { InitCodecAndInvokeCodecCallback( std::move(ui_task_runner), context, std::move(queue), std::move(callback), std::move(buffer), std::move(image_info), - decodedCacheRatioCap, targetWidth, targetHeight, trace_id); + targetWidth, targetHeight, trace_id); })); } @@ -494,92 +486,64 @@ void Codec::dispose() { ClearDartWrapper(); } -MultiFrameCodec::MultiFrameCodec(std::unique_ptr codec, - const float decodedCacheRatioCap) - : codec_(std::move(codec)), decodedCacheRatioCap_(decodedCacheRatioCap) { - repetitionCount_ = codec_->getRepetitionCount(); - frameInfos_ = codec_->getFrameInfo(); - compressedSizeBytes_ = codec_->getInfo().computeMinByteSize(); - frameBitmaps_.clear(); - decodedCacheSize_ = 0; - nextFrameIndex_ = 0; - // Go through our frame information and mark which frames are required in - // order to decode subsequent ones. - requiredFrames_.clear(); - for (size_t frameIndex = 0; frameIndex < frameInfos_.size(); frameIndex++) { - const int requiredFrame = frameInfos_[frameIndex].fRequiredFrame; - if (requiredFrame != SkCodec::kNoFrame) { - requiredFrames_[requiredFrame] = true; - } - } -} +MultiFrameCodec::MultiFrameCodec(std::unique_ptr codec) + : codec_(std::move(codec)), + frameCount_(codec_->getFrameCount()), + repetitionCount_(codec_->getRepetitionCount()), + nextFrameIndex_(0) {} MultiFrameCodec::~MultiFrameCodec() {} -int MultiFrameCodec::frameCount() { - return frameInfos_.size(); +int MultiFrameCodec::frameCount() const { + return frameCount_; } -int MultiFrameCodec::repetitionCount() { +int MultiFrameCodec::repetitionCount() const { return repetitionCount_; } sk_sp MultiFrameCodec::GetNextFrameImage( fml::WeakPtr resourceContext) { - // Populate this bitmap from the cache if it exists - SkBitmap bitmap = frameBitmaps_[nextFrameIndex_] != nullptr - ? *frameBitmaps_[nextFrameIndex_] - : SkBitmap(); - const bool frameAlreadyCached = bitmap.getPixels(); - if (!frameAlreadyCached) { - SkImageInfo info = codec_->getInfo().makeColorType(kN32_SkColorType); - if (info.alphaType() == kUnpremul_SkAlphaType) { - info = info.makeAlphaType(kPremul_SkAlphaType); - } - bitmap.allocPixels(info); + SkBitmap bitmap = SkBitmap(); + SkImageInfo info = codec_->getInfo().makeColorType(kN32_SkColorType); + if (info.alphaType() == kUnpremul_SkAlphaType) { + info = info.makeAlphaType(kPremul_SkAlphaType); + } + bitmap.allocPixels(info); - SkCodec::Options options; - options.fFrameIndex = nextFrameIndex_; - const int requiredFrameIndex = frameInfos_[nextFrameIndex_].fRequiredFrame; - if (requiredFrameIndex != SkCodec::kNoFrame) { - if (lastRequiredFrame_ == nullptr) { - FML_LOG(ERROR) << "Frame " << nextFrameIndex_ << " depends on frame " - << requiredFrameIndex - << " and no required frames are cached."; - return NULL; - } else if (lastRequiredFrameIndex_ != requiredFrameIndex) { - FML_DLOG(INFO) << "Required frame " << requiredFrameIndex - << " is not cached. Using " << lastRequiredFrameIndex_ - << " instead"; - } - - if (lastRequiredFrame_->getPixels() && - copy_to(&bitmap, lastRequiredFrame_->colorType(), - *lastRequiredFrame_)) { - options.fPriorFrame = requiredFrameIndex; - } - } - - if (SkCodec::kSuccess != codec_->getPixels(info, bitmap.getPixels(), - bitmap.rowBytes(), &options)) { - FML_LOG(ERROR) << "Could not getPixels for frame " << nextFrameIndex_; + SkCodec::Options options; + options.fFrameIndex = nextFrameIndex_; + SkCodec::FrameInfo frameInfo; + codec_->getFrameInfo(nextFrameIndex_, &frameInfo); + const int requiredFrameIndex = frameInfo.fRequiredFrame; + if (requiredFrameIndex != SkCodec::kNoFrame) { + if (lastRequiredFrame_ == nullptr) { + FML_LOG(ERROR) << "Frame " << nextFrameIndex_ << " depends on frame " + << requiredFrameIndex + << " and no required frames are cached."; return NULL; + } else if (lastRequiredFrameIndex_ != requiredFrameIndex) { + FML_DLOG(INFO) << "Required frame " << requiredFrameIndex + << " is not cached. Using " << lastRequiredFrameIndex_ + << " instead"; } - const size_t cachedFrameSize = bitmap.computeByteSize(); - const bool shouldCache = ((decodedCacheSize_ + cachedFrameSize) / - compressedSizeBytes_) <= decodedCacheRatioCap_; - if (shouldCache) { - frameBitmaps_[nextFrameIndex_] = std::make_shared(bitmap); - decodedCacheSize_ += cachedFrameSize; + if (lastRequiredFrame_->getPixels() && + copy_to(&bitmap, lastRequiredFrame_->colorType(), + *lastRequiredFrame_)) { + options.fPriorFrame = requiredFrameIndex; } } + if (SkCodec::kSuccess != codec_->getPixels(info, bitmap.getPixels(), + bitmap.rowBytes(), &options)) { + FML_LOG(ERROR) << "Could not getPixels for frame " << nextFrameIndex_; + return NULL; + } + // Hold onto this if we need it to decode future frames. - if (requiredFrames_[nextFrameIndex_]) { - lastRequiredFrame_ = frameAlreadyCached - ? frameBitmaps_[nextFrameIndex_] - : std::make_shared(bitmap); + if (frameInfo.fDisposalMethod == SkCodecAnimation::DisposalMethod::kKeep) { + lastRequiredFrame_ = std::make_unique(bitmap); lastRequiredFrameIndex_ = nextFrameIndex_; } @@ -609,10 +573,12 @@ void MultiFrameCodec::GetNextFrameAndInvokeCallback( if (skImage) { fml::RefPtr image = CanvasImage::Create(); image->set_image({skImage, std::move(unref_queue)}); - frameInfo = fml::MakeRefCounted( - std::move(image), frameInfos_[nextFrameIndex_].fDuration); + SkCodec::FrameInfo skFrameInfo; + codec_->getFrameInfo(nextFrameIndex_, &skFrameInfo); + frameInfo = + fml::MakeRefCounted(std::move(image), skFrameInfo.fDuration); } - nextFrameIndex_ = (nextFrameIndex_ + 1) % frameInfos_.size(); + nextFrameIndex_ = (nextFrameIndex_ + 1) % frameCount_; ui_task_runner->PostTask(fml::MakeCopyable( [callback = std::move(callback), frameInfo, trace_id]() mutable { @@ -655,11 +621,11 @@ SingleFrameCodec::SingleFrameCodec(fml::RefPtr frame) SingleFrameCodec::~SingleFrameCodec() {} -int SingleFrameCodec::frameCount() { +int SingleFrameCodec::frameCount() const { return 1; } -int SingleFrameCodec::repetitionCount() { +int SingleFrameCodec::repetitionCount() const { return 0; } @@ -682,7 +648,7 @@ Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { void Codec::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({ - {"instantiateImageCodec", InstantiateImageCodec, 6, true}, + {"instantiateImageCodec", InstantiateImageCodec, 5, true}, }); natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } diff --git a/engine/src/flutter/lib/ui/painting/codec.h b/engine/src/flutter/lib/ui/painting/codec.h index fa14cd63ca..776e97cc58 100644 --- a/engine/src/flutter/lib/ui/painting/codec.h +++ b/engine/src/flutter/lib/ui/painting/codec.h @@ -26,8 +26,8 @@ class Codec : public RefCountedDartWrappable { DEFINE_WRAPPERTYPEINFO(); public: - virtual int frameCount() = 0; - virtual int repetitionCount() = 0; + virtual int frameCount() const = 0; + virtual int repetitionCount() const = 0; virtual Dart_Handle getNextFrame(Dart_Handle callback_handle) = 0; void dispose(); @@ -36,13 +36,12 @@ class Codec : public RefCountedDartWrappable { class MultiFrameCodec : public Codec { public: - int frameCount() override; - int repetitionCount() override; + int frameCount() const override; + int repetitionCount() const override; Dart_Handle getNextFrame(Dart_Handle args) override; private: - MultiFrameCodec(std::unique_ptr codec, - const float decodedCacheRatioCap); + MultiFrameCodec(std::unique_ptr codec); ~MultiFrameCodec() override; @@ -56,23 +55,12 @@ class MultiFrameCodec : public Codec { size_t trace_id); const std::unique_ptr codec_; - int repetitionCount_; + const int frameCount_; + const int repetitionCount_; int nextFrameIndex_; - // The default max amount of memory to use for caching decoded animated image - // frames compared to total undecoded size. - const float decodedCacheRatioCap_; - size_t compressedSizeBytes_; - size_t decodedCacheSize_; - std::vector frameInfos_; - std::map requiredFrames_; - - // A cache of previously loaded bitmaps, indexed by the frame they belong to. - // Caches all frames until [decodedCacheSize_] : [compressedSize_] exceeds - // [decodedCacheRatioCap_]. - std::map> frameBitmaps_; // The last decoded frame that's required to decode any subsequent frames. - std::shared_ptr lastRequiredFrame_; + std::unique_ptr lastRequiredFrame_; // The index of the last decoded required frame. int lastRequiredFrameIndex_ = -1; @@ -82,8 +70,8 @@ class MultiFrameCodec : public Codec { class SingleFrameCodec : public Codec { public: - int frameCount() override; - int repetitionCount() override; + int frameCount() const override; + int repetitionCount() const override; Dart_Handle getNextFrame(Dart_Handle args) override; private: diff --git a/engine/src/flutter/testing/dart/codec_test.dart b/engine/src/flutter/testing/dart/codec_test.dart index 728bfdcc26..00ff78f211 100644 --- a/engine/src/flutter/testing/dart/codec_test.dart +++ b/engine/src/flutter/testing/dart/codec_test.dart @@ -54,29 +54,6 @@ void main() { ])); }); - test('decodedCacheRatioCap', () async { - // No real way to test the native layer, but a smoke test here to at least - // verify that animation is still consistent with caching disabled. - final Uint8List data = await _getSkiaResource('test640x479.gif').readAsBytes(); - final ui.Codec codec = await ui.instantiateImageCodec(data, decodedCacheRatioCap: 1.0); - final List> decodedFrameInfos = >[]; - for (int i = 0; i < 5; i++) { - final ui.FrameInfo frameInfo = await codec.getNextFrame(); - decodedFrameInfos.add([ - frameInfo.duration.inMilliseconds, - frameInfo.image.width, - frameInfo.image.height, - ]); - } - expect(decodedFrameInfos, equals(>[ - [200, 640, 479], - [200, 640, 479], - [200, 640, 479], - [200, 640, 479], - [200, 640, 479], - ])); - }); - test('non animated image', () async { final Uint8List data = await _getSkiaResource('baby_tux.png').readAsBytes(); final ui.Codec codec = await ui.instantiateImageCodec(data);