diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 05c6078103..db332dbce8 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -335,12 +335,16 @@ FILE: ../../../flutter/lib/ui/painting/image.h FILE: ../../../flutter/lib/ui/painting/image_decoder.cc FILE: ../../../flutter/lib/ui/painting/image_decoder.h FILE: ../../../flutter/lib/ui/painting/image_decoder_unittests.cc +FILE: ../../../flutter/lib/ui/painting/image_descriptor.cc +FILE: ../../../flutter/lib/ui/painting/image_descriptor.h FILE: ../../../flutter/lib/ui/painting/image_encoding.cc FILE: ../../../flutter/lib/ui/painting/image_encoding.h FILE: ../../../flutter/lib/ui/painting/image_filter.cc FILE: ../../../flutter/lib/ui/painting/image_filter.h FILE: ../../../flutter/lib/ui/painting/image_shader.cc FILE: ../../../flutter/lib/ui/painting/image_shader.h +FILE: ../../../flutter/lib/ui/painting/immutable_buffer.cc +FILE: ../../../flutter/lib/ui/painting/immutable_buffer.h FILE: ../../../flutter/lib/ui/painting/matrix.cc FILE: ../../../flutter/lib/ui/painting/matrix.h FILE: ../../../flutter/lib/ui/painting/multi_frame_codec.cc diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn index 0699795130..1fd1d7cdf9 100644 --- a/engine/src/flutter/lib/ui/BUILD.gn +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -38,12 +38,16 @@ source_set_maybe_fuchsia_legacy("ui") { "painting/image.h", "painting/image_decoder.cc", "painting/image_decoder.h", + "painting/image_descriptor.cc", + "painting/image_descriptor.h", "painting/image_encoding.cc", "painting/image_encoding.h", "painting/image_filter.cc", "painting/image_filter.h", "painting/image_shader.cc", "painting/image_shader.h", + "painting/immutable_buffer.cc", + "painting/immutable_buffer.h", "painting/matrix.cc", "painting/matrix.h", "painting/multi_frame_codec.cc", diff --git a/engine/src/flutter/lib/ui/dart_ui.cc b/engine/src/flutter/lib/ui/dart_ui.cc index 313aefc5d3..a02bf3523d 100644 --- a/engine/src/flutter/lib/ui/dart_ui.cc +++ b/engine/src/flutter/lib/ui/dart_ui.cc @@ -16,8 +16,10 @@ #include "flutter/lib/ui/painting/frame_info.h" #include "flutter/lib/ui/painting/gradient.h" #include "flutter/lib/ui/painting/image.h" +#include "flutter/lib/ui/painting/image_descriptor.h" #include "flutter/lib/ui/painting/image_filter.h" #include "flutter/lib/ui/painting/image_shader.h" +#include "flutter/lib/ui/painting/immutable_buffer.h" #include "flutter/lib/ui/painting/path.h" #include "flutter/lib/ui/painting/path_measure.h" #include "flutter/lib/ui/painting/picture.h" @@ -69,8 +71,10 @@ void DartUI::InitForGlobal() { EngineLayer::RegisterNatives(g_natives); FontCollection::RegisterNatives(g_natives); FrameInfo::RegisterNatives(g_natives); + ImageDescriptor::RegisterNatives(g_natives); ImageFilter::RegisterNatives(g_natives); ImageShader::RegisterNatives(g_natives); + ImmutableBuffer::RegisterNatives(g_natives); IsolateNameServerNatives::RegisterNatives(g_natives); Paragraph::RegisterNatives(g_natives); ParagraphBuilder::RegisterNatives(g_natives); diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart index 992db71cf2..54f2588f3d 100644 --- a/engine/src/flutter/lib/ui/painting.dart +++ b/engine/src/flutter/lib/ui/painting.dart @@ -1035,12 +1035,6 @@ enum Clip { antiAliasWithSaveLayer, } -/// Indicates that the image should not be resized in this dimension. -/// -/// Used by [instantiateImageCodec] as a magical value to disable resizing -/// in the given dimension. -const int _kDoNotResizeDimension = -1; - /// A description of the style to use when drawing on a [Canvas]. /// /// Most APIs on [Canvas] take a [Paint] object to describe the style @@ -1561,19 +1555,6 @@ enum PixelFormat { bgra8888, } -class _ImageInfo { - _ImageInfo(this.width, this.height, this.format, int? rowBytes) : rowBytes = rowBytes ?? width * 4; - - @pragma('vm:entry-point', 'get') - int width; - @pragma('vm:entry-point', 'get') - int height; - @pragma('vm:entry-point', 'get') - int format; - @pragma('vm:entry-point', 'get') - int rowBytes; -} - /// Opaque handle to raw decoded image data (pixels). /// /// To obtain an [Image] object, use [instantiateImageCodec]. @@ -1723,39 +1704,23 @@ Future instantiateImageCodec( int? targetWidth, int? targetHeight, bool allowUpscaling = true, -}) { - return _futurize((_Callback callback) { - return _instantiateImageCodec( - list, - callback, - null, - targetWidth ?? _kDoNotResizeDimension, - targetHeight ?? _kDoNotResizeDimension, - allowUpscaling, - ); - }); +}) async { + final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(list); + final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); + if (!allowUpscaling) { + if (targetWidth != null && targetWidth > descriptor.width) { + targetWidth = descriptor.width; + } + if (targetHeight != null && targetHeight > descriptor.height) { + targetHeight = descriptor.height; + } + } + return descriptor.instantiateCodec( + targetWidth: targetWidth, + targetHeight: targetHeight, + ); } -/// Instantiates a [Codec] object for an image binary data. -/// -/// The [targetWidth] and [targetHeight] arguments specify the size of the output -/// image, in image pixels. Image in this context refers to image in every frame of the [Codec]. -/// If [targetWidth] and [targetHeight] are not equal to the intrinsic dimensions of the -/// image, then the image will be scaled after being decoded. If exactly one of -/// these two arguments is not equal to [_kDoNotResizeDimension], then the aspect -/// ratio will be maintained while forcing the image to match the given dimension. -/// 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, - int targetWidth, - int targetHeight, - bool allowUpscaling, -) native 'instantiateImageCodec'; - /// Loads a single image frame from a byte array into an [Image] object. /// /// This is a convenience wrapper around [instantiateImageCodec]. Prefer using @@ -1813,19 +1778,33 @@ void decodeImageFromPixels( assert(allowUpscaling || targetHeight <= height); } - final _ImageInfo imageInfo = _ImageInfo(width, height, format.index, rowBytes); - final Future codecFuture = _futurize((_Callback callback) { - return _instantiateImageCodec( - pixels, - callback, - imageInfo, - targetWidth ?? _kDoNotResizeDimension, - targetHeight ?? _kDoNotResizeDimension, - allowUpscaling, - ); + ImmutableBuffer.fromUint8List(pixels) + .then((ImmutableBuffer buffer) { + final ImageDescriptor descriptor = ImageDescriptor.raw( + buffer, + width: width, + height: height, + rowBytes: rowBytes, + pixelFormat: format, + ); + + if (!allowUpscaling) { + if (targetWidth != null && targetWidth! > descriptor.width) { + targetWidth = descriptor.width; + } + if (targetHeight != null && targetHeight! > descriptor.height) { + targetHeight = descriptor.height; + } + } + + descriptor + .instantiateCodec( + targetWidth: targetWidth, + targetHeight: targetHeight, + ) + .then((Codec codec) => codec.getNextFrame()) + .then((FrameInfo frameInfo) => callback(frameInfo.image)); }); - codecFuture.then((Codec codec) => codec.getNextFrame()) - .then((FrameInfo frameInfo) => callback(frameInfo.image)); } /// Determines the winding rule that decides how the interior of a [Path] is @@ -4464,6 +4443,130 @@ class Shadow { String toString() => 'TextShadow($color, $offset, $blurRadius)'; } +/// A handle to a read-only byte buffer that is managed by the engine. +class ImmutableBuffer extends NativeFieldWrapperClass2 { + ImmutableBuffer._(this.length); + + /// Creates a copy of the data from a [Uint8List] suitable for internal use + /// in the engine. + static Future fromUint8List(Uint8List list) { + final ImmutableBuffer instance = ImmutableBuffer._(list.length); + return _futurize((_Callback callback) { + instance._init(list, callback); + }).then((_) => instance); + } + void _init(Uint8List list, _Callback callback) native 'ImmutableBuffer_init'; + + /// The length, in bytes, of the underlying data. + final int length; + + /// Release the resources used by this object. The object is no longer usable + /// after this method is called. + void dispose() native 'ImmutableBuffer_dispose'; +} + +/// A descriptor of data that can be turned into an [Image] via a [Codec]. +/// +/// Use this class to determine the height, width, and byte size of image data +/// before decoding it. +class ImageDescriptor extends NativeFieldWrapperClass2 { + ImageDescriptor._(); + + /// Creates an image descriptor from encoded data in a supported format. + static Future encoded(ImmutableBuffer buffer) { + final ImageDescriptor descriptor = ImageDescriptor._(); + return _futurize((_Callback callback) { + return descriptor._initEncoded(buffer, callback); + }).then((_) => descriptor); + } + String? _initEncoded(ImmutableBuffer buffer, _Callback callback) native 'ImageDescriptor_initEncoded'; + + /// Creates an image descriptor from raw image pixels. + /// + /// The `pixels` parameter is the pixel data in the encoding described by + /// `format`. + /// + /// The `rowBytes` parameter is the number of bytes consumed by each row of + /// pixels in the data buffer. If unspecified, it defaults to `width` multiplied + /// by the number of bytes per pixel in the provided `format`. + // Not async because there's no expensive work to do here. + ImageDescriptor.raw( + ImmutableBuffer buffer, { + required int width, + required int height, + int? rowBytes, + required PixelFormat pixelFormat, + }) { + _width = width; + _height = height; + // We only support 4 byte pixel formats in the PixelFormat enum. + _bytesPerPixel = 4; + _initRaw(this, buffer, width, height, rowBytes ?? -1, pixelFormat.index); + } + void _initRaw(ImageDescriptor outDescriptor, ImmutableBuffer buffer, int width, int height, int rowBytes, int pixelFormat) native 'ImageDescriptor_initRaw'; + + int? _width; + int _getWidth() native 'ImageDescriptor_width'; + /// The width, in pixels, of the image. + /// + /// On the Web, this is only supported for [raw] images. + int get width => _width ??= _getWidth(); + + int? _height; + int _getHeight() native 'ImageDescriptor_height'; + /// The height, in pixels, of the image. + /// + /// On the Web, this is only supported for [raw] images. + int get height => _height ??= _getHeight(); + + int? _bytesPerPixel; + int _getBytesPerPixel() native 'ImageDescriptor_bytesPerPixel'; + /// The number of bytes per pixel in the image. + /// + /// On web, this is only supported for [raw] images. + int get bytesPerPixel => _bytesPerPixel ??= _getBytesPerPixel(); + + /// Release the resources used by this object. The object is no longer usable + /// after this method is called. + void dispose() native 'ImageDescriptor_dispose'; + + /// Creates a [Codec] object which is suitable for decoding the data in the + /// buffer to an [Image]. + /// + /// If only one of targetWidth or targetHeight are specified, the other + /// dimension will be scaled according to the aspect ratio of the supplied + /// dimension. + /// + /// If either targetWidth or targetHeight is less than or equal to zero, it + /// will be treated as if it is null. + Future instantiateCodec({int? targetWidth, int? targetHeight}) async { + if (targetWidth != null && targetWidth <= 0) { + targetWidth = null; + } + if (targetHeight != null && targetHeight <= 0) { + targetHeight = null; + } + + if (targetWidth == null && targetHeight == null) { + targetWidth = width; + targetHeight = height; + } else if (targetWidth == null && targetHeight != null) { + targetWidth = (targetHeight * (width / height)).round(); + targetHeight = targetHeight; + } else if (targetHeight == null && targetWidth != null) { + targetWidth = targetWidth; + targetHeight = targetWidth ~/ (width / height); + } + assert(targetWidth != null); + assert(targetHeight != null); + + final Codec codec = Codec._(); + _instantiateCodec(codec, targetWidth!, targetHeight!); + return codec; + } + void _instantiateCodec(Codec outCodec, int targetWidth, int targetHeight) native 'ImageDescriptor_instantiateCodec'; +} + /// Generic callback signature, used by [_futurize]. typedef _Callback = void Function(T result); diff --git a/engine/src/flutter/lib/ui/painting/codec.cc b/engine/src/flutter/lib/ui/painting/codec.cc index a2abdf29a0..0f8325c17d 100644 --- a/engine/src/flutter/lib/ui/painting/codec.cc +++ b/engine/src/flutter/lib/ui/painting/codec.cc @@ -4,238 +4,18 @@ #include "flutter/lib/ui/painting/codec.h" -#include - -#include "flutter/common/task_runners.h" -#include "flutter/fml/logging.h" -#include "flutter/fml/make_copyable.h" -#include "flutter/fml/trace_event.h" -#include "flutter/lib/ui/painting/frame_info.h" -#include "flutter/lib/ui/painting/multi_frame_codec.h" -#include "flutter/lib/ui/painting/single_frame_codec.h" -#include "third_party/skia/include/codec/SkCodec.h" -#include "third_party/skia/include/core/SkPixelRef.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/dart_state.h" #include "third_party/tonic/logging/dart_invoke.h" #include "third_party/tonic/typed_data/typed_list.h" -#if OS_ANDROID -#include -#endif - using tonic::DartInvoke; using tonic::DartPersistentValue; using tonic::ToDart; namespace flutter { -namespace { - -// This must be kept in sync with the enum in painting.dart -enum PixelFormat { - kRGBA8888, - kBGRA8888, -}; - -#if OS_ANDROID - -// Compressed image buffers are allocated on the UI thread but are deleted on a -// decoder worker thread. Android's implementation of malloc appears to -// continue growing the native heap size when the allocating thread is -// different from the freeing thread. To work around this, create an SkData -// backed by an anonymous mapping. -sk_sp MakeSkDataWithCopy(const void* data, size_t length) { - if (length == 0) { - return SkData::MakeEmpty(); - } - - size_t mapping_length = length + sizeof(size_t); - void* mapping = ::mmap(nullptr, mapping_length, PROT_READ | PROT_WRITE, - MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); - - if (mapping == MAP_FAILED) { - return SkData::MakeEmpty(); - } - - *reinterpret_cast(mapping) = mapping_length; - void* mapping_data = reinterpret_cast(mapping) + sizeof(size_t); - ::memcpy(mapping_data, data, length); - - SkData::ReleaseProc proc = [](const void* ptr, void* context) { - size_t* size_ptr = reinterpret_cast(context); - FML_DCHECK(ptr == size_ptr + 1); - if (::munmap(const_cast(context), *size_ptr) == -1) { - FML_LOG(ERROR) << "munmap of codec SkData failed"; - } - }; - - return SkData::MakeWithProc(mapping_data, length, proc, mapping); -} - -#else - -sk_sp MakeSkDataWithCopy(const void* data, size_t length) { - return SkData::MakeWithCopy(data, length); -} - -#endif // OS_ANDROID - -} // anonymous namespace - -static std::variant ConvertImageInfo( - Dart_Handle image_info_handle, - Dart_NativeArguments args) { - Dart_Handle width_handle = Dart_GetField(image_info_handle, ToDart("width")); - if (!Dart_IsInteger(width_handle)) { - return "ImageInfo.width must be an integer"; - } - Dart_Handle height_handle = - Dart_GetField(image_info_handle, ToDart("height")); - if (!Dart_IsInteger(height_handle)) { - return "ImageInfo.height must be an integer"; - } - Dart_Handle format_handle = - Dart_GetField(image_info_handle, ToDart("format")); - if (!Dart_IsInteger(format_handle)) { - return "ImageInfo.format must be an integer"; - } - Dart_Handle row_bytes_handle = - Dart_GetField(image_info_handle, ToDart("rowBytes")); - if (!Dart_IsInteger(row_bytes_handle)) { - return "ImageInfo.rowBytes must be an integer"; - } - - PixelFormat pixel_format = static_cast( - tonic::DartConverter::FromDart(format_handle)); - SkColorType color_type = kUnknown_SkColorType; - switch (pixel_format) { - case kRGBA8888: - color_type = kRGBA_8888_SkColorType; - break; - case kBGRA8888: - color_type = kBGRA_8888_SkColorType; - break; - } - if (color_type == kUnknown_SkColorType) { - return "Invalid pixel format"; - } - - int width = tonic::DartConverter::FromDart(width_handle); - if (width <= 0) { - return "width must be greater than zero"; - } - int height = tonic::DartConverter::FromDart(height_handle); - if (height <= 0) { - return "height must be greater than zero"; - } - - ImageDecoder::ImageInfo image_info; - image_info.sk_info = - SkImageInfo::Make(width, height, color_type, kPremul_SkAlphaType); - image_info.row_bytes = - tonic::DartConverter::FromDart(row_bytes_handle); - - if (image_info.row_bytes < image_info.sk_info.minRowBytes()) { - return "rowBytes does not match the width of the image"; - } - - return image_info; -} - -static void InstantiateImageCodec(Dart_NativeArguments args) { - UIDartState::ThrowIfUIOperationsProhibited(); - Dart_Handle callback_handle = Dart_GetNativeArgument(args, 1); - if (!Dart_IsClosure(callback_handle)) { - Dart_SetReturnValue(args, tonic::ToDart("Callback must be a function")); - return; - } - - Dart_Handle image_info_handle = Dart_GetNativeArgument(args, 2); - - std::optional image_info; - - if (!Dart_IsNull(image_info_handle)) { - auto image_info_results = ConvertImageInfo(image_info_handle, args); - if (auto value = - std::get_if(&image_info_results)) { - image_info = *value; - } else if (auto error = std::get_if(&image_info_results)) { - Dart_SetReturnValue(args, tonic::ToDart(*error)); - return; - } - } - - sk_sp buffer; - - { - Dart_Handle exception = nullptr; - tonic::Uint8List list = - tonic::DartConverter::FromArguments(args, 0, - exception); - if (exception) { - Dart_SetReturnValue(args, exception); - return; - } - buffer = MakeSkDataWithCopy(list.data(), list.num_elements()); - } - - if (image_info) { - const auto expected_size = - image_info->row_bytes * image_info->sk_info.height(); - if (buffer->size() < expected_size) { - Dart_SetReturnValue( - args, ToDart("Pixel buffer size does not match image size")); - return; - } - } - - const int target_width = - tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 3)); - const int target_height = - tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 4)); - const bool allow_upscaling = - tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 5)); - - std::unique_ptr codec; - bool single_frame; - if (image_info) { - single_frame = true; - } else { - codec = SkCodec::MakeFromData(buffer); - if (!codec) { - Dart_SetReturnValue(args, ToDart("Could not instantiate image codec.")); - return; - } - single_frame = codec->getFrameCount() == 1; - } - - fml::RefPtr ui_codec; - - if (single_frame) { - ImageDecoder::ImageDescriptor descriptor; - descriptor.decompressed_image_info = image_info; - - if (target_width > 0) { - descriptor.target_width = target_width; - } - if (target_height > 0) { - descriptor.target_height = target_height; - } - descriptor.image_upscaling = allow_upscaling - ? ImageUpscalingMode::kAllowed - : ImageUpscalingMode::kNotAllowed; - descriptor.data = std::move(buffer); - - ui_codec = fml::MakeRefCounted(std::move(descriptor)); - } else { - ui_codec = fml::MakeRefCounted(std::move(codec)); - } - - tonic::DartInvoke(callback_handle, {ToDart(ui_codec)}); -} - IMPLEMENT_WRAPPERTYPEINFO(ui, Codec); #define FOR_EACH_BINDING(V) \ @@ -251,9 +31,6 @@ void Codec::dispose() { } void Codec::RegisterNatives(tonic::DartLibraryNatives* natives) { - natives->Register({ - {"instantiateImageCodec", InstantiateImageCodec, 6, true}, - }); natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } diff --git a/engine/src/flutter/lib/ui/painting/image_decoder.cc b/engine/src/flutter/lib/ui/painting/image_decoder.cc index c778d1ba22..7fe26cec55 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder.cc +++ b/engine/src/flutter/lib/ui/painting/image_decoder.cc @@ -8,14 +8,8 @@ #include "flutter/fml/make_copyable.h" #include "third_party/skia/include/codec/SkCodec.h" -#include "third_party/skia/src/codec/SkCodecImageGenerator.h" namespace flutter { -namespace { - -constexpr double kAspectRatioChangedThreshold = 0.01; - -} // namespace ImageDecoder::ImageDecoder( TaskRunners runners, @@ -32,52 +26,6 @@ ImageDecoder::ImageDecoder( ImageDecoder::~ImageDecoder() = default; -static double AspectRatio(const SkISize& size) { - return static_cast(size.width()) / size.height(); -} - -// Get the updated dimensions of the image. If both dimensions are specified, -// use them. If one of them is specified, respect the one that is and use the -// aspect ratio to calculate the other. If neither dimension is specified, use -// intrinsic dimensions of the image. -static SkISize GetResizedDimensions(SkISize current_size, - std::optional target_width, - std::optional target_height, - ImageUpscalingMode image_upscaling) { - if (current_size.isEmpty()) { - return SkISize::MakeEmpty(); - } - - if (image_upscaling == ImageUpscalingMode::kNotAllowed) { - if (target_width) { - target_width = std::min(current_size.width(), - static_cast(target_width.value())); - } - if (target_height) { - target_height = std::min(current_size.height(), - static_cast(target_height.value())); - } - } - - if (target_width && target_height) { - return SkISize::Make(target_width.value(), target_height.value()); - } - - const auto aspect_ratio = AspectRatio(current_size); - - if (target_width) { - return SkISize::Make(target_width.value(), - target_width.value() / aspect_ratio); - } - - if (target_height) { - return SkISize::Make(target_height.value() * aspect_ratio, - target_height.value()); - } - - return current_size; -} - static sk_sp ResizeRasterImage(sk_sp image, const SkISize& resized_dimensions, const fml::tracing::TraceFlow& flow) { @@ -95,19 +43,6 @@ static sk_sp ResizeRasterImage(sk_sp image, return image->makeRasterImage(); } - // TODO(dnfield): remove this in favor of clearer constraints. - // https://github.com/flutter/flutter/issues/59578 - const bool aspect_ratio_changed = - std::abs(AspectRatio(resized_dimensions) - - AspectRatio(image->dimensions())) > kAspectRatioChangedThreshold; - if (aspect_ratio_changed) { - // This is probably a bug. If a user passes dimensions that change the - // aspect ratio in a "caching" context that's probably not working as - // intended and rather a signal that the API is hard to use. - FML_LOG(WARNING) - << "Aspect ratio changes. Are cache(Height|Width) used correctly?"; - } - const auto scaled_image_info = image->imageInfo().makeDimensions(resized_dimensions); @@ -138,15 +73,14 @@ static sk_sp ResizeRasterImage(sk_sp image, } static sk_sp ImageFromDecompressedData( - sk_sp data, - ImageDecoder::ImageInfo info, - std::optional target_width, - std::optional target_height, - ImageUpscalingMode image_upscaling, + fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height, const fml::tracing::TraceFlow& flow) { TRACE_EVENT0("flutter", __FUNCTION__); flow.Step(__FUNCTION__); - auto image = SkImage::MakeRasterData(info.sk_info, data, info.row_bytes); + auto image = SkImage::MakeRasterData( + descriptor->image_info(), descriptor->data(), descriptor->row_bytes()); if (!image) { FML_LOG(ERROR) << "Could not create image from decompressed bytes."; @@ -158,46 +92,27 @@ static sk_sp ImageFromDecompressedData( return image->makeRasterImage(); } - auto resized_dimensions = GetResizedDimensions( - image->dimensions(), target_width, target_height, image_upscaling); - - return ResizeRasterImage(std::move(image), resized_dimensions, flow); + return ResizeRasterImage(std::move(image), + SkISize::Make(target_width, target_height), flow); } -sk_sp ImageFromCompressedData(sk_sp data, - std::optional target_width, - std::optional target_height, - ImageUpscalingMode image_upscaling, +sk_sp ImageFromCompressedData(fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height, const fml::tracing::TraceFlow& flow) { TRACE_EVENT0("flutter", __FUNCTION__); flow.Step(__FUNCTION__); - if (!target_width && !target_height) { + if (!descriptor->should_resize(target_width, target_height)) { // No resizing requested. Just decode & rasterize the image. - return SkImage::MakeFromEncoded(data)->makeRasterImage(); + return SkImage::MakeFromEncoded(descriptor->data())->makeRasterImage(); } - auto codec = SkCodec::MakeFromData(data); - if (codec == nullptr) { - return nullptr; - } + const SkISize source_dimensions = descriptor->image_info().dimensions(); + const SkISize resized_dimensions = {static_cast(target_width), + static_cast(target_height)}; - const auto* codec_ptr = codec.get(); - - // Note that we cannot read the dimensions from the codec since they don't - // respect image orientation provided e.g. in EXIF data. - auto image_generator = SkCodecImageGenerator::MakeFromCodec(std::move(codec)); - const auto& source_dimensions = image_generator->getInfo().dimensions(); - - auto resized_dimensions = GetResizedDimensions( - source_dimensions, target_width, target_height, image_upscaling); - - // No resize needed. - if (resized_dimensions == source_dimensions) { - return SkImage::MakeFromEncoded(data)->makeRasterImage(); - } - - auto decode_dimensions = codec_ptr->getScaledDimensions( + auto decode_dimensions = descriptor->get_scaled_dimensions( std::max(static_cast(resized_dimensions.width()) / source_dimensions.width(), static_cast(resized_dimensions.height()) / @@ -205,14 +120,9 @@ sk_sp ImageFromCompressedData(sk_sp data, // If the codec supports efficient sub-pixel decoding, decoded at a resolution // close to the target resolution before resizing. - if (decode_dimensions != codec_ptr->dimensions()) { - if (source_dimensions != codec_ptr->dimensions()) { - decode_dimensions = - SkISize::Make(decode_dimensions.height(), decode_dimensions.width()); - } - + if (decode_dimensions != source_dimensions) { auto scaled_image_info = - image_generator->getInfo().makeDimensions(decode_dimensions); + descriptor->image_info().makeDimensions(decode_dimensions); SkBitmap scaled_bitmap; if (!scaled_bitmap.tryAllocPixels(scaled_image_info)) { @@ -222,8 +132,7 @@ sk_sp ImageFromCompressedData(sk_sp data, } const auto& pixmap = scaled_bitmap.pixmap(); - if (image_generator->getPixels(pixmap.info(), pixmap.writable_addr(), - pixmap.rowBytes())) { + if (descriptor->get_pixels(pixmap)) { // Marking this as immutable makes the MakeFromBitmap call share // the pixels instead of copying. scaled_bitmap.setImmutable(); @@ -240,7 +149,7 @@ sk_sp ImageFromCompressedData(sk_sp data, } } - auto image = SkImage::MakeFromEncoded(data); + auto image = SkImage::MakeFromEncoded(descriptor->data()); if (!image) { return nullptr; } @@ -304,7 +213,9 @@ static SkiaGPUObject UploadRasterImage( return result; } -void ImageDecoder::Decode(ImageDescriptor descriptor, +void ImageDecoder::Decode(fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height, const ImageResult& callback) { TRACE_EVENT0("flutter", __FUNCTION__); fml::tracing::TraceFlow flow(__FUNCTION__); @@ -326,7 +237,7 @@ void ImageDecoder::Decode(ImageDescriptor descriptor, })); }; - if (!descriptor.data || descriptor.data->size() == 0) { + if (!descriptor->data() || descriptor->data()->size() == 0) { result({}, std::move(flow)); return; } @@ -336,26 +247,23 @@ void ImageDecoder::Decode(ImageDescriptor descriptor, io_manager = io_manager_, // io_runner = runners_.GetIOTaskRunner(), // result, // + target_width = target_width, // + target_height = target_height, // flow = std::move(flow) // ]() mutable { // Step 1: Decompress the image. // On Worker. auto decompressed = - descriptor.decompressed_image_info - ? ImageFromDecompressedData( - std::move(descriptor.data), // - descriptor.decompressed_image_info.value(), // - descriptor.target_width, // - descriptor.target_height, // - descriptor.image_upscaling, // - flow // - ) - : ImageFromCompressedData(std::move(descriptor.data), // - descriptor.target_width, // - descriptor.target_height, // - descriptor.image_upscaling, // - flow); + descriptor->is_compressed() + ? ImageFromCompressedData(std::move(descriptor), // + target_width, // + target_height, // + flow) + : ImageFromDecompressedData(std::move(descriptor), // + target_width, // + target_height, // + flow); if (!decompressed) { FML_LOG(ERROR) << "Could not decompress image."; diff --git a/engine/src/flutter/lib/ui/painting/image_decoder.h b/engine/src/flutter/lib/ui/painting/image_decoder.h index 81e216a8a6..dbcf4701d0 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder.h +++ b/engine/src/flutter/lib/ui/painting/image_decoder.h @@ -15,6 +15,7 @@ #include "flutter/fml/mapping.h" #include "flutter/fml/trace_event.h" #include "flutter/lib/ui/io_manager.h" +#include "flutter/lib/ui/painting/image_descriptor.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkImageInfo.h" @@ -23,9 +24,6 @@ namespace flutter { -// Whether to allow for image upscaling when resizing an image. -enum class ImageUpscalingMode { kAllowed, kNotAllowed }; - // An object that coordinates image decompression and texture upload across // multiple threads/components in the shell. This object must be created, // accessed and collected on the UI thread (typically the engine or its runtime @@ -40,19 +38,6 @@ class ImageDecoder { ~ImageDecoder(); - struct ImageInfo { - SkImageInfo sk_info = {}; - size_t row_bytes = 0; - }; - - struct ImageDescriptor { - sk_sp data; - std::optional decompressed_image_info; - std::optional target_width; - std::optional target_height; - ImageUpscalingMode image_upscaling = ImageUpscalingMode::kNotAllowed; - }; - using ImageResult = std::function)>; // Takes an image descriptor and returns a handle to a texture resident on the @@ -60,7 +45,10 @@ class ImageDecoder { // concurrently. Texture upload is done on the IO thread and the result // returned back on the UI thread. On error, the texture is null but the // callback is guaranteed to return on the UI thread. - void Decode(ImageDescriptor descriptor, const ImageResult& result); + void Decode(fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height, + const ImageResult& result); fml::WeakPtr GetWeakPtr() const; @@ -73,10 +61,9 @@ class ImageDecoder { FML_DISALLOW_COPY_AND_ASSIGN(ImageDecoder); }; -sk_sp ImageFromCompressedData(sk_sp data, - std::optional target_width, - std::optional target_height, - ImageUpscalingMode image_upscaling, +sk_sp ImageFromCompressedData(fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height, const fml::tracing::TraceFlow& flow); } // namespace flutter diff --git a/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc b/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc index 582df460d8..8389429d17 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc +++ b/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc @@ -158,17 +158,18 @@ TEST_F(ImageDecoderFixtureTest, InvalidImageResultsError) { ImageDecoder decoder(runners, loop->GetTaskRunner(), manager.GetWeakIOManager()); - ImageDecoder::ImageDescriptor image_descriptor; - image_descriptor.data = OpenFixtureAsSkData("ThisDoesNotExist.jpg"); + auto data = OpenFixtureAsSkData("ThisDoesNotExist.jpg"); + ASSERT_FALSE(data); - ASSERT_FALSE(image_descriptor.data); + fml::RefPtr image_descriptor = + fml::MakeRefCounted(std::move(data), nullptr); ImageDecoder::ImageResult callback = [&](SkiaGPUObject image) { ASSERT_TRUE(runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); ASSERT_FALSE(image.get()); latch.Signal(); }; - decoder.Decode(std::move(image_descriptor), callback); + decoder.Decode(image_descriptor, 0, 0, callback); }); latch.Wait(); } @@ -195,11 +196,16 @@ TEST_F(ImageDecoderFixtureTest, ValidImageResultsInSuccess) { std::make_unique(runners, loop->GetTaskRunner(), io_manager->GetWeakIOManager()); - ImageDecoder::ImageDescriptor image_descriptor; - image_descriptor.data = OpenFixtureAsSkData("DashInNooglerHat.jpg"); + auto data = OpenFixtureAsSkData("DashInNooglerHat.jpg"); - ASSERT_TRUE(image_descriptor.data); - ASSERT_GE(image_descriptor.data->size(), 0u); + ASSERT_TRUE(data); + ASSERT_GE(data->size(), 0u); + + std::unique_ptr codec = SkCodec::MakeFromData(data); + ASSERT_TRUE(codec); + + auto descriptor = + fml::MakeRefCounted(std::move(data), std::move(codec)); ImageDecoder::ImageResult callback = [&](SkiaGPUObject image) { ASSERT_TRUE(runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); @@ -208,7 +214,8 @@ TEST_F(ImageDecoderFixtureTest, ValidImageResultsInSuccess) { runners.GetIOTaskRunner()->PostTask(release_io_manager); }; EXPECT_FALSE(io_manager->did_access_is_gpu_disabled_sync_switch_); - image_decoder->Decode(std::move(image_descriptor), callback); + image_decoder->Decode(descriptor, descriptor->width(), descriptor->height(), + callback); }; auto setup_io_manager_and_decode = [&]() { @@ -244,11 +251,16 @@ TEST_F(ImageDecoderFixtureTest, ExifDataIsRespectedOnDecode) { std::make_unique(runners, loop->GetTaskRunner(), io_manager->GetWeakIOManager()); - ImageDecoder::ImageDescriptor image_descriptor; - image_descriptor.data = OpenFixtureAsSkData("Horizontal.jpg"); + auto data = OpenFixtureAsSkData("Horizontal.jpg"); - ASSERT_TRUE(image_descriptor.data); - ASSERT_GE(image_descriptor.data->size(), 0u); + ASSERT_TRUE(data); + ASSERT_GE(data->size(), 0u); + + std::unique_ptr codec = SkCodec::MakeFromData(data); + ASSERT_TRUE(codec); + + auto descriptor = + fml::MakeRefCounted(std::move(data), std::move(codec)); ImageDecoder::ImageResult callback = [&](SkiaGPUObject image) { ASSERT_TRUE(runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); @@ -256,7 +268,8 @@ TEST_F(ImageDecoderFixtureTest, ExifDataIsRespectedOnDecode) { decoded_size = image.get()->dimensions(); runners.GetIOTaskRunner()->PostTask(release_io_manager); }; - image_decoder->Decode(std::move(image_descriptor), callback); + image_decoder->Decode(descriptor, descriptor->width(), descriptor->height(), + callback); }; auto setup_io_manager_and_decode = [&]() { @@ -295,18 +308,24 @@ TEST_F(ImageDecoderFixtureTest, CanDecodeWithoutAGPUContext) { std::make_unique(runners, loop->GetTaskRunner(), io_manager->GetWeakIOManager()); - ImageDecoder::ImageDescriptor image_descriptor; - image_descriptor.data = OpenFixtureAsSkData("DashInNooglerHat.jpg"); + auto data = OpenFixtureAsSkData("DashInNooglerHat.jpg"); - ASSERT_TRUE(image_descriptor.data); - ASSERT_GE(image_descriptor.data->size(), 0u); + ASSERT_TRUE(data); + ASSERT_GE(data->size(), 0u); + + std::unique_ptr codec = SkCodec::MakeFromData(data); + ASSERT_TRUE(codec); + + auto descriptor = + fml::MakeRefCounted(std::move(data), std::move(codec)); ImageDecoder::ImageResult callback = [&](SkiaGPUObject image) { ASSERT_TRUE(runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); ASSERT_TRUE(image.get()); runners.GetIOTaskRunner()->PostTask(release_io_manager); }; - image_decoder->Decode(std::move(image_descriptor), callback); + image_decoder->Decode(descriptor, descriptor->width(), descriptor->height(), + callback); }; auto setup_io_manager_and_decode = [&]() { @@ -358,18 +377,20 @@ TEST_F(ImageDecoderFixtureTest, CanDecodeWithResizes) { latch.Wait(); // Setup a generic decoding utility that gives us the final decoded size. - auto decoded_size = [&](std::optional target_width, - std::optional target_height) -> SkISize { + auto decoded_size = [&](uint32_t target_width, + uint32_t target_height) -> SkISize { SkISize final_size = SkISize::MakeEmpty(); runners.GetUITaskRunner()->PostTask([&]() { - ImageDecoder::ImageDescriptor image_descriptor; - image_descriptor.target_width = target_width; - image_descriptor.target_height = target_height; - image_descriptor.image_upscaling = ImageUpscalingMode::kNotAllowed; - image_descriptor.data = OpenFixtureAsSkData("DashInNooglerHat.jpg"); + auto data = OpenFixtureAsSkData("DashInNooglerHat.jpg"); - ASSERT_TRUE(image_descriptor.data); - ASSERT_GE(image_descriptor.data->size(), 0u); + ASSERT_TRUE(data); + ASSERT_GE(data->size(), 0u); + + std::unique_ptr codec = SkCodec::MakeFromData(data); + ASSERT_TRUE(codec); + + auto descriptor = fml::MakeRefCounted(std::move(data), + std::move(codec)); ImageDecoder::ImageResult callback = [&](SkiaGPUObject image) { ASSERT_TRUE(runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); @@ -377,16 +398,14 @@ TEST_F(ImageDecoderFixtureTest, CanDecodeWithResizes) { final_size = image.get()->dimensions(); latch.Signal(); }; - image_decoder->Decode(std::move(image_descriptor), callback); + image_decoder->Decode(descriptor, target_width, target_height, callback); }); latch.Wait(); return final_size; }; ASSERT_EQ(SkISize::Make(3024, 4032), image_dimensions); - ASSERT_EQ(decoded_size({}, {}), image_dimensions); - ASSERT_EQ(decoded_size(100, {}), SkISize::Make(100, 133)); - ASSERT_EQ(decoded_size({}, 100), SkISize::Make(75, 100)); + ASSERT_EQ(decoded_size(3024, 4032), image_dimensions); ASSERT_EQ(decoded_size(100, 100), SkISize::Make(100, 100)); // Destroy the IO manager @@ -405,7 +424,8 @@ TEST_F(ImageDecoderFixtureTest, CanDecodeWithResizes) { } TEST_F(ImageDecoderFixtureTest, CanResizeWithoutDecode) { - ImageDecoder::ImageInfo info = {}; + SkImageInfo info = {}; + size_t row_bytes; sk_sp decompressed_data; SkISize image_dimensions = SkISize::MakeEmpty(); { @@ -415,17 +435,17 @@ TEST_F(ImageDecoderFixtureTest, CanResizeWithoutDecode) { image_dimensions = image->dimensions(); SkPixmap pixmap; ASSERT_TRUE(image->peekPixels(&pixmap)); - info.sk_info = SkImageInfo::MakeN32Premul(image_dimensions); - info.row_bytes = pixmap.rowBytes(); + info = SkImageInfo::MakeN32Premul(image_dimensions); + row_bytes = pixmap.rowBytes(); decompressed_data = SkData::MakeWithCopy(pixmap.writable_addr(), pixmap.computeByteSize()); } - // This is not susecptible to changes in the underlying image decoder. + // This is not susceptible to changes in the underlying image decoder. ASSERT_EQ(decompressed_data->size(), 48771072u); ASSERT_EQ(decompressed_data->size(), image_dimensions.width() * image_dimensions.height() * 4u); - ASSERT_EQ(info.row_bytes, image_dimensions.width() * 4u); + ASSERT_EQ(row_bytes, image_dimensions.width() * 4u); ASSERT_FALSE(image_dimensions.isEmpty()); ASSERT_NE(image_dimensions.width(), image_dimensions.height()); @@ -458,19 +478,15 @@ TEST_F(ImageDecoderFixtureTest, CanResizeWithoutDecode) { latch.Wait(); // Setup a generic decoding utility that gives us the final decoded size. - auto decoded_size = [&](std::optional target_width, - std::optional target_height) -> SkISize { + auto decoded_size = [&](uint32_t target_width, + uint32_t target_height) -> SkISize { SkISize final_size = SkISize::MakeEmpty(); runners.GetUITaskRunner()->PostTask([&]() { - ImageDecoder::ImageDescriptor image_descriptor; - image_descriptor.target_width = target_width; - image_descriptor.target_height = target_height; - image_descriptor.image_upscaling = ImageUpscalingMode::kNotAllowed; - image_descriptor.data = decompressed_data; - image_descriptor.decompressed_image_info = info; + ASSERT_TRUE(decompressed_data); + ASSERT_GE(decompressed_data->size(), 0u); - ASSERT_TRUE(image_descriptor.data); - ASSERT_GE(image_descriptor.data->size(), 0u); + auto descriptor = fml::MakeRefCounted(decompressed_data, + info, row_bytes); ImageDecoder::ImageResult callback = [&](SkiaGPUObject image) { ASSERT_TRUE(runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); @@ -478,16 +494,14 @@ TEST_F(ImageDecoderFixtureTest, CanResizeWithoutDecode) { final_size = image.get()->dimensions(); latch.Signal(); }; - image_decoder->Decode(std::move(image_descriptor), callback); + image_decoder->Decode(descriptor, target_width, target_height, callback); }); latch.Wait(); return final_size; }; ASSERT_EQ(SkISize::Make(3024, 4032), image_dimensions); - ASSERT_EQ(decoded_size({}, {}), image_dimensions); - ASSERT_EQ(decoded_size(100, {}), SkISize::Make(100, 133)); - ASSERT_EQ(decoded_size({}, 100), SkISize::Make(75, 100)); + ASSERT_EQ(decoded_size(3024, 4032), image_dimensions); ASSERT_EQ(decoded_size(100, 100), SkISize::Make(100, 100)); // Destroy the IO manager @@ -533,61 +547,30 @@ TEST(ImageDecoderTest, VerifySimpleDecoding) { ASSERT_TRUE(image != nullptr); ASSERT_EQ(SkISize::Make(600, 200), image->dimensions()); - ASSERT_EQ(ImageFromCompressedData(data, 6, 2, ImageUpscalingMode::kNotAllowed, - fml::tracing::TraceFlow("")) - ->dimensions(), - SkISize::Make(6, 2)); -} - -TEST(ImageDecoderTest, VerifySimpleDecodingNoUpscaling) { - auto data = OpenFixtureAsSkData("Horizontal.jpg"); - auto image = SkImage::MakeFromEncoded(data); - ASSERT_TRUE(image != nullptr); - ASSERT_EQ(SkISize::Make(600, 200), image->dimensions()); + auto codec = SkCodec::MakeFromData(data); + ASSERT_TRUE(codec); + auto descriptor = + fml::MakeRefCounted(std::move(data), std::move(codec)); ASSERT_EQ( - ImageFromCompressedData(data, 900, 300, ImageUpscalingMode::kNotAllowed, - fml::tracing::TraceFlow("")) + ImageFromCompressedData(descriptor, 6, 2, fml::tracing::TraceFlow("")) ->dimensions(), - SkISize::Make(600, 200)); -} - -TEST(ImageDecoderTest, VerifySimpleDecodingNoUpscalingOneDimension) { - auto data = OpenFixtureAsSkData("Horizontal.jpg"); - auto image = SkImage::MakeFromEncoded(data); - ASSERT_TRUE(image != nullptr); - ASSERT_EQ(SkISize::Make(600, 200), image->dimensions()); - - ASSERT_EQ( - ImageFromCompressedData(data, 1200, 200, ImageUpscalingMode::kNotAllowed, - fml::tracing::TraceFlow("")) - ->dimensions(), - SkISize::Make(600, 200)); -} - -TEST(ImageDecoderTest, VerifySimpleDecodingWithUpscaling) { - auto data = OpenFixtureAsSkData("Horizontal.jpg"); - auto image = SkImage::MakeFromEncoded(data); - ASSERT_TRUE(image != nullptr); - ASSERT_EQ(SkISize::Make(600, 200), image->dimensions()); - - ASSERT_EQ( - ImageFromCompressedData(data, 900, 300, ImageUpscalingMode::kAllowed, - fml::tracing::TraceFlow("")) - ->dimensions(), - SkISize::Make(900, 300)); + SkISize::Make(6, 2)); } TEST(ImageDecoderTest, VerifySubpixelDecodingPreservesExifOrientation) { auto data = OpenFixtureAsSkData("Horizontal.jpg"); + auto codec = SkCodec::MakeFromData(data); + ASSERT_TRUE(codec); + auto descriptor = + fml::MakeRefCounted(data, std::move(codec)); + auto image = SkImage::MakeFromEncoded(data); ASSERT_TRUE(image != nullptr); ASSERT_EQ(SkISize::Make(600, 200), image->dimensions()); - auto decode = [data](std::optional target_width, - std::optional target_height) { - return ImageFromCompressedData(data, target_width, target_height, - ImageUpscalingMode::kNotAllowed, + auto decode = [descriptor](uint32_t target_width, uint32_t target_height) { + return ImageFromCompressedData(descriptor, target_width, target_height, fml::tracing::TraceFlow("")); }; @@ -602,8 +585,6 @@ TEST(ImageDecoderTest, VerifySubpixelDecodingPreservesExifOrientation) { }; assert_image(decode(300, 100)); - assert_image(decode(300, {})); - assert_image(decode({}, 100)); } TEST_F(ImageDecoderFixtureTest, @@ -629,7 +610,9 @@ TEST_F(ImageDecoderFixtureTest, ASSERT_TRUE(gif_mapping); - auto gif_codec = SkCodec::MakeFromData(gif_mapping); + auto gif_codec = std::shared_ptr( + static_cast( + SkCodecImageGenerator::MakeFromEncodedCodec(gif_mapping).release())); ASSERT_TRUE(gif_codec); TaskRunners runners(GetCurrentTestName(), // label diff --git a/engine/src/flutter/lib/ui/painting/image_descriptor.cc b/engine/src/flutter/lib/ui/painting/image_descriptor.cc new file mode 100644 index 0000000000..e63e39d42b --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_descriptor.cc @@ -0,0 +1,131 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/lib/ui/painting/image_descriptor.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "flutter/lib/ui/painting/codec.h" +#include "flutter/lib/ui/painting/image_decoder.h" +#include "flutter/lib/ui/painting/multi_frame_codec.h" +#include "flutter/lib/ui/painting/single_frame_codec.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "third_party/skia/src/codec/SkCodecImageGenerator.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/logging/dart_invoke.h" + +namespace flutter { + +IMPLEMENT_WRAPPERTYPEINFO(ui, ImageDescriptor); + +#define FOR_EACH_BINDING(V) \ + V(ImageDescriptor, initRaw) \ + V(ImageDescriptor, instantiateCodec) \ + V(ImageDescriptor, width) \ + V(ImageDescriptor, height) \ + V(ImageDescriptor, bytesPerPixel) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void ImageDescriptor::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register( + {{"ImageDescriptor_initEncoded", ImageDescriptor::initEncoded, 3, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +const SkImageInfo ImageDescriptor::CreateImageInfo() const { + if (!generator_) { + return SkImageInfo::MakeUnknown(); + } + return generator_->getInfo(); +} + +ImageDescriptor::ImageDescriptor(sk_sp buffer, + const SkImageInfo& image_info, + std::optional row_bytes) + : buffer_(std::move(buffer)), + generator_(nullptr), + image_info_(std::move(image_info)), + row_bytes_(row_bytes) {} + +ImageDescriptor::ImageDescriptor(sk_sp buffer, + std::unique_ptr codec) + : buffer_(std::move(buffer)), + generator_(std::shared_ptr( + static_cast( + SkCodecImageGenerator::MakeFromCodec(std::move(codec)) + .release()))), + image_info_(CreateImageInfo()), + row_bytes_(std::nullopt) {} + +void ImageDescriptor::initEncoded(Dart_NativeArguments args) { + Dart_Handle callback_handle = Dart_GetNativeArgument(args, 2); + if (!Dart_IsClosure(callback_handle)) { + Dart_SetReturnValue(args, tonic::ToDart("Callback must be a function")); + return; + } + + Dart_Handle descriptor_handle = Dart_GetNativeArgument(args, 0); + ImmutableBuffer* immutable_buffer = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 1)); + + if (!immutable_buffer) { + Dart_SetReturnValue(args, + tonic::ToDart("Buffer parameter must not be null")); + return; + } + + std::unique_ptr codec = + SkCodec::MakeFromData(immutable_buffer->data()); + if (!codec) { + Dart_SetReturnValue(args, tonic::ToDart("Invalid image data")); + return; + } + + auto descriptor = fml::MakeRefCounted( + immutable_buffer->data(), std::move(codec)); + + descriptor->AssociateWithDartWrapper(descriptor_handle); + tonic::DartInvoke(callback_handle, {Dart_TypeVoid()}); +} + +void ImageDescriptor::initRaw(Dart_Handle descriptor_handle, + fml::RefPtr data, + int width, + int height, + int row_bytes, + PixelFormat pixel_format) { + SkColorType color_type = kUnknown_SkColorType; + switch (pixel_format) { + case PixelFormat::kRGBA8888: + color_type = kRGBA_8888_SkColorType; + break; + case PixelFormat::kBGRA8888: + color_type = kBGRA_8888_SkColorType; + break; + } + FML_DCHECK(color_type != kUnknown_SkColorType); + auto image_info = + SkImageInfo::Make(width, height, color_type, kPremul_SkAlphaType); + auto descriptor = fml::MakeRefCounted( + data->data(), std::move(image_info), + row_bytes == -1 ? std::nullopt : std::optional(row_bytes)); + descriptor->AssociateWithDartWrapper(descriptor_handle); +} + +void ImageDescriptor::instantiateCodec(Dart_Handle codec_handle, + int target_width, + int target_height) { + fml::RefPtr ui_codec; + if (!generator_ || generator_->getFrameCount() == 1) { + ui_codec = fml::MakeRefCounted( + static_cast>(this), target_width, + target_height); + } else { + ui_codec = fml::MakeRefCounted(generator_); + } + ui_codec->AssociateWithDartWrapper(codec_handle); +} +} // namespace flutter diff --git a/engine/src/flutter/lib/ui/painting/image_descriptor.h b/engine/src/flutter/lib/ui/painting/image_descriptor.h new file mode 100644 index 0000000000..15ada34152 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_descriptor.h @@ -0,0 +1,139 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_DESCRIPTOR_H_ +#define FLUTTER_LIB_UI_PAINTING_IMAGE_DESCRIPTOR_H_ + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/lib/ui/dart_wrapper.h" +#include "flutter/lib/ui/painting/immutable_buffer.h" +#include "third_party/skia/include/codec/SkCodec.h" +#include "third_party/skia/include/core/SkImageInfo.h" +#include "third_party/skia/src/codec/SkCodecImageGenerator.h" +#include "third_party/tonic/dart_library_natives.h" + +namespace flutter { + +/// Creates an image descriptor for encoded or decoded image data, describing +/// the width, height, and bytes per pixel for that image. +/// +/// This class will hold a reference on the underlying image data, and in the +/// case of compressed data, an SkCodec and SkImageGenerator for the data. +/// The Codec initialization actually happens in initEncoded, making +/// initstantiateCodec a lightweight operation. +class ImageDescriptor : public RefCountedDartWrappable { + public: + ~ImageDescriptor() override = default; + + // This must be kept in sync with the enum in painting.dart + enum PixelFormat { + kRGBA8888, + kBGRA8888, + }; + + /// Asynchronously initlializes an ImageDescriptor for an encoded image, as + /// long as the format is supported by Skia. + /// + /// Calling this method will result in creating an SkCodec and + /// SkImageGenerator to read EXIF corrected dimensions from the image data. + static void initEncoded(Dart_NativeArguments args); + + /// Synchronously initializes an ImageDescriptor for decompressed image data + /// as specified by the PixelFormat. + static void initRaw(Dart_Handle descriptor_handle, + fml::RefPtr data, + int width, + int height, + int row_bytes, + PixelFormat pixel_format); + + /// Associates a flutter::Codec object with the dart.ui Codec handle. + void instantiateCodec(Dart_Handle codec, int target_width, int target_height); + + /// The width of this image, EXIF oriented if applicable. + int width() const { return image_info_.width(); } + + /// The height of this image. EXIF oriented if applicable. + int height() const { return image_info_.height(); } + + /// The bytes per pixel of the image. + int bytesPerPixel() const { return image_info_.bytesPerPixel(); } + + /// The byte length of the first row of the image. + /// + /// Defaults to width() * 4. + int row_bytes() const { + return row_bytes_.value_or( + static_cast(image_info_.width() * image_info_.bytesPerPixel())); + } + + /// Whether the given target_width or target_height differ from width() and + /// height() respectively. + bool should_resize(int target_width, int target_height) const { + return target_width != width() || target_height != height(); + } + + /// The underlying buffer for this image. + sk_sp data() const { return buffer_; } + + /// Whether this descriptor represents compressed (encoded) data or not. + bool is_compressed() const { return !!generator_; } + + /// The orientation corrected image info for this image. + const SkImageInfo& image_info() const { return image_info_; } + + SkISize get_scaled_dimensions(float scale) { + if (!generator_) { + FML_DCHECK(false); + return image_info_.dimensions(); + } + return generator_->getScaledDimensions(scale); + } + + /// Gets pixels for this image transformed based on the EXIF orientation tag, + /// if applicable. + bool get_pixels(const SkPixmap& pixmap) const { + FML_DCHECK(generator_); + return generator_->getPixels(pixmap.info(), pixmap.writable_addr(), + pixmap.rowBytes()); + } + + void dispose() { + ClearDartWrapper(); + generator_.reset(); + } + + size_t GetAllocationSize() const override { + return sizeof(ImageDescriptor) + sizeof(SkImageInfo) + buffer_->size(); + } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + ImageDescriptor(sk_sp buffer, + const SkImageInfo& image_info, + std::optional row_bytes); + ImageDescriptor(sk_sp buffer, std::unique_ptr codec); + + sk_sp buffer_; + std::shared_ptr generator_; + const SkImageInfo image_info_; + std::optional row_bytes_; + + const SkImageInfo CreateImageInfo() const; + + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_MAKE_REF_COUNTED(ImageDescriptor); + FML_DISALLOW_COPY_AND_ASSIGN(ImageDescriptor); + + friend class ImageDecoderFixtureTest; +}; + +} // namespace flutter + +#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_DESCRIPTOR_H_ diff --git a/engine/src/flutter/lib/ui/painting/immutable_buffer.cc b/engine/src/flutter/lib/ui/painting/immutable_buffer.cc new file mode 100644 index 0000000000..c62ad3bb71 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/immutable_buffer.cc @@ -0,0 +1,99 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/lib/ui/painting/immutable_buffer.h" + +#include "flutter/lib/ui/ui_dart_state.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_args.h" +#include "third_party/tonic/dart_binding_macros.h" + +#if OS_ANDROID +#include +#endif + +namespace flutter { + +IMPLEMENT_WRAPPERTYPEINFO(ui, ImmutableBuffer); + +#define FOR_EACH_BINDING(V) \ + V(ImmutableBuffer, dispose) \ + V(ImmutableBuffer, length) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +ImmutableBuffer::~ImmutableBuffer() {} + +void ImmutableBuffer::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({{"ImmutableBuffer_init", ImmutableBuffer::init, 3, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +void ImmutableBuffer::init(Dart_NativeArguments args) { + Dart_Handle callback_handle = Dart_GetNativeArgument(args, 2); + if (!Dart_IsClosure(callback_handle)) { + Dart_SetReturnValue(args, tonic::ToDart("Callback must be a function")); + return; + } + + Dart_Handle buffer_handle = Dart_GetNativeArgument(args, 0); + tonic::Uint8List data = tonic::Uint8List(Dart_GetNativeArgument(args, 1)); + + auto sk_data = MakeSkDataWithCopy(data.data(), data.num_elements()); + data.Release(); + auto buffer = fml::MakeRefCounted(sk_data); + buffer->AssociateWithDartWrapper(buffer_handle); + tonic::DartInvoke(callback_handle, {Dart_TypeVoid()}); +} + +size_t ImmutableBuffer::GetAllocationSize() const { + return sizeof(ImmutableBuffer) + data_->size(); +} + +#if OS_ANDROID + +// Compressed image buffers are allocated on the UI thread but are deleted on a +// decoder worker thread. Android's implementation of malloc appears to +// continue growing the native heap size when the allocating thread is +// different from the freeing thread. To work around this, create an SkData +// backed by an anonymous mapping. +sk_sp ImmutableBuffer::MakeSkDataWithCopy(const void* data, + size_t length) { + if (length == 0) { + return SkData::MakeEmpty(); + } + + size_t mapping_length = length + sizeof(size_t); + void* mapping = ::mmap(nullptr, mapping_length, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); + + if (mapping == MAP_FAILED) { + return SkData::MakeEmpty(); + } + + *reinterpret_cast(mapping) = mapping_length; + void* mapping_data = reinterpret_cast(mapping) + sizeof(size_t); + ::memcpy(mapping_data, data, length); + + SkData::ReleaseProc proc = [](const void* ptr, void* context) { + size_t* size_ptr = reinterpret_cast(context); + FML_DCHECK(ptr == size_ptr + 1); + if (::munmap(const_cast(context), *size_ptr) == -1) { + FML_LOG(ERROR) << "munmap of codec SkData failed"; + } + }; + + return SkData::MakeWithProc(mapping_data, length, proc, mapping); +} + +#else + +sk_sp ImmutableBuffer::MakeSkDataWithCopy(const void* data, + size_t length) { + return SkData::MakeWithCopy(data, length); +} + +#endif // OS_ANDROID + +} // namespace flutter diff --git a/engine/src/flutter/lib/ui/painting/immutable_buffer.h b/engine/src/flutter/lib/ui/painting/immutable_buffer.h new file mode 100644 index 0000000000..ff7299881d --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/immutable_buffer.h @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_LIB_UI_PAINTNIG_IMMUTABLE_BUFER_H_ +#define FLUTTER_LIB_UI_PAINTNIG_IMMUTABLE_BUFER_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/lib/ui/dart_wrapper.h" +#include "third_party/skia/include/core/SkData.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/logging/dart_invoke.h" +#include "third_party/tonic/typed_data/typed_list.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// A simple opaque handle to an immutable byte buffer suitable for use +/// internally by the engine. +/// +/// This data is not known by the Dart VM. +/// +/// It is expected that C++ users of this object will not modify the data +/// argument. No Dart side calls are provided to do so. +class ImmutableBuffer : public RefCountedDartWrappable { + public: + ~ImmutableBuffer() override; + + /// Initializes a new ImmutableData from a Dart Uint8List. + /// + /// The zero indexed argument is the the caller that will be registered as the + /// Dart peer of the native ImmutableBuffer object. + /// + /// The first indexed argumented is a tonic::Uint8List of bytes to copy. + /// + /// The second indexed argument is expected to be a void callback to signal + /// when the copy has completed. + static void init(Dart_NativeArguments args); + + /// The length of the data in bytes. + size_t length() const { + FML_DCHECK(data_); + return data_->size(); + } + + /// Callers should not modify the returned data. This is not exposed to Dart. + sk_sp data() const { return data_; } + + /// Clears the Dart native fields and removes the reference to the underlying + /// byte buffer. + /// + /// The byte buffer will continue to live if other objects hold a reference to + /// it. + void dispose() { + ClearDartWrapper(); + data_.reset(); + } + + size_t GetAllocationSize() const override; + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit ImmutableBuffer(sk_sp data) : data_(std::move(data)) {} + + sk_sp data_; + + static sk_sp MakeSkDataWithCopy(const void* data, size_t length); + + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_MAKE_REF_COUNTED(ImmutableBuffer); + FML_DISALLOW_COPY_AND_ASSIGN(ImmutableBuffer); +}; + +} // namespace flutter + +#endif // FLUTTER_LIB_UI_PAINTNIG_IMMUTABLE_BUFER_H_ diff --git a/engine/src/flutter/lib/ui/painting/multi_frame_codec.cc b/engine/src/flutter/lib/ui/painting/multi_frame_codec.cc index 6c3763b1ab..b144a24f0d 100644 --- a/engine/src/flutter/lib/ui/painting/multi_frame_codec.cc +++ b/engine/src/flutter/lib/ui/painting/multi_frame_codec.cc @@ -11,15 +11,16 @@ namespace flutter { -MultiFrameCodec::MultiFrameCodec(std::unique_ptr codec) - : state_(new State(std::move(codec))) {} +MultiFrameCodec::MultiFrameCodec( + std::shared_ptr generator) + : state_(new State(std::move(generator))) {} MultiFrameCodec::~MultiFrameCodec() = default; -MultiFrameCodec::State::State(std::unique_ptr codec) - : codec_(std::move(codec)), - frameCount_(codec_->getFrameCount()), - repetitionCount_(codec_->getRepetitionCount()), +MultiFrameCodec::State::State(std::shared_ptr generator) + : generator_(std::move(generator)), + frameCount_(generator_->getFrameCount()), + repetitionCount_(generator_->getRepetitionCount()), nextFrameIndex_(0) {} static void InvokeNextFrameCallback( @@ -76,7 +77,7 @@ static bool CopyToBitmap(SkBitmap* dst, sk_sp MultiFrameCodec::State::GetNextFrameImage( fml::WeakPtr resourceContext) { SkBitmap bitmap = SkBitmap(); - SkImageInfo info = codec_->getInfo().makeColorType(kN32_SkColorType); + SkImageInfo info = generator_->getInfo().makeColorType(kN32_SkColorType); if (info.alphaType() == kUnpremul_SkAlphaType) { info = info.makeAlphaType(kPremul_SkAlphaType); } @@ -85,7 +86,7 @@ sk_sp MultiFrameCodec::State::GetNextFrameImage( SkCodec::Options options; options.fFrameIndex = nextFrameIndex_; SkCodec::FrameInfo frameInfo; - codec_->getFrameInfo(nextFrameIndex_, &frameInfo); + generator_->getFrameInfo(nextFrameIndex_, &frameInfo); const int requiredFrameIndex = frameInfo.fRequiredFrame; if (requiredFrameIndex != SkCodec::kNoFrame) { if (lastRequiredFrame_ == nullptr) { @@ -106,8 +107,8 @@ sk_sp MultiFrameCodec::State::GetNextFrameImage( } } - if (SkCodec::kSuccess != codec_->getPixels(info, bitmap.getPixels(), - bitmap.rowBytes(), &options)) { + if (!generator_->getPixels(info, bitmap.getPixels(), bitmap.rowBytes(), + &options)) { FML_LOG(ERROR) << "Could not getPixels for frame " << nextFrameIndex_; return nullptr; } @@ -143,7 +144,7 @@ void MultiFrameCodec::State::GetNextFrameAndInvokeCallback( fml::RefPtr image = CanvasImage::Create(); image->set_image({skImage, std::move(unref_queue)}); SkCodec::FrameInfo skFrameInfo; - codec_->getFrameInfo(nextFrameIndex_, &skFrameInfo); + generator_->getFrameInfo(nextFrameIndex_, &skFrameInfo); frameInfo = fml::MakeRefCounted(std::move(image), skFrameInfo.fDuration); } diff --git a/engine/src/flutter/lib/ui/painting/multi_frame_codec.h b/engine/src/flutter/lib/ui/painting/multi_frame_codec.h index 3ca317cbac..5843876046 100644 --- a/engine/src/flutter/lib/ui/painting/multi_frame_codec.h +++ b/engine/src/flutter/lib/ui/painting/multi_frame_codec.h @@ -7,12 +7,13 @@ #include "flutter/fml/macros.h" #include "flutter/lib/ui/painting/codec.h" +#include "third_party/skia/src/codec/SkCodecImageGenerator.h" namespace flutter { class MultiFrameCodec : public Codec { public: - MultiFrameCodec(std::unique_ptr codec); + MultiFrameCodec(std::shared_ptr generator); ~MultiFrameCodec() override; @@ -36,9 +37,9 @@ class MultiFrameCodec : public Codec { // shares it with the IO task runner's decoding work, and sets the live_ // member to false when it is destructed. struct State { - State(std::unique_ptr codec); + State(std::shared_ptr generator); - const std::unique_ptr codec_; + const std::shared_ptr generator_; const int frameCount_; const int repetitionCount_; diff --git a/engine/src/flutter/lib/ui/painting/single_frame_codec.cc b/engine/src/flutter/lib/ui/painting/single_frame_codec.cc index 7b77b03a1b..dbe603a5f0 100644 --- a/engine/src/flutter/lib/ui/painting/single_frame_codec.cc +++ b/engine/src/flutter/lib/ui/painting/single_frame_codec.cc @@ -10,8 +10,13 @@ namespace flutter { -SingleFrameCodec::SingleFrameCodec(ImageDecoder::ImageDescriptor descriptor) - : status_(Status::kNew), descriptor_(std::move(descriptor)) {} +SingleFrameCodec::SingleFrameCodec(fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height) + : status_(Status::kNew), + descriptor_(std::move(descriptor)), + target_width_(target_width), + target_height_(target_height) {} SingleFrameCodec::~SingleFrameCodec() = default; @@ -57,44 +62,45 @@ Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { fml::RefPtr* raw_codec_ref = new fml::RefPtr(this); - decoder->Decode(descriptor_, [raw_codec_ref](auto image) { - std::unique_ptr> codec_ref(raw_codec_ref); - fml::RefPtr codec(std::move(*codec_ref)); + decoder->Decode( + descriptor_, target_width_, target_height_, [raw_codec_ref](auto image) { + std::unique_ptr> codec_ref(raw_codec_ref); + fml::RefPtr codec(std::move(*codec_ref)); - auto state = codec->pending_callbacks_.front().dart_state().lock(); + auto state = codec->pending_callbacks_.front().dart_state().lock(); - if (!state) { - // This is probably because the isolate has been terminated before the - // image could be decoded. + if (!state) { + // This is probably because the isolate has been terminated before the + // image could be decoded. - return; - } + return; + } - tonic::DartState::Scope scope(state.get()); + tonic::DartState::Scope scope(state.get()); - if (image.get()) { - auto canvas_image = fml::MakeRefCounted(); - canvas_image->set_image(std::move(image)); + if (image.get()) { + auto canvas_image = fml::MakeRefCounted(); + canvas_image->set_image(std::move(image)); - codec->cached_frame_ = fml::MakeRefCounted( - std::move(canvas_image), 0 /* duration */); - } + codec->cached_frame_ = fml::MakeRefCounted( + std::move(canvas_image), 0 /* duration */); + } - // The cached frame is now available and should be returned to any future - // callers. - codec->status_ = Status::kComplete; + // The cached frame is now available and should be returned to any + // future callers. + codec->status_ = Status::kComplete; - // Invoke any callbacks that were provided before the frame was decoded. - Dart_Handle frame = tonic::ToDart(codec->cached_frame_); - for (const DartPersistentValue& callback : codec->pending_callbacks_) { - tonic::DartInvoke(callback.value(), {frame}); - } - codec->pending_callbacks_.clear(); - }); + // Invoke any callbacks that were provided before the frame was decoded. + Dart_Handle frame = tonic::ToDart(codec->cached_frame_); + for (const DartPersistentValue& callback : codec->pending_callbacks_) { + tonic::DartInvoke(callback.value(), {frame}); + } + codec->pending_callbacks_.clear(); + }); // The encoded data is no longer needed now that it has been handed off // to the decoder. - descriptor_.data.reset(); + descriptor_ = nullptr; status_ = Status::kInProgress; @@ -102,12 +108,11 @@ Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { } size_t SingleFrameCodec::GetAllocationSize() const { - const auto& data = descriptor_.data; - const auto data_byte_size = data ? data->size() : 0; + const auto& data_size = descriptor_->GetAllocationSize(); const auto frame_byte_size = (cached_frame_ && cached_frame_->image()) ? cached_frame_->image()->GetAllocationSize() : 0; - return data_byte_size + frame_byte_size + sizeof(this); + return data_size + frame_byte_size + sizeof(this); } } // namespace flutter diff --git a/engine/src/flutter/lib/ui/painting/single_frame_codec.h b/engine/src/flutter/lib/ui/painting/single_frame_codec.h index c3d92946ff..587bea6fed 100644 --- a/engine/src/flutter/lib/ui/painting/single_frame_codec.h +++ b/engine/src/flutter/lib/ui/painting/single_frame_codec.h @@ -9,12 +9,15 @@ #include "flutter/lib/ui/painting/codec.h" #include "flutter/lib/ui/painting/frame_info.h" #include "flutter/lib/ui/painting/image_decoder.h" +#include "flutter/lib/ui/painting/image_descriptor.h" namespace flutter { class SingleFrameCodec : public Codec { public: - SingleFrameCodec(ImageDecoder::ImageDescriptor descriptor); + SingleFrameCodec(fml::RefPtr descriptor, + uint32_t target_width, + uint32_t target_height); ~SingleFrameCodec() override; @@ -33,7 +36,9 @@ class SingleFrameCodec : public Codec { private: enum class Status { kNew, kInProgress, kComplete }; Status status_; - ImageDecoder::ImageDescriptor descriptor_; + fml::RefPtr descriptor_; + uint32_t target_width_; + uint32_t target_height_; fml::RefPtr cached_frame_; std::vector pending_callbacks_; diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart index a9bd10662b..a0fbd1da7e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart @@ -1499,15 +1499,6 @@ enum PixelFormat { bgra8888, } -class _ImageInfo { - _ImageInfo(this.width, this.height, this.format, int? rowBytes) : this.rowBytes = rowBytes ?? width * 4; - - int width; - int height; - int format; - int rowBytes; -} - /// Callback signature for [decodeImageFromList]. typedef ImageDecoderCallback = void Function(Image result); @@ -1583,20 +1574,27 @@ Future instantiateImageCodec( }) { return _futurize((engine.Callback callback) => // TODO: Implement targetWidth and targetHeight support. - _instantiateImageCodec(list, callback, null)); + _instantiateImageCodec(list, callback)); } /// Instantiates a [Codec] object for an image binary data. /// /// Returns an error message if the instantiation has failed, null otherwise. String? _instantiateImageCodec( - Uint8List list, engine.Callback callback, _ImageInfo? imageInfo) { + Uint8List list, + engine.Callback callback, { + int? width, + int? height, + int? rowBytes, + PixelFormat? format, +}) { if (engine.experimentalUseSkia) { - if (imageInfo == null) { + if (width == null) { engine.skiaInstantiateImageCodec(list, callback); } else { - engine.skiaInstantiateImageCodec(list, callback, imageInfo.width, - imageInfo.height, imageInfo.format, imageInfo.rowBytes); + assert(height != null); + assert(format != null); + engine.skiaInstantiateImageCodec(list, callback, width, height, format!.index, rowBytes); } return null; } @@ -1652,11 +1650,17 @@ void decodeImageFromPixels( int? targetHeight, bool allowUpscaling = true, }) { - final _ImageInfo imageInfo = - _ImageInfo(width, height, format.index, rowBytes); final Future codecFuture = _futurize( - (engine.Callback callback) => - _instantiateImageCodec(pixels, callback, imageInfo)); + (engine.Callback callback) { + return _instantiateImageCodec( + pixels, + callback, + width: width, + height: height, + format: format, + rowBytes: rowBytes, + ); + }); codecFuture .then((Codec codec) => codec.getNextFrame()) .then((FrameInfo frameInfo) => callback(frameInfo.image)); @@ -1845,3 +1849,110 @@ class ImageShader extends Shader { 'ImageShader not implemented for web platform.'); } } + + +/// A handle to a read-only byte buffer that is managed by the engine. +class ImmutableBuffer { + ImmutableBuffer._(this.length); + + /// Creates a copy of the data from a [Uint8List] suitable for internal use + /// in the engine. + static Future fromUint8List(Uint8List list) async { + final ImmutableBuffer instance = ImmutableBuffer._(list.length); + instance._list = list; + return instance; + } + + Uint8List? _list; + + /// The length, in bytes, of the underlying data. + final int length; + + /// Release the resources used by this object. The object is no longer usable + /// after this method is called. + void dispose() => _list = null; +} + +/// A descriptor of data that can be turned into an [Image] via a [Codec]. +/// +/// Use this class to determine the height, width, and byte size of image data +/// before decoding it. +class ImageDescriptor { + ImageDescriptor._() : _width = null, _height = null, _rowBytes = null, _format = null; + + /// Creates an image descriptor from encoded data in a supported format. + static Future encoded(ImmutableBuffer buffer) async { + final ImageDescriptor descriptor = ImageDescriptor._(); + descriptor._data = buffer._list; + return descriptor; + } + + /// Creates an image descriptor from raw image pixels. + /// + /// The `pixels` parameter is the pixel data in the encoding described by + /// `format`. + /// + /// The `rowBytes` parameter is the number of bytes consumed by each row of + /// pixels in the data buffer. If unspecified, it defaults to `width` multiplied + /// by the number of bytes per pixel in the provided `format`. + // Not async because there's no expensive work to do here. + ImageDescriptor.raw( + ImmutableBuffer buffer, { + required int width, + required int height, + int? rowBytes, + required PixelFormat pixelFormat, + }) : _width = width, _height = height, _rowBytes = rowBytes, _format = pixelFormat { + _data = buffer._list; + } + + Uint8List? _data; + final int? _width; + final int? _height; + final int? _rowBytes; + final PixelFormat? _format; + + Never _throw(String parameter) { + throw UnsupportedError('ImageDescriptor.$parameter is not supported on web.'); + } + + /// The width, in pixels, of the image. + int get width => _width ?? _throw('width'); + + /// The height, in pixels, of the image. + int get height => _height ?? _throw('height'); + + /// The number of bytes per pixel in the image. + int get bytesPerPixel => throw UnsupportedError('ImageDescriptor.bytesPerPixel is not supported on web.'); + + /// Release the resources used by this object. The object is no longer usable + /// after this method is called. + void dispose() => _data = null; + + /// Creates a [Codec] object which is suitable for decoding the data in the + /// buffer to an [Image]. + Future instantiateCodec({int? targetWidth, int? targetHeight}) { + if (_data == null) { + throw StateError('Object is disposed'); + } + if (_width == null) { + return instantiateImageCodec( + _data!, + targetWidth: targetWidth, + targetHeight: targetHeight, + allowUpscaling: false, + ); + } + return _futurize( + (engine.Callback callback) { + return _instantiateImageCodec( + _data!, + callback, + width: _width, + height: _height, + format: _format, + rowBytes: _rowBytes, + ); + }); + } +} diff --git a/engine/src/flutter/testing/dart/codec_test.dart b/engine/src/flutter/testing/dart/codec_test.dart index 8c729df531..961f54f4ac 100644 --- a/engine/src/flutter/testing/dart/codec_test.dart +++ b/engine/src/flutter/testing/dart/codec_test.dart @@ -30,7 +30,7 @@ void main() { final Uint8List data = Uint8List.fromList([1, 2, 3]); expect( () => ui.instantiateImageCodec(data), - throwsA(exceptionWithMessage('Could not instantiate image codec.')) + throwsA(exceptionWithMessage('Invalid image data')) ); }); diff --git a/engine/src/flutter/testing/dart/image_descriptor_test.dart b/engine/src/flutter/testing/dart/image_descriptor_test.dart new file mode 100644 index 0000000000..e888ee26ee --- /dev/null +++ b/engine/src/flutter/testing/dart/image_descriptor_test.dart @@ -0,0 +1,91 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// @dart = 2.6 +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; +import 'dart:ui'; + +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +void main() { + test('basic image descriptor - encoded - greyscale', () async { + final Uint8List bytes = await readFile('4x4.png'); + final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); + final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); + + expect(descriptor.width, 2); + expect(descriptor.height, 2); + expect(descriptor.bytesPerPixel, 1); + + final Codec codec = await descriptor.instantiateCodec(); + expect(codec.frameCount, 1); + }); + + test('basic image descriptor - encoded - square', () async { + final Uint8List bytes = await readFile('square.png'); + final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); + final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); + + expect(descriptor.width, 10); + expect(descriptor.height, 10); + expect(descriptor.bytesPerPixel, 4); + + final Codec codec = await descriptor.instantiateCodec(); + expect(codec.frameCount, 1); + }); + + test('basic image descriptor - encoded - animated', () async { + final Uint8List bytes = await _getSkiaResource('test640x479.gif').readAsBytes(); + final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); + final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); + + expect(descriptor.width, 640); + expect(descriptor.height, 479); + expect(descriptor.bytesPerPixel, 4); + + final Codec codec = await descriptor.instantiateCodec(); + expect(codec.frameCount, 4); + expect(codec.repetitionCount, -1); + }); + + test('basic image descriptor - raw', () async { + final Uint8List bytes = Uint8List.fromList(List.filled(16, 0xFFABCDEF)); + final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); + final ImageDescriptor descriptor = ImageDescriptor.raw( + buffer, + width: 4, + height: 4, + rowBytes: 4 * 4, + pixelFormat: PixelFormat.rgba8888, + ); + + expect(descriptor.width, 4); + expect(descriptor.height, 4); + expect(descriptor.bytesPerPixel, 4); + + final Codec codec = await descriptor.instantiateCodec(); + expect(codec.frameCount, 1); + }); +} + +Future readFile(String fileName, ) async { + final File file = + File(path.join('flutter', 'testing', 'resources', fileName)); + return await file.readAsBytes(); +} + +/// Returns a File handle to a file in the skia/resources directory. +File _getSkiaResource(String fileName) { + // As Platform.script is not working for flutter_tester + // (https://github.com/flutter/flutter/issues/12847), this is currently + // assuming the curent working directory is engine/src. + // This is fragile and should be changed once the Platform.script issue is + // resolved. + final String assetPath = + path.join('third_party', 'skia', 'resources', 'images', fileName); + return File(assetPath); +} diff --git a/engine/src/flutter/testing/dart/image_resize_test.dart b/engine/src/flutter/testing/dart/image_resize_test.dart index 484dfc48bb..c631a6c15c 100644 --- a/engine/src/flutter/testing/dart/image_resize_test.dart +++ b/engine/src/flutter/testing/dart/image_resize_test.dart @@ -169,8 +169,7 @@ void main() { test('pixels: large negative dimensions', () async { final BlackSquare blackSquare = BlackSquare.create(); - final Image resized = - await blackSquare.resize(targetHeight: -100, targetWidth: -99999); + final Image resized = await blackSquare.resize(targetHeight: -100, targetWidth: -99999); expect(resized.height, 2); expect(resized.width, 2); });