Only cache required frames (flutter/engine#8837)

Remove the extra `decodedCacheRatioCap` parameter, and the
`_frameBitmaps` member from `Codec`. This means that small looped images
will consume more CPU but prevents us from hitting OOM exceptions based
on trying to render multiple larger images.

Also switch to fDisposalMethod for caching frames.

Previously we looped over every single SkCodec::FrameInfo, tracked its
`fRequiredFrame`, and then saved any frames matching those indeces.
Doing this instead avoids that initialization loop and extra data
structure.
This commit is contained in:
Michael Klimushyn
2019-05-13 11:18:20 -07:00
committed by GitHub
parent ead69ba45a
commit 3d8b9b1e9c
4 changed files with 72 additions and 160 deletions

View File

@@ -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<Codec> instantiateImageCodec(Uint8List list, {
double decodedCacheRatioCap = 0,
int targetWidth,
int targetHeight,
}) {
return _futurize(
(_Callback<Codec> callback) => _instantiateImageCodec(list, callback, null, decodedCacheRatioCap, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension)
(_Callback<Codec> callback) => _instantiateImageCodec(list, callback, null, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension)
);
}
@@ -1689,7 +1679,7 @@ Future<Codec> 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<Codec> callback, _ImageInfo imageInfo, double decodedCacheRatioCap, int targetWidth, int targetHeight)
String _instantiateImageCodec(Uint8List list, _Callback<Codec> 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<Null> _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<Codec> codecFuture = _futurize(
(_Callback<Codec> callback) => _instantiateImageCodec(pixels, callback, imageInfo, decodedCacheRatioCap, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension)
(_Callback<Codec> callback) => _instantiateImageCodec(pixels, callback, imageInfo, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension)
);
codecFuture.then((Codec codec) => codec.getNextFrame())
.then((FrameInfo frameInfo) => callback(frameInfo.image));

View File

@@ -191,7 +191,6 @@ static sk_sp<SkImage> DecodeAndResizeImage(fml::WeakPtr<GrContext> context,
fml::RefPtr<Codec> InitCodec(fml::WeakPtr<GrContext> context,
sk_sp<SkData> buffer,
fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue,
const float decodedCacheRatioCap,
const int targetWidth,
const int targetHeight,
size_t trace_id) {
@@ -210,8 +209,7 @@ fml::RefPtr<Codec> InitCodec(fml::WeakPtr<GrContext> context,
return nullptr;
}
if (skCodec->getFrameCount() > 1) {
return fml::MakeRefCounted<MultiFrameCodec>(std::move(skCodec),
decodedCacheRatioCap);
return fml::MakeRefCounted<MultiFrameCodec>(std::move(skCodec));
}
auto skImage = DecodeAndResizeImage(context, skCodec, buffer, targetWidth,
@@ -232,7 +230,6 @@ fml::RefPtr<Codec> InitCodecUncompressed(
sk_sp<SkData> buffer,
ImageInfo image_info,
fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue,
const float decodedCacheRatioCap,
int targetWidth,
int targetHeight,
size_t trace_id) {
@@ -274,19 +271,17 @@ void InitCodecAndInvokeCodecCallback(
std::unique_ptr<DartPersistentValue> callback,
sk_sp<SkData> buffer,
std::unique_ptr<ImageInfo> image_info,
const float decodedCacheRatioCap,
const int targetWidth,
const int targetHeight,
size_t trace_id) {
fml::RefPtr<Codec> 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<float>::FromDart(Dart_GetNativeArgument(args, 3));
const int targetWidth =
tonic::DartConverter<int>::FromDart(Dart_GetNativeArgument(args, 4));
tonic::DartConverter<int>::FromDart(Dart_GetNativeArgument(args, 3));
const int targetHeight =
tonic::DartConverter<int>::FromDart(Dart_GetNativeArgument(args, 5));
tonic::DartConverter<int>::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<SkCodec> 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<SkCodec> 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<SkImage> MultiFrameCodec::GetNextFrameImage(
fml::WeakPtr<GrContext> 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<SkBitmap>(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<SkBitmap>(bitmap);
if (frameInfo.fDisposalMethod == SkCodecAnimation::DisposalMethod::kKeep) {
lastRequiredFrame_ = std::make_unique<SkBitmap>(bitmap);
lastRequiredFrameIndex_ = nextFrameIndex_;
}
@@ -609,10 +573,12 @@ void MultiFrameCodec::GetNextFrameAndInvokeCallback(
if (skImage) {
fml::RefPtr<CanvasImage> image = CanvasImage::Create();
image->set_image({skImage, std::move(unref_queue)});
frameInfo = fml::MakeRefCounted<FrameInfo>(
std::move(image), frameInfos_[nextFrameIndex_].fDuration);
SkCodec::FrameInfo skFrameInfo;
codec_->getFrameInfo(nextFrameIndex_, &skFrameInfo);
frameInfo =
fml::MakeRefCounted<FrameInfo>(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<FrameInfo> 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)});
}

View File

@@ -26,8 +26,8 @@ class Codec : public RefCountedDartWrappable<Codec> {
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<Codec> {
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<SkCodec> codec,
const float decodedCacheRatioCap);
MultiFrameCodec(std::unique_ptr<SkCodec> codec);
~MultiFrameCodec() override;
@@ -56,23 +55,12 @@ class MultiFrameCodec : public Codec {
size_t trace_id);
const std::unique_ptr<SkCodec> 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<SkCodec::FrameInfo> frameInfos_;
std::map<int, bool> requiredFrames_;
// A cache of previously loaded bitmaps, indexed by the frame they belong to.
// Caches all frames until [decodedCacheSize_] : [compressedSize_] exceeds
// [decodedCacheRatioCap_].
std::map<int, std::shared_ptr<SkBitmap>> frameBitmaps_;
// The last decoded frame that's required to decode any subsequent frames.
std::shared_ptr<SkBitmap> lastRequiredFrame_;
std::unique_ptr<SkBitmap> 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:

View File

@@ -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<List<int>> decodedFrameInfos = <List<int>>[];
for (int i = 0; i < 5; i++) {
final ui.FrameInfo frameInfo = await codec.getNextFrame();
decodedFrameInfos.add(<int>[
frameInfo.duration.inMilliseconds,
frameInfo.image.width,
frameInfo.image.height,
]);
}
expect(decodedFrameInfos, equals(<List<int>>[
<int>[200, 640, 479],
<int>[200, 640, 479],
<int>[200, 640, 479],
<int>[200, 640, 479],
<int>[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);