diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index b291c356e0..a6cf06c028 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -873,6 +873,8 @@ FILE: ../../../flutter/lib/ui/painting/codec.cc FILE: ../../../flutter/lib/ui/painting/codec.h FILE: ../../../flutter/lib/ui/painting/color_filter.cc FILE: ../../../flutter/lib/ui/painting/color_filter.h +FILE: ../../../flutter/lib/ui/painting/display_list_deferred_image_gpu.cc +FILE: ../../../flutter/lib/ui/painting/display_list_deferred_image_gpu.h FILE: ../../../flutter/lib/ui/painting/display_list_image_gpu.cc FILE: ../../../flutter/lib/ui/painting/display_list_image_gpu.h FILE: ../../../flutter/lib/ui/painting/engine_layer.cc diff --git a/engine/src/flutter/display_list/display_list_image.cc b/engine/src/flutter/display_list/display_list_image.cc index 1b40c14cfe..7196a4e47c 100644 --- a/engine/src/flutter/display_list/display_list_image.cc +++ b/engine/src/flutter/display_list/display_list_image.cc @@ -32,4 +32,8 @@ SkIRect DlImage::bounds() const { return SkIRect::MakeSize(dimensions()); } +std::optional DlImage::get_error() const { + return std::nullopt; +} + } // namespace flutter diff --git a/engine/src/flutter/display_list/display_list_image.h b/engine/src/flutter/display_list/display_list_image.h index ff2aad1adb..fafb1504f4 100644 --- a/engine/src/flutter/display_list/display_list_image.h +++ b/engine/src/flutter/display_list/display_list_image.h @@ -6,6 +6,8 @@ #define FLUTTER_DISPLAY_LIST_DISPLAY_LIST_IMAGE_H_ #include +#include +#include #include "flutter/fml/macros.h" #include "include/core/SkRefCnt.h" @@ -27,6 +29,9 @@ namespace flutter { /// class DlImage : public SkRefCnt { public: + // Describes which GPU context owns this image. + enum class OwningContext { kRaster, kIO }; + static sk_sp Make(const SkImage* image); static sk_sp Make(sk_sp image); @@ -81,6 +86,17 @@ class DlImage : public SkRefCnt { /// SkIRect bounds() const; + //---------------------------------------------------------------------------- + /// @return Specifies which context was used to create this image. The + /// image must be collected on the same task runner as its + /// context. + virtual OwningContext owning_context() const { return OwningContext::kIO; } + + //---------------------------------------------------------------------------- + /// @return An error, if any, that occurred when trying to create the + /// image. + virtual std::optional get_error() const; + protected: DlImage(); }; diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn index a4f45330de..80b4f773f9 100644 --- a/engine/src/flutter/lib/ui/BUILD.gn +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -30,6 +30,8 @@ source_set("ui") { "painting/codec.h", "painting/color_filter.cc", "painting/color_filter.h", + "painting/display_list_deferred_image_gpu.cc", + "painting/display_list_deferred_image_gpu.h", "painting/display_list_image_gpu.cc", "painting/display_list_image_gpu.h", "painting/engine_layer.cc", diff --git a/engine/src/flutter/lib/ui/compositing.dart b/engine/src/flutter/lib/ui/compositing.dart index ce87901e82..dbfc6918ce 100644 --- a/engine/src/flutter/lib/ui/compositing.dart +++ b/engine/src/flutter/lib/ui/compositing.dart @@ -21,6 +21,23 @@ class Scene extends NativeFieldWrapperClass1 { @pragma('vm:entry-point') Scene._(); + /// Creates a GPU resident image from this scene. + /// + /// {@macro dart.ui.painting.Picture.toGpuImage} + Image toGpuImage(int width, int height) { + if (width <= 0 || height <= 0) { + throw Exception('Invalid image dimensions.'); + } + + final _Image image = _Image._(); + final String? result = _toGpuImage(width, height, image); + if (result != null) { + throw PictureRasterizationException._(result); + } + return Image._(image, image.width, image.height); + } + String? _toGpuImage(int width, int height, _Image outImage) native 'Scene_toGpuImage'; + /// Creates a raster image representation of the current state of the scene. /// This is a slow operation that is performed on a background thread. /// @@ -35,7 +52,7 @@ class Scene extends NativeFieldWrapperClass1 { if (image == null) { callback(null); } else { - callback(Image._(image)); + callback(Image._(image, image.width, image.height)); } }), ); diff --git a/engine/src/flutter/lib/ui/compositing/scene.cc b/engine/src/flutter/lib/ui/compositing/scene.cc index a6448970f6..e42ec7c8d6 100644 --- a/engine/src/flutter/lib/ui/compositing/scene.cc +++ b/engine/src/flutter/lib/ui/compositing/scene.cc @@ -22,6 +22,7 @@ namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Scene); #define FOR_EACH_BINDING(V) \ + V(Scene, toGpuImage) \ V(Scene, toImage) \ V(Scene, dispose) @@ -66,6 +67,24 @@ void Scene::dispose() { ClearDartWrapper(); } +Dart_Handle Scene::toGpuImage(uint32_t width, + uint32_t height, + Dart_Handle raw_image_handle) { + TRACE_EVENT0("flutter", "Scene::toGpuImage"); + + if (!layer_tree_) { + return tonic::ToDart("Scene did not contain a layer tree."); + } + + auto picture = layer_tree_->Flatten(SkRect::MakeWH(width, height)); + if (!picture) { + return tonic::ToDart("Could not flatten scene into a layer tree."); + } + + Picture::RasterizeToGpuImage(picture, width, height, raw_image_handle); + return Dart_Null(); +} + Dart_Handle Scene::toImage(uint32_t width, uint32_t height, Dart_Handle raw_image_callback) { diff --git a/engine/src/flutter/lib/ui/compositing/scene.h b/engine/src/flutter/lib/ui/compositing/scene.h index f7a8d93711..29b66d150f 100644 --- a/engine/src/flutter/lib/ui/compositing/scene.h +++ b/engine/src/flutter/lib/ui/compositing/scene.h @@ -32,6 +32,10 @@ class Scene : public RefCountedDartWrappable { std::unique_ptr takeLayerTree(); + Dart_Handle toGpuImage(uint32_t width, + uint32_t height, + Dart_Handle raw_image_handle); + Dart_Handle toImage(uint32_t width, uint32_t height, Dart_Handle image_callback); diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart index f5ed75057e..91803c6112 100644 --- a/engine/src/flutter/lib/ui/painting.dart +++ b/engine/src/flutter/lib/ui/painting.dart @@ -1646,7 +1646,7 @@ enum PixelFormat { /// creating a codec to decode it. /// * [instantiateImageCodec], a utility method that wraps [ImageDescriptor]. class Image { - Image._(this._image) { + Image._(this._image, this.width, this.height) { assert(() { _debugStack = StackTrace.current; return true; @@ -1661,16 +1661,10 @@ class Image { StackTrace? _debugStack; /// The number of image pixels along the image's horizontal axis. - int get width { - assert(!_disposed && !_image._disposed); - return _image.width; - } + final int width; /// The number of image pixels along the image's vertical axis. - int get height { - assert(!_disposed && !_image._disposed); - return _image.height; - } + final int height; bool _disposed = false; /// Release this handle's claim on the underlying Image. This handle is no @@ -1820,7 +1814,7 @@ class Image { ); } assert(!_image._disposed); - return Image._(_image); + return Image._(_image, width, height); } /// Returns true if `other` is a [clone] of this and thus shares the same @@ -1999,7 +1993,7 @@ class Codec extends NativeFieldWrapperClass1 { completer.completeError(Exception('Codec failed to produce an image, possibly due to invalid image data.')); } else { completer.complete(FrameInfo._( - image: Image._(image), + image: Image._(image, image.width, image.height), duration: Duration(milliseconds: durationMilliseconds), )); } @@ -3885,10 +3879,13 @@ class ImageShader extends Shader { if (matrix4.length != 16) throw ArgumentError('"matrix4" must have 16 entries.'); _constructor(); - _initWithImage(image._image, tmx.index, tmy.index, filterQuality?.index ?? -1, matrix4); + final String? error = _initWithImage(image._image, tmx.index, tmy.index, filterQuality?.index ?? -1, matrix4); + if (error != null) { + throw Exception(error); + } } void _constructor() native 'ImageShader_constructor'; - void _initWithImage(_Image image, int tmx, int tmy, int filterQualityIndex, Float64List matrix4) native 'ImageShader_initWithImage'; + String? _initWithImage(_Image image, int tmx, int tmy, int filterQualityIndex, Float64List matrix4) native 'ImageShader_initWithImage'; } /// An instance of [FragmentProgram] creates [Shader] objects (as used by [Paint.shader]) that run SPIR-V code. @@ -4752,14 +4749,17 @@ class Canvas extends NativeFieldWrapperClass1 { assert(image != null); // image is checked on the engine side assert(_offsetIsValid(offset)); assert(paint != null); - _drawImage(image._image, offset.dx, offset.dy, paint._objects, paint._data, paint.filterQuality.index); + final String? error = _drawImage(image._image, offset.dx, offset.dy, paint._objects, paint._data, paint.filterQuality.index); + if (error != null) { + throw PictureRasterizationException._(error, stack: image._debugStack); + } } - void _drawImage(_Image image, - double x, - double y, - List? paintObjects, - ByteData paintData, - int filterQualityIndex) native 'Canvas_drawImage'; + String? _drawImage(_Image image, + double x, + double y, + List? paintObjects, + ByteData paintData, + int filterQualityIndex) native 'Canvas_drawImage'; /// Draws the subset of the given image described by the `src` argument into /// the canvas in the axis-aligned rectangle given by the `dst` argument. @@ -4775,31 +4775,34 @@ class Canvas extends NativeFieldWrapperClass1 { assert(_rectIsValid(src)); assert(_rectIsValid(dst)); assert(paint != null); - _drawImageRect(image._image, - src.left, - src.top, - src.right, - src.bottom, - dst.left, - dst.top, - dst.right, - dst.bottom, - paint._objects, - paint._data, - paint.filterQuality.index); + final String? error = _drawImageRect(image._image, + src.left, + src.top, + src.right, + src.bottom, + dst.left, + dst.top, + dst.right, + dst.bottom, + paint._objects, + paint._data, + paint.filterQuality.index); + if (error != null) { + throw PictureRasterizationException._(error, stack: image._debugStack); + } } - void _drawImageRect(_Image image, - double srcLeft, - double srcTop, - double srcRight, - double srcBottom, - double dstLeft, - double dstTop, - double dstRight, - double dstBottom, - List? paintObjects, - ByteData paintData, - int filterQualityIndex) native 'Canvas_drawImageRect'; + String? _drawImageRect(_Image image, + double srcLeft, + double srcTop, + double srcRight, + double srcBottom, + double dstLeft, + double dstTop, + double dstRight, + double dstBottom, + List? paintObjects, + ByteData paintData, + int filterQualityIndex) native 'Canvas_drawImageRect'; /// Draws the given [Image] into the canvas using the given [Paint]. /// @@ -4819,31 +4822,34 @@ class Canvas extends NativeFieldWrapperClass1 { assert(_rectIsValid(center)); assert(_rectIsValid(dst)); assert(paint != null); - _drawImageNine(image._image, - center.left, - center.top, - center.right, - center.bottom, - dst.left, - dst.top, - dst.right, - dst.bottom, - paint._objects, - paint._data, - paint.filterQuality.index); + final String? error = _drawImageNine(image._image, + center.left, + center.top, + center.right, + center.bottom, + dst.left, + dst.top, + dst.right, + dst.bottom, + paint._objects, + paint._data, + paint.filterQuality.index); + if (error != null) { + throw PictureRasterizationException._(error, stack: image._debugStack); + } } - void _drawImageNine(_Image image, - double centerLeft, - double centerTop, - double centerRight, - double centerBottom, - double dstLeft, - double dstTop, - double dstRight, - double dstBottom, - List? paintObjects, - ByteData paintData, - int filterQualityIndex) native 'Canvas_drawImageNine'; + String? _drawImageNine(_Image image, + double centerLeft, + double centerTop, + double centerRight, + double centerBottom, + double dstLeft, + double dstTop, + double dstRight, + double dstBottom, + List? paintObjects, + ByteData paintData, + int filterQualityIndex) native 'Canvas_drawImageNine'; /// Draw the given picture onto the canvas. To create a picture, see /// [PictureRecorder]. @@ -5121,10 +5127,14 @@ class Canvas extends NativeFieldWrapperClass1 { final Float32List? cullRectBuffer = cullRect?._getValue32(); final int qualityIndex = paint.filterQuality.index; - _drawAtlas( + final String? error = _drawAtlas( paint._objects, paint._data, qualityIndex, atlas._image, rstTransformBuffer, rectBuffer, colorBuffer, (blendMode ?? BlendMode.src).index, cullRectBuffer ); + + if (error != null) { + throw PictureRasterizationException._(error, stack: atlas._debugStack); + } } /// Draws many parts of an image - the [atlas] - onto the canvas. @@ -5290,21 +5300,25 @@ class Canvas extends NativeFieldWrapperClass1 { throw ArgumentError('If non-null, "colors" length must be one fourth the length of "rstTransforms" and "rects".'); final int qualityIndex = paint.filterQuality.index; - _drawAtlas( + final String? error = _drawAtlas( paint._objects, paint._data, qualityIndex, atlas._image, rstTransforms, rects, colors, (blendMode ?? BlendMode.src).index, cullRect?._getValue32() ); + + if (error != null) { + throw PictureRasterizationException._(error, stack: atlas._debugStack); + } } - void _drawAtlas(List? paintObjects, - ByteData paintData, - int filterQualityIndex, - _Image atlas, - Float32List rstTransforms, - Float32List rects, - Int32List? colors, - int blendMode, - Float32List? cullRect) native 'Canvas_drawAtlas'; + String? _drawAtlas(List? paintObjects, + ByteData paintData, + int filterQualityIndex, + _Image atlas, + Float32List rstTransforms, + Float32List rects, + Int32List? colors, + int blendMode, + Float32List? cullRect) native 'Canvas_drawAtlas'; /// Draws a shadow for a [Path] representing the given material elevation. /// @@ -5345,9 +5359,6 @@ class Picture extends NativeFieldWrapperClass1 { /// The returned image will be `width` pixels wide and `height` pixels high. /// The picture is rasterized within the 0 (left), 0 (top), `width` (right), /// `height` (bottom) bounds. Content outside these bounds is clipped. - /// - /// Although the image is returned synchronously, the picture is actually - /// rasterized the first time the image is drawn and then cached. Future toImage(int width, int height) { assert(!_disposed); if (width <= 0 || height <= 0) @@ -5357,14 +5368,39 @@ class Picture extends NativeFieldWrapperClass1 { if (image == null) { callback(null); } else { - callback(Image._(image)); + callback(Image._(image, image.width, image.height)); } }), ); } - String? _toImage(int width, int height, _Callback<_Image?> callback) native 'Picture_toImage'; + /// Creates a GPU resident image from this picture. + /// + /// {@template dart.ui.painting.Picture.toGpuImage} + /// The returned image will be `width` pixels wide and `height` pixels high. + /// The picture is rasterized within the 0 (left), 0 (top), `width` (right), + /// `height` (bottom) bounds. Content outside these bounds is clipped. + /// + /// The image object is created and returned synchronously, but is rasterized + /// asynchronously. If the rasterization fails, an exception will be thrown + /// when the image is drawn to a [Canvas]. + /// + /// In the flutter_tester, this will always created a light gray and white + /// checkerboard bitmap with the requested dimensions. + /// {@endtemplate} + Image toGpuImage(int width, int height) { + assert(!_disposed); + if (width <= 0 || height <= 0) { + throw Exception('Invalid image dimensions.'); + } + + final _Image image = _Image._(); + _toGpuImage(width, height, image); + return Image._(image, image.width, image.height); + } + void _toGpuImage(int width, int height, _Image outImage) native 'Picture_toGpuImage'; + /// Release the resources used by this object. The object is no longer usable /// after this method is called. void dispose() { @@ -5871,3 +5907,30 @@ Future _futurize(_Callbacker callbacker) { throw Exception(error); return completer.future; } + +/// An exception thrown by [Canvas.drawImage] and related methods when drawing +/// an [Image] created via [Picture.toGpuImage] that is in an invalid state. +/// +/// This exception may be thrown if the requested image dimensions exceeded the +/// maximum 2D texture size allowed by the GPU, or if no GPU surface or context +/// was available for rasterization at request time. +class PictureRasterizationException implements Exception { + const PictureRasterizationException._(this.message, {this.stack}); + + /// A string containing details about the failure. + final String message; + + /// If available, the stack trace at the time [Picture.toGpuImage] was called. + final StackTrace? stack; + + @override + String toString() { + final StringBuffer buffer = StringBuffer('Failed to rasterize a picture: $message.'); + if (stack != null) { + buffer.writeln(); + buffer.writeln('The callstack when the image was created was:'); + buffer.writeln(stack!.toString()); + } + return buffer.toString(); + } +} diff --git a/engine/src/flutter/lib/ui/painting/canvas.cc b/engine/src/flutter/lib/ui/painting/canvas.cc index 068c21a782..fea8a02b7c 100644 --- a/engine/src/flutter/lib/ui/painting/canvas.cc +++ b/engine/src/flutter/lib/ui/painting/canvas.cc @@ -385,74 +385,98 @@ void Canvas::drawPath(const CanvasPath* path, } } -void Canvas::drawImage(const CanvasImage* image, - double x, - double y, - const Paint& paint, - const PaintData& paint_data, - int filterQualityIndex) { +Dart_Handle Canvas::drawImage(const CanvasImage* image, + double x, + double y, + const Paint& paint, + const PaintData& paint_data, + int filterQualityIndex) { FML_DCHECK(paint.isNotNull()); if (!image) { - Dart_ThrowException( - ToDart("Canvas.drawImage called with non-genuine Image.")); - return; + return ToDart("Canvas.drawImage called with non-genuine Image."); } + + auto dl_image = image->image(); + if (!dl_image) { + return Dart_Null(); + } + auto error = dl_image->get_error(); + if (error) { + return ToDart(error.value()); + } + auto sampling = ImageFilter::SamplingFromIndex(filterQualityIndex); if (display_list_recorder_) { bool with_attributes = paint.sync_to(builder(), kDrawImageWithPaintFlags); - builder()->drawImage(image->image(), SkPoint::Make(x, y), sampling, + builder()->drawImage(dl_image, SkPoint::Make(x, y), sampling, with_attributes); } + return Dart_Null(); } -void Canvas::drawImageRect(const CanvasImage* image, - double src_left, - double src_top, - double src_right, - double src_bottom, - double dst_left, - double dst_top, - double dst_right, - double dst_bottom, - const Paint& paint, - const PaintData& paint_data, - int filterQualityIndex) { +Dart_Handle Canvas::drawImageRect(const CanvasImage* image, + double src_left, + double src_top, + double src_right, + double src_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data, + int filterQualityIndex) { FML_DCHECK(paint.isNotNull()); if (!image) { - Dart_ThrowException( - ToDart("Canvas.drawImageRect called with non-genuine Image.")); - return; + return ToDart("Canvas.drawImageRect called with non-genuine Image."); } + + auto dl_image = image->image(); + if (!dl_image) { + return Dart_Null(); + } + auto error = dl_image->get_error(); + if (error) { + return ToDart(error.value()); + } + SkRect src = SkRect::MakeLTRB(src_left, src_top, src_right, src_bottom); SkRect dst = SkRect::MakeLTRB(dst_left, dst_top, dst_right, dst_bottom); auto sampling = ImageFilter::SamplingFromIndex(filterQualityIndex); if (display_list_recorder_) { bool with_attributes = paint.sync_to(builder(), kDrawImageRectWithPaintFlags); - builder()->drawImageRect(image->image(), src, dst, sampling, - with_attributes, + builder()->drawImageRect(dl_image, src, dst, sampling, with_attributes, SkCanvas::kFast_SrcRectConstraint); } + return Dart_Null(); } -void Canvas::drawImageNine(const CanvasImage* image, - double center_left, - double center_top, - double center_right, - double center_bottom, - double dst_left, - double dst_top, - double dst_right, - double dst_bottom, - const Paint& paint, - const PaintData& paint_data, - int bitmapSamplingIndex) { +Dart_Handle Canvas::drawImageNine(const CanvasImage* image, + double center_left, + double center_top, + double center_right, + double center_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data, + int bitmapSamplingIndex) { FML_DCHECK(paint.isNotNull()); if (!image) { - Dart_ThrowException( - ToDart("Canvas.drawImageNine called with non-genuine Image.")); - return; + return ToDart("Canvas.drawImageNine called with non-genuine Image."); } + auto dl_image = image->image(); + if (!dl_image) { + return Dart_Null(); + } + auto error = dl_image->get_error(); + if (error) { + return ToDart(error.value()); + } + SkRect center = SkRect::MakeLTRB(center_left, center_top, center_right, center_bottom); SkIRect icenter; @@ -462,9 +486,9 @@ void Canvas::drawImageNine(const CanvasImage* image, if (display_list_recorder_) { bool with_attributes = paint.sync_to(builder(), kDrawImageNineWithPaintFlags); - builder()->drawImageNine(image->image(), icenter, dst, filter, - with_attributes); + builder()->drawImageNine(dl_image, icenter, dst, filter, with_attributes); } + return Dart_Null(); } void Canvas::drawPicture(Picture* picture) { @@ -526,23 +550,34 @@ void Canvas::drawVertices(const Vertices* vertices, } } -void Canvas::drawAtlas(const Paint& paint, - const PaintData& paint_data, - int filterQualityIndex, - CanvasImage* atlas, - const tonic::Float32List& transforms, - const tonic::Float32List& rects, - const tonic::Int32List& colors, - DlBlendMode blend_mode, - const tonic::Float32List& cull_rect) { +Dart_Handle Canvas::drawAtlas(const Paint& paint, + const PaintData& paint_data, + int filterQualityIndex, + CanvasImage* atlas, + tonic::Float32List& transforms, + tonic::Float32List& rects, + tonic::Int32List& colors, + DlBlendMode blend_mode, + tonic::Float32List& cull_rect) { if (!atlas) { - Dart_ThrowException( - ToDart("Canvas.drawAtlas or Canvas.drawRawAtlas called with " - "non-genuine Image.")); - return; + transforms.Release(); + rects.Release(); + colors.Release(); + cull_rect.Release(); + return ToDart( + "Canvas.drawAtlas or Canvas.drawRawAtlas called with " + "non-genuine Image."); } auto dl_image = atlas->image(); + auto error = dl_image->get_error(); + if (error) { + transforms.Release(); + rects.Release(); + colors.Release(); + cull_rect.Release(); + return ToDart(error.value()); + } static_assert(sizeof(SkRSXform) == sizeof(float) * 4, "SkRSXform doesn't use floats."); @@ -562,6 +597,12 @@ void Canvas::drawAtlas(const Paint& paint, blend_mode, sampling, reinterpret_cast(cull_rect.data()), with_attributes); } + + transforms.Release(); + rects.Release(); + colors.Release(); + cull_rect.Release(); + return Dart_Null(); } void Canvas::drawShadow(const CanvasPath* path, diff --git a/engine/src/flutter/lib/ui/painting/canvas.h b/engine/src/flutter/lib/ui/painting/canvas.h index ff5b39c3c0..d80b329491 100644 --- a/engine/src/flutter/lib/ui/painting/canvas.h +++ b/engine/src/flutter/lib/ui/painting/canvas.h @@ -110,36 +110,36 @@ class Canvas : public RefCountedDartWrappable, DisplayListOpFlags { void drawPath(const CanvasPath* path, const Paint& paint, const PaintData& paint_data); - void drawImage(const CanvasImage* image, - double x, - double y, - const Paint& paint, - const PaintData& paint_data, - int filterQualityIndex); - void drawImageRect(const CanvasImage* image, - double src_left, - double src_top, - double src_right, - double src_bottom, - double dst_left, - double dst_top, - double dst_right, - double dst_bottom, - const Paint& paint, - const PaintData& paint_data, - int filterQualityIndex); - void drawImageNine(const CanvasImage* image, - double center_left, - double center_top, - double center_right, - double center_bottom, - double dst_left, - double dst_top, - double dst_right, - double dst_bottom, - const Paint& paint, - const PaintData& paint_data, - int bitmapSamplingIndex); + Dart_Handle drawImage(const CanvasImage* image, + double x, + double y, + const Paint& paint, + const PaintData& paint_data, + int filterQualityIndex); + Dart_Handle drawImageRect(const CanvasImage* image, + double src_left, + double src_top, + double src_right, + double src_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data, + int filterQualityIndex); + Dart_Handle drawImageNine(const CanvasImage* image, + double center_left, + double center_top, + double center_right, + double center_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data, + int bitmapSamplingIndex); void drawPicture(Picture* picture); // The paint argument is first for the following functions because Paint @@ -157,15 +157,15 @@ class Canvas : public RefCountedDartWrappable, DisplayListOpFlags { const Paint& paint, const PaintData& paint_data); - void drawAtlas(const Paint& paint, - const PaintData& paint_data, - int filterQualityIndex, - CanvasImage* atlas, - const tonic::Float32List& transforms, - const tonic::Float32List& rects, - const tonic::Int32List& colors, - DlBlendMode blend_mode, - const tonic::Float32List& cull_rect); + Dart_Handle drawAtlas(const Paint& paint, + const PaintData& paint_data, + int filterQualityIndex, + CanvasImage* atlas, + tonic::Float32List& transforms, + tonic::Float32List& rects, + tonic::Int32List& colors, + DlBlendMode blend_mode, + tonic::Float32List& cull_rect); void drawShadow(const CanvasPath* path, SkColor color, diff --git a/engine/src/flutter/lib/ui/painting/display_list_deferred_image_gpu.cc b/engine/src/flutter/lib/ui/painting/display_list_deferred_image_gpu.cc new file mode 100644 index 0000000000..3868cf1f06 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/display_list_deferred_image_gpu.cc @@ -0,0 +1,70 @@ +// 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/display_list_deferred_image_gpu.h" + +namespace flutter { + +sk_sp DlDeferredImageGPU::Make(SkISize size) { + return sk_sp(new DlDeferredImageGPU(size)); +} + +DlDeferredImageGPU::DlDeferredImageGPU(SkISize size) : size_(size) {} + +// |DlImage| +DlDeferredImageGPU::~DlDeferredImageGPU() = default; + +// |DlImage| +sk_sp DlDeferredImageGPU::skia_image() const { + return image_; +}; + +// |DlImage| +std::shared_ptr DlDeferredImageGPU::impeller_texture() + const { + return nullptr; +} + +// |DlImage| +bool DlDeferredImageGPU::isTextureBacked() const { + if (auto image = skia_image()) { + return image->isTextureBacked(); + } + return false; +} + +// |DlImage| +SkISize DlDeferredImageGPU::dimensions() const { + return size_; +} + +// |DlImage| +size_t DlDeferredImageGPU::GetApproximateByteSize() const { + // This call is accessed on the UI thread, and image_ may not be available + // yet. The image is not mipmapped and it's created using N32 pixels, so this + // is safe. + if (size_.isEmpty()) { + return sizeof(this); + } + return sizeof(this) + size_.width() * size_.height() * 4; +} + +void DlDeferredImageGPU::set_image(sk_sp image) { + FML_DCHECK(image); + FML_DCHECK(image->dimensions() == size_); + image_ = std::move(image); +} + +void DlDeferredImageGPU::set_error(const std::string& error) { + FML_DCHECK(!image_); + std::scoped_lock lock(error_mutex_); + error_ = std::move(error); +} + +std::optional DlDeferredImageGPU::get_error() const { + std::scoped_lock lock(error_mutex_); + return error_; +} + +} // namespace flutter diff --git a/engine/src/flutter/lib/ui/painting/display_list_deferred_image_gpu.h b/engine/src/flutter/lib/ui/painting/display_list_deferred_image_gpu.h new file mode 100644 index 0000000000..0cec807fe7 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/display_list_deferred_image_gpu.h @@ -0,0 +1,67 @@ +// 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_DISPLAY_LIST_DEFERRED_IMAGE_GPU_H_ +#define FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_H_ + +#include + +#include "flutter/display_list/display_list_image.h" +#include "flutter/flow/skia_gpu_object.h" +#include "flutter/fml/macros.h" + +namespace flutter { + +class DlDeferredImageGPU final : public DlImage { + public: + static sk_sp Make(SkISize size); + + // |DlImage| + ~DlDeferredImageGPU() override; + + // |DlImage| + // This method is only safe to call from the raster thread. + sk_sp skia_image() const override; + + // |DlImage| + std::shared_ptr impeller_texture() const override; + + // |DlImage| + bool isTextureBacked() const override; + + // |DlImage| + SkISize dimensions() const override; + + // |DlImage| + virtual size_t GetApproximateByteSize() const override; + + // This method must only be called from the raster thread. + void set_image(sk_sp image); + + // This method is safe to call from any thread. + void set_error(const std::string& error); + + // |DlImage| + // This method is safe to call from any thread. + std::optional get_error() const override; + + // |DlImage| + OwningContext owning_context() const override { + return OwningContext::kRaster; + } + + private: + sk_sp image_; + SkISize size_; + mutable std::mutex error_mutex_; + std::optional error_; + + explicit DlDeferredImageGPU(SkISize size); + + FML_DISALLOW_COPY_AND_ASSIGN(DlDeferredImageGPU); +}; + +} // namespace flutter + +#endif // FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_H_ diff --git a/engine/src/flutter/lib/ui/painting/image.cc b/engine/src/flutter/lib/ui/painting/image.cc index 3e8865e555..0ef33bf6f1 100644 --- a/engine/src/flutter/lib/ui/painting/image.cc +++ b/engine/src/flutter/lib/ui/painting/image.cc @@ -4,6 +4,9 @@ #include "flutter/lib/ui/painting/image.h" +#include +#include + #include "flutter/lib/ui/painting/image_encoding.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" @@ -53,7 +56,11 @@ size_t CanvasImage::GetAllocationSize() const { if (image_) { size += image_->GetApproximateByteSize(); } - return size; + // The VM will assert if we set a value larger than or close to + // std::numeric_limits::max(). + // https://github.com/dart-lang/sdk/issues/49332 + return std::clamp( + size, static_cast(0), + static_cast(std::numeric_limits::max() / 10)); } - } // namespace flutter diff --git a/engine/src/flutter/lib/ui/painting/image_encoding.cc b/engine/src/flutter/lib/ui/painting/image_encoding.cc index c8df75ebb6..b3149f80d6 100644 --- a/engine/src/flutter/lib/ui/painting/image_encoding.cc +++ b/engine/src/flutter/lib/ui/painting/image_encoding.cc @@ -60,6 +60,21 @@ void InvokeDataCallback(std::unique_ptr callback, DartInvoke(callback->value(), {dart_data}); } +static void ConvertGpuImageToRaster( + sk_sp dl_image, + std::function)> encode_task, + fml::RefPtr raster_task_runner) { + fml::TaskRunner::RunNowOrPostTask( + raster_task_runner, [dl_image, encode_task = std::move(encode_task)]() { + auto image = dl_image->skia_image(); + if (image == nullptr) { + encode_task(nullptr); + return; + } + encode_task(image->makeRasterImage()); + }); +} + void ConvertImageToRaster( sk_sp dl_image, std::function)> encode_task, @@ -228,9 +243,18 @@ void EncodeImageAndInvokeDataCallback( }); }; - ConvertImageToRaster(std::move(image), encode_task, raster_task_runner, - io_task_runner, resource_context, snapshot_delegate, - is_gpu_disabled_sync_switch); + FML_DCHECK(image); + switch (image->owning_context()) { + case DlImage::OwningContext::kRaster: + ConvertGpuImageToRaster(std::move(image), encode_task, + raster_task_runner); + break; + case DlImage::OwningContext::kIO: + ConvertImageToRaster(std::move(image), encode_task, raster_task_runner, + io_task_runner, resource_context, snapshot_delegate, + is_gpu_disabled_sync_switch); + break; + } } } // namespace diff --git a/engine/src/flutter/lib/ui/painting/image_shader.cc b/engine/src/flutter/lib/ui/painting/image_shader.cc index fb32e7a2f9..cb12c5d7b0 100644 --- a/engine/src/flutter/lib/ui/painting/image_shader.cc +++ b/engine/src/flutter/lib/ui/painting/image_shader.cc @@ -5,8 +5,8 @@ #include "flutter/lib/ui/painting/image_shader.h" #include "flutter/lib/ui/painting/image_filter.h" -#include "flutter/lib/ui/ui_dart_state.h" #include "flutter/lib/ui/painting/display_list_image_gpu.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" @@ -36,30 +36,38 @@ fml::RefPtr ImageShader::Create() { return fml::MakeRefCounted(); } -void ImageShader::initWithImage(CanvasImage* image, - SkTileMode tmx, - SkTileMode tmy, - int filter_quality_index, - const tonic::Float64List& matrix4) { +Dart_Handle ImageShader::initWithImage(CanvasImage* image, + SkTileMode tmx, + SkTileMode tmy, + int filter_quality_index, + tonic::Float64List& matrix4) { if (!image) { - Dart_ThrowException( - ToDart("ImageShader constructor called with non-genuine Image.")); - return; + matrix4.Release(); + return ToDart("ImageShader constructor called with non-genuine Image."); } + + if (image->image()->owning_context() != DlImage::OwningContext::kIO) { + matrix4.Release(); + // TODO(dnfield): it should be possible to support this + // https://github.com/flutter/flutter/issues/105085 + return ToDart("ImageShader constructor with GPU image is not supported."); + } + auto raw_sk_image = image->image()->skia_image(); if (!raw_sk_image) { - Dart_ThrowException( - ToDart("ImageShader constructor with Impeller is not supported.")); - return; + matrix4.Release(); + return ToDart("ImageShader constructor with Impeller is not supported."); } sk_image_ = UIDartState::CreateGPUObject(std::move(raw_sk_image)); SkMatrix local_matrix = ToSkMatrix(matrix4); + matrix4.Release(); sampling_is_locked_ = filter_quality_index >= 0; DlImageSampling sampling = sampling_is_locked_ ? ImageFilter::SamplingFromIndex(filter_quality_index) : DlImageSampling::kLinear; cached_shader_ = UIDartState::CreateGPUObject(sk_make_sp( sk_image_.skia_object(), ToDl(tmx), ToDl(tmy), sampling, &local_matrix)); + return Dart_Null(); } std::shared_ptr ImageShader::shader(DlImageSampling sampling) { diff --git a/engine/src/flutter/lib/ui/painting/image_shader.h b/engine/src/flutter/lib/ui/painting/image_shader.h index 04d1e49a32..785ebef28f 100644 --- a/engine/src/flutter/lib/ui/painting/image_shader.h +++ b/engine/src/flutter/lib/ui/painting/image_shader.h @@ -28,11 +28,11 @@ class ImageShader : public Shader { ~ImageShader() override; static fml::RefPtr Create(); - void initWithImage(CanvasImage* image, - SkTileMode tmx, - SkTileMode tmy, - int filter_quality_index, - const tonic::Float64List& matrix4); + Dart_Handle initWithImage(CanvasImage* image, + SkTileMode tmx, + SkTileMode tmy, + int filter_quality_index, + tonic::Float64List& matrix4); std::shared_ptr shader(DlImageSampling) override; diff --git a/engine/src/flutter/lib/ui/painting/picture.cc b/engine/src/flutter/lib/ui/painting/picture.cc index aa7056b37a..816c555da3 100644 --- a/engine/src/flutter/lib/ui/painting/picture.cc +++ b/engine/src/flutter/lib/ui/painting/picture.cc @@ -8,8 +8,8 @@ #include "flutter/fml/make_copyable.h" #include "flutter/lib/ui/painting/canvas.h" +#include "flutter/lib/ui/painting/display_list_deferred_image_gpu.h" #include "flutter/lib/ui/ui_dart_state.h" -#include "third_party/skia/include/core/SkImage.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" @@ -23,6 +23,7 @@ IMPLEMENT_WRAPPERTYPEINFO(ui, Picture); #define FOR_EACH_BINDING(V) \ V(Picture, toImage) \ + V(Picture, toGpuImage) \ V(Picture, dispose) \ V(Picture, GetAllocationSize) @@ -52,6 +53,46 @@ Dart_Handle Picture::toImage(uint32_t width, raw_image_callback); } +void Picture::toGpuImage(uint32_t width, + uint32_t height, + Dart_Handle raw_image_handle) { + FML_DCHECK(display_list_.skia_object()); + RasterizeToGpuImage(display_list_.skia_object(), width, height, + raw_image_handle); +} + +// static +void Picture::RasterizeToGpuImage(sk_sp display_list, + uint32_t width, + uint32_t height, + Dart_Handle raw_image_handle) { + auto* dart_state = UIDartState::Current(); + auto unref_queue = dart_state->GetSkiaUnrefQueue(); + auto snapshot_delegate = dart_state->GetSnapshotDelegate(); + auto raster_task_runner = dart_state->GetTaskRunners().GetRasterTaskRunner(); + + auto image = CanvasImage::Create(); + auto dl_image = DlDeferredImageGPU::Make(SkISize::Make(width, height)); + image->set_image(dl_image); + + fml::TaskRunner::RunNowOrPostTask( + raster_task_runner, + [snapshot_delegate, unref_queue, dl_image = std::move(dl_image), + display_list = std::move(display_list)]() { + sk_sp sk_image; + std::string error; + std::tie(sk_image, error) = snapshot_delegate->MakeGpuImage( + display_list, dl_image->dimensions()); + if (sk_image) { + dl_image->set_image(std::move(sk_image)); + } else { + dl_image->set_error(std::move(error)); + } + }); + + image->AssociateWithDartWrapper(raw_image_handle); +} + void Picture::dispose() { display_list_.reset(); ClearDartWrapper(); diff --git a/engine/src/flutter/lib/ui/painting/picture.h b/engine/src/flutter/lib/ui/painting/picture.h index 33e5cb5772..e7f4f02e2c 100644 --- a/engine/src/flutter/lib/ui/painting/picture.h +++ b/engine/src/flutter/lib/ui/painting/picture.h @@ -37,12 +37,21 @@ class Picture : public RefCountedDartWrappable { uint32_t height, Dart_Handle raw_image_callback); + void toGpuImage(uint32_t width, + uint32_t height, + Dart_Handle raw_image_handle); + void dispose(); size_t GetAllocationSize() const override; static void RegisterNatives(tonic::DartLibraryNatives* natives); + static void RasterizeToGpuImage(sk_sp display_list, + uint32_t width, + uint32_t height, + Dart_Handle raw_image_handle); + static Dart_Handle RasterizeToImage(sk_sp display_list, uint32_t width, uint32_t height, diff --git a/engine/src/flutter/lib/ui/snapshot_delegate.h b/engine/src/flutter/lib/ui/snapshot_delegate.h index a1f7c618b0..7c87a01c86 100644 --- a/engine/src/flutter/lib/ui/snapshot_delegate.h +++ b/engine/src/flutter/lib/ui/snapshot_delegate.h @@ -5,13 +5,21 @@ #ifndef FLUTTER_LIB_UI_SNAPSHOT_DELEGATE_H_ #define FLUTTER_LIB_UI_SNAPSHOT_DELEGATE_H_ +#include + +#include "flutter/display_list/display_list.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkPicture.h" - +#include "third_party/skia/include/core/SkPromiseImageTexture.h" +#include "third_party/skia/include/gpu/GrContextThreadSafeProxy.h" namespace flutter { class SnapshotDelegate { public: + virtual std::pair, std::string> MakeGpuImage( + sk_sp display_list, + SkISize picture_size) = 0; + virtual sk_sp MakeRasterSnapshot( std::function draw_callback, SkISize picture_size) = 0; diff --git a/engine/src/flutter/lib/web_ui/lib/canvas.dart b/engine/src/flutter/lib/web_ui/lib/canvas.dart index 2b0de7976e..b78e19e415 100644 --- a/engine/src/flutter/lib/web_ui/lib/canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/canvas.dart @@ -155,6 +155,7 @@ abstract class Canvas { abstract class Picture { Future toImage(int width, int height); + Image toGpuImage(int width, int height); void dispose(); bool get debugDisposed; int get approximateBytesUsed; @@ -173,3 +174,8 @@ enum PathOperation { xor, reverseDifference, } + +abstract class PictureRasterizationException implements Exception { + String get message; + StackTrace? stack; +} diff --git a/engine/src/flutter/lib/web_ui/lib/compositing.dart b/engine/src/flutter/lib/web_ui/lib/compositing.dart index de1e6cdbee..c18280559b 100644 --- a/engine/src/flutter/lib/web_ui/lib/compositing.dart +++ b/engine/src/flutter/lib/web_ui/lib/compositing.dart @@ -6,6 +6,7 @@ part of ui; abstract class Scene { Future toImage(int width, int height); + Image toGpuImage(int width, int height); void dispose(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart index f0cbd4a12a..eff0fa26d9 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart @@ -25,6 +25,12 @@ class LayerScene implements ui.Scene { final ui.Picture picture = layerTree.flatten(); return picture.toImage(width, height); } + + @override + ui.Image toGpuImage(int width, int height) { + final ui.Picture picture = layerTree.flatten(); + return picture.toGpuImage(width, height); + } } class LayerSceneBuilder implements ui.SceneBuilder { diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/picture.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/picture.dart index 0227246be5..a02a9a2cf5 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/picture.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/picture.dart @@ -92,6 +92,11 @@ class CkPicture extends ManagedSkiaObject implements ui.Picture { @override Future toImage(int width, int height) async { + return toGpuImage(width, height); + } + + @override + ui.Image toGpuImage(int width, int height) { assert(debugCheckNotDisposed('Cannot convert picture to image.')); final SkSurface skSurface = canvasKit.MakeSurface(width, height); final SkCanvas skCanvas = skSurface.getCanvas(); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart index 7ae9a36d69..50cee45690 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart @@ -24,6 +24,11 @@ class SurfaceScene implements ui.Scene { throw UnsupportedError('toImage is not supported on the Web'); } + @override + ui.Image toGpuImage(int width, int height) { + throw UnsupportedError('toGpuImage is not supported on the Web'); + } + /// Releases the resources used by this scene. /// /// After calling this function, the scene is cannot be used further. diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart index 6cc68063c9..1734c414cc 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart @@ -88,6 +88,11 @@ class EnginePicture implements ui.Picture { return onImageLoaded.future; } + @override + ui.Image toGpuImage(int width, int height) { + throw UnsupportedError('toGpuImage is not supported on the HTML backend. Use drawPicture instead, or toImage.'); + } + bool _disposed = false; @override diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/picture_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/picture_test.dart index 59851bfc7c..1c437293a7 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/picture_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/picture_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:typed_data'; + import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; @@ -83,6 +85,23 @@ void testMain() { expect(picture.resurrect(), isNotNull); }); }); + + test('toGpuImage', () async { + const ui.Color color = ui.Color(0xFFAAAAAA); + final ui.PictureRecorder recorder = ui.PictureRecorder(); + final ui.Canvas canvas = ui.Canvas(recorder); + canvas.drawPaint(ui.Paint()..color = color); + final ui.Picture picture = recorder.endRecording(); + final ui.Image image = picture.toGpuImage(10, 15); + + expect(image.width, 10); + expect(image.height, 15); + + final ByteData? data = await image.toByteData(); + expect(data, isNotNull); + expect(data!.lengthInBytes, 10 * 15 * 4); + expect(data.buffer.asUint32List().first, color.value); + }); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040 }, skip: isIosSafari); } diff --git a/engine/src/flutter/shell/common/fixtures/shell_test.dart b/engine/src/flutter/shell/common/fixtures/shell_test.dart index f9d526ae6d..4aded8ad83 100644 --- a/engine/src/flutter/shell/common/fixtures/shell_test.dart +++ b/engine/src/flutter/shell/common/fixtures/shell_test.dart @@ -321,3 +321,26 @@ void scene_with_red_box() { }; PlatformDispatcher.instance.scheduleFrame(); } + + +@pragma('vm:entry-point') +Future toGpuImage() async { + final PictureRecorder recorder = PictureRecorder(); + final Canvas canvas = Canvas(recorder); + canvas.drawPaint(Paint()..color = const Color(0xFFAAAAAA)); + final Picture picture = recorder.endRecording(); + + final Image image = picture.toGpuImage(20, 25); + void expect(Object? a, Object? b) { + if (a != b) { + throw 'Expected $a to == $b'; + } + } + expect(image.width, 20); + expect(image.height, 25); + + final ByteData data = (await image.toByteData())!; + expect(data.lengthInBytes, 20 * 25 * 4); + expect(data.buffer.asUint32List().every((int byte) => byte == 0xFFAAAAAA), true); + notifyNative(); +} diff --git a/engine/src/flutter/shell/common/rasterizer.cc b/engine/src/flutter/shell/common/rasterizer.cc index 077bb33365..f246d1cead 100644 --- a/engine/src/flutter/shell/common/rasterizer.cc +++ b/engine/src/flutter/shell/common/rasterizer.cc @@ -28,8 +28,10 @@ namespace flutter { // used within this interval. static constexpr std::chrono::milliseconds kSkiaCleanupExpiration(15000); -Rasterizer::Rasterizer(Delegate& delegate) +Rasterizer::Rasterizer(Delegate& delegate, + MakeGpuImageBehavior gpu_image_behavior) : delegate_(delegate), + gpu_image_behavior_(gpu_image_behavior), compositor_context_(std::make_unique(*this)), user_override_resource_cache_bytes_(false), weak_factory_(this) { @@ -245,6 +247,69 @@ bool Rasterizer::ShouldResubmitFrame(const RasterStatus& raster_status) { raster_status == RasterStatus::kSkipAndRetry; } +namespace { +std::pair, std::string> MakeBitmapImage(SkISize picture_size) { + // Use 16384 as a proxy for the maximum texture size for a GPU image. + // This is meant to be large enough to avoid false positives in test contexts, + // but not so artificially large to be completely unrealistic on any platform. + // This limit is taken from the Metal specification. D3D, Vulkan, and GL + // generally have lower limits. + if (picture_size.width() > 16384 || picture_size.height() > 16384) { + return {nullptr, "unable to create render target at specified size"}; + } + SkBitmap bitmap; + if (!bitmap.tryAllocN32Pixels(picture_size.width(), picture_size.height())) { + return {nullptr, "unable to create render target at specified size"}; + } + bitmap.eraseColor(SK_ColorLTGRAY); + uint32_t half_width = std::floor(picture_size.width() / 2); + uint32_t half_height = std::floor(picture_size.height() / 2); + bitmap.erase(SK_ColorWHITE, SkIRect::MakeLTRB(0, 0, half_width, half_height)); + bitmap.erase(SK_ColorWHITE, + SkIRect::MakeLTRB(half_width, half_height, picture_size.width(), + picture_size.height())); + bitmap.setImmutable(); + return {bitmap.asImage(), ""}; +} +} // namespace + +std::pair, std::string> Rasterizer::MakeGpuImage( + sk_sp display_list, + SkISize picture_size) { + TRACE_EVENT0("flutter", "Rasterizer::MakeGpuImage"); + FML_DCHECK(display_list); + + switch (gpu_image_behavior_) { + case MakeGpuImageBehavior::kGpu: + break; + case MakeGpuImageBehavior::kBitmap: + return MakeBitmapImage(picture_size); + } + + if (!surface_) { + return {nullptr, "GPU surface unavilable"}; + } + + auto* context = surface_->GetContext(); + if (!context) { + return {nullptr, "GPU context unavailable"}; + } + + const SkImageInfo image_info = SkImageInfo::MakeN32Premul(picture_size); + sk_sp surface = + SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, image_info); + if (!surface) { + return {nullptr, "unable to create render target at specified size"}; + } + + SkCanvas* canvas = surface->getCanvas(); + canvas->clear(SK_ColorTRANSPARENT); + display_list->RenderTo(canvas); + + sk_sp image = surface->makeImageSnapshot(); + return {image, image ? "" : "Unable to create image"}; +} + namespace { sk_sp DrawSnapshot( sk_sp surface, diff --git a/engine/src/flutter/shell/common/rasterizer.h b/engine/src/flutter/shell/common/rasterizer.h index 1979c1db3c..425b8214e5 100644 --- a/engine/src/flutter/shell/common/rasterizer.h +++ b/engine/src/flutter/shell/common/rasterizer.h @@ -25,6 +25,7 @@ #include "flutter/lib/ui/snapshot_delegate.h" #include "flutter/shell/common/pipeline.h" #include "flutter/shell/common/snapshot_surface_producer.h" +#include "third_party/skia/include/core/SkImage.h" namespace flutter { @@ -98,6 +99,16 @@ class Rasterizer final : public SnapshotDelegate, const = 0; }; + //---------------------------------------------------------------------------- + /// @brief How to handle calls to MakeGpuImage. + enum class MakeGpuImageBehavior { + /// MakeGpuImage returns a GPU resident image, if possible. + kGpu, + /// MakeGpuImage returns a checkerboard bitmap. This is useful in test + /// contexts where no GPU surface is available. + kBitmap, + }; + //---------------------------------------------------------------------------- /// @brief Creates a new instance of a rasterizer. Rasterizers may only /// be created on the raster task runner. Rasterizers are @@ -105,8 +116,12 @@ class Rasterizer final : public SnapshotDelegate, /// as the rasterizer delegate). /// /// @param[in] delegate The rasterizer delegate. + /// @param[in] gpu_image_behavior How to handle calls to + /// MakeGpuImage. /// - explicit Rasterizer(Delegate& delegate); + explicit Rasterizer( + Delegate& delegate, + MakeGpuImageBehavior gpu_image_behavior = MakeGpuImageBehavior::kGpu); //---------------------------------------------------------------------------- /// @brief Destroys the rasterizer. This must happen on the raster task @@ -454,6 +469,11 @@ class Rasterizer final : public SnapshotDelegate, void DisableThreadMergerIfNeeded(); private: + // |SnapshotDelegate| + std::pair, std::string> MakeGpuImage( + sk_sp display_list, + SkISize picture_size) override; + // |SnapshotDelegate| sk_sp MakeRasterSnapshot( std::function draw_callback, @@ -498,6 +518,7 @@ class Rasterizer final : public SnapshotDelegate, static bool ShouldResubmitFrame(const RasterStatus& raster_status); Delegate& delegate_; + MakeGpuImageBehavior gpu_image_behavior_; std::unique_ptr surface_; std::unique_ptr snapshot_surface_producer_; std::unique_ptr compositor_context_; diff --git a/engine/src/flutter/shell/common/shell_unittests.cc b/engine/src/flutter/shell/common/shell_unittests.cc index 18737e57f6..d5ffce3770 100644 --- a/engine/src/flutter/shell/common/shell_unittests.cc +++ b/engine/src/flutter/shell/common/shell_unittests.cc @@ -3720,6 +3720,40 @@ TEST_F(ShellTest, SpawnWorksWithOnError) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); } +TEST_F(ShellTest, PictureToGpuImage) { +#if !SHELL_ENABLE_GL + // GL emulation does not exist on Fuchsia. + GTEST_SKIP(); +#endif // !SHELL_ENABLE_GL + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = + CreateShell(settings, // + GetTaskRunnersForFixture(), // + false, // + nullptr, // + false, // + ShellTestPlatformView::BackendType::kGLBackend // + ); + + fml::AutoResetWaitableEvent latch; + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) { + latch.Signal(); + })); + + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("toGpuImage"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +} + } // namespace testing } // namespace flutter diff --git a/engine/src/flutter/shell/testing/tester_main.cc b/engine/src/flutter/shell/testing/tester_main.cc index 3f2e4ab03e..2416a61289 100644 --- a/engine/src/flutter/shell/testing/tester_main.cc +++ b/engine/src/flutter/shell/testing/tester_main.cc @@ -235,7 +235,8 @@ int RunTester(const flutter::Settings& settings, }; Shell::CreateCallback on_create_rasterizer = [](Shell& shell) { - return std::make_unique(shell); + return std::make_unique( + shell, Rasterizer::MakeGpuImageBehavior::kBitmap); }; auto shell = Shell::Create(flutter::PlatformData(), // diff --git a/engine/src/flutter/testing/dart/canvas_test.dart b/engine/src/flutter/testing/dart/canvas_test.dart index 50b499f11b..da6d4d8afc 100644 --- a/engine/src/flutter/testing/dart/canvas_test.dart +++ b/engine/src/flutter/testing/dart/canvas_test.dart @@ -410,6 +410,113 @@ void main() { expect(areEqual, true); }, skip: !Platform.isLinux); // https://github.com/flutter/flutter/issues/53784 + test('toGpuImage - too big', () async { + PictureRecorder recorder = PictureRecorder(); + Canvas canvas = Canvas(recorder); + canvas.drawPaint(Paint()..color = const Color(0xFF123456)); + final Picture picture = recorder.endRecording(); + final Image image = picture.toGpuImage(300000, 4000000); + picture.dispose(); + + expect(image.width, 300000); + expect(image.height, 4000000); + + recorder = PictureRecorder(); + canvas = Canvas(recorder); + + // On a slower CI machine, the raster thread may get behind the UI thread + // here. However, once the image is in an error state it will immediately + // throw on subsequent attempts. + bool caughtException = false; + for (int iterations = 0; iterations < 1000; iterations += 1) { + try { + canvas.drawImage(image, Offset.zero, Paint()); + } on PictureRasterizationException catch (e) { + caughtException = true; + expect(e.message, contains('unable to create render target at specified size')); + break; + } + // Let the event loop turn. + await Future.delayed(const Duration(milliseconds: 1)); + } + expect(caughtException, true); + expect( + () => canvas.drawImageRect(image, Rect.zero, Rect.zero, Paint()), + throwsException, + ); + expect( + () => canvas.drawImageNine(image, Rect.zero, Rect.zero, Paint()), + throwsException, + ); + expect( + () => canvas.drawAtlas(image, [], [], null, null, null, Paint()), + throwsException, + ); + }); + + test('toGpuImage - succeeds', () async { + PictureRecorder recorder = PictureRecorder(); + Canvas canvas = Canvas(recorder); + canvas.drawPaint(Paint()..color = const Color(0xFF123456)); + final Picture picture = recorder.endRecording(); + final Image image = picture.toGpuImage(30, 40); + picture.dispose(); + + expect(image.width, 30); + expect(image.height, 40); + + recorder = PictureRecorder(); + canvas = Canvas(recorder); + expect( + () => canvas.drawImage(image, Offset.zero, Paint()), + returnsNormally, + ); + expect( + () => canvas.drawImageRect(image, Rect.zero, Rect.zero, Paint()), + returnsNormally, + ); + expect( + () => canvas.drawImageNine(image, Rect.zero, Rect.zero, Paint()), + returnsNormally, + ); + expect( + () => canvas.drawAtlas(image, [], [], null, null, null, Paint()), + returnsNormally, + ); + }); + + test('toGpuImage - toByteData', () async { + const Color color = Color(0xFF123456); + final PictureRecorder recorder = PictureRecorder(); + final Canvas canvas = Canvas(recorder); + canvas.drawPaint(Paint()..color = color); + final Picture picture = recorder.endRecording(); + final Image image = picture.toGpuImage(6, 8); + picture.dispose(); + + expect(image.width, 6); + expect(image.height, 8); + + final ByteData? data = await image.toByteData(); + + expect(data, isNotNull); + expect(data!.lengthInBytes, 6 * 8 * 4); + final Uint32List bytes = data.buffer.asUint32List(); + // Draws a checkerboard due to flutter_tester not having a GPU context. + const int white = 0xFFFFFFFF; + const int grey = 0xFFCCCCCC; + expect(bytes, const [ + white, white, white, grey, grey, grey, // + white, white, white, grey, grey, grey, + white, white, white, grey, grey, grey, + white, white, white, grey, grey, grey, + grey, grey, grey, white, white, white, + grey, grey, grey, white, white, white, + grey, grey, grey, white, white, white, + grey, grey, grey, white, white, white, + ]); + }); + test('Canvas.drawParagraph throws when Paragraph.layout was not called', () async { // Regression test for https://github.com/flutter/flutter/issues/97172 bool assertsEnabled = false; diff --git a/engine/src/flutter/testing/dart/compositing_test.dart b/engine/src/flutter/testing/dart/compositing_test.dart index 2b2b0be433..c55f18899e 100644 --- a/engine/src/flutter/testing/dart/compositing_test.dart +++ b/engine/src/flutter/testing/dart/compositing_test.dart @@ -2,12 +2,49 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:typed_data' show Float64List; +import 'dart:typed_data' show Float64List, Uint32List, ByteData; import 'dart:ui'; import 'package:litetest/litetest.dart'; void main() { + test('Scene.toGpuImage succeeds', () async { + final PictureRecorder recorder = PictureRecorder(); + final Canvas canvas = Canvas(recorder); + canvas.drawPaint(Paint()..color = const Color(0xFF123456)); + final Picture picture = recorder.endRecording(); + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(10, 10); + builder.addPicture(const Offset(5, 5), picture); + final Scene scene = builder.build(); + + final Image image = scene.toGpuImage(6, 8); + picture.dispose(); + scene.dispose(); + + expect(image.width, 6); + expect(image.height, 8); + + final ByteData? data = await image.toByteData(); + + expect(data, isNotNull); + expect(data!.lengthInBytes, 6 * 8 * 4); + final Uint32List bytes = data.buffer.asUint32List(); + // Draws a checkerboard due to flutter_tester not having a GPU context. + const int white = 0xFFFFFFFF; + const int grey = 0xFFCCCCCC; + expect(bytes, const [ + white, white, white, grey, grey, grey, // + white, white, white, grey, grey, grey, + white, white, white, grey, grey, grey, + white, white, white, grey, grey, grey, + grey, grey, grey, white, white, white, + grey, grey, grey, white, white, white, + grey, grey, grey, white, white, white, + grey, grey, grey, white, white, white, + ]); + }); + test('addPicture with disposed picture does not crash', () { bool assertsEnabled = false; assert(() { diff --git a/engine/src/flutter/testing/dart/image_shader_test.dart b/engine/src/flutter/testing/dart/image_shader_test.dart index 3a7b40354b..5aab759536 100644 --- a/engine/src/flutter/testing/dart/image_shader_test.dart +++ b/engine/src/flutter/testing/dart/image_shader_test.dart @@ -14,7 +14,23 @@ void main() { final Image image = await createImage(50, 50); final ImageShader shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16)); final Paint paint = Paint()..shader=shader; - final Rect rect = Rect.fromLTRB(0, 0, 100, 100); + const Rect rect = Rect.fromLTRB(0, 0, 100, 100); testCanvas((Canvas canvas) => canvas.drawRect(rect, paint)); }); + + test('Construct an ImageShader - GPU image', () async { + final PictureRecorder recorder = PictureRecorder(); + final Canvas canvas = Canvas(recorder); + canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF)); + final Picture picture = recorder.endRecording(); + final Image image = picture.toGpuImage(50, 50); + picture.dispose(); + + // TODO(dnfield): this should not throw once + // https://github.com/flutter/flutter/issues/105085 is fixed. + expect( + () => ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16)), + throwsException, + ); + }); }