diff --git a/engine/src/flutter/flow/BUILD.gn b/engine/src/flutter/flow/BUILD.gn index 86c867ce9f..8496d2b13d 100644 --- a/engine/src/flutter/flow/BUILD.gn +++ b/engine/src/flutter/flow/BUILD.gn @@ -40,6 +40,8 @@ source_set("flow") { "layers/picture_layer.h", "layers/shader_mask_layer.cc", "layers/shader_mask_layer.h", + "layers/texture_layer.cc", + "layers/texture_layer.h", "layers/transform_layer.cc", "layers/transform_layer.h", "matrix_decomposition.cc", @@ -51,6 +53,8 @@ source_set("flow") { "raster_cache.h", "raster_cache_key.cc", "raster_cache_key.h", + "texture.cc", + "texture.h", ] public_deps = [ diff --git a/engine/src/flutter/flow/compositor_context.cc b/engine/src/flutter/flow/compositor_context.cc index 2229301246..9f87eed8db 100644 --- a/engine/src/flutter/flow/compositor_context.cc +++ b/engine/src/flutter/flow/compositor_context.cc @@ -57,7 +57,12 @@ CompositorContext::ScopedFrame::~ScopedFrame() { context_.EndFrame(*this, instrumentation_enabled_); } +void CompositorContext::OnGrContextCreated() { + texture_registry_.OnGrContextCreated(); +} + void CompositorContext::OnGrContextDestroyed() { + texture_registry_.OnGrContextDestroyed(); raster_cache_.Clear(); } diff --git a/engine/src/flutter/flow/compositor_context.h b/engine/src/flutter/flow/compositor_context.h index 9ca1572521..0b40bb5ed3 100644 --- a/engine/src/flutter/flow/compositor_context.h +++ b/engine/src/flutter/flow/compositor_context.h @@ -11,6 +11,7 @@ #include "flutter/flow/instrumentation.h" #include "flutter/flow/process_info.h" #include "flutter/flow/raster_cache.h" +#include "flutter/flow/texture.h" #include "lib/fxl/macros.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPictureRecorder.h" @@ -55,10 +56,14 @@ class CompositorContext { SkCanvas* canvas, bool instrumentation_enabled = true); + void OnGrContextCreated(); + void OnGrContextDestroyed(); RasterCache& raster_cache() { return raster_cache_; } + TextureRegistry& texture_registry() { return texture_registry_; } + const Counter& frame_count() const { return frame_count_; } const Stopwatch& frame_time() const { return frame_time_; } @@ -69,6 +74,7 @@ class CompositorContext { private: RasterCache raster_cache_; + TextureRegistry texture_registry_; std::unique_ptr process_info_; Counter frame_count_; Stopwatch frame_time_; diff --git a/engine/src/flutter/flow/layers/default_layer_builder.cc b/engine/src/flutter/flow/layers/default_layer_builder.cc index 50a33092c8..1427b95561 100644 --- a/engine/src/flutter/flow/layers/default_layer_builder.cc +++ b/engine/src/flutter/flow/layers/default_layer_builder.cc @@ -17,6 +17,7 @@ #include "flutter/flow/layers/physical_model_layer.h" #include "flutter/flow/layers/picture_layer.h" #include "flutter/flow/layers/shader_mask_layer.h" +#include "flutter/flow/layers/texture_layer.h" #include "flutter/flow/layers/transform_layer.h" #if defined(OS_FUCHSIA) @@ -151,6 +152,19 @@ void DefaultLayerBuilder::PushPicture(const SkPoint& offset, current_layer_->Add(std::move(layer)); } +void DefaultLayerBuilder::PushTexture(const SkPoint& offset, + const SkSize& size, + int64_t texture_id) { + if (!current_layer_) { + return; + } + auto layer = std::make_unique(); + layer->set_offset(offset); + layer->set_size(size); + layer->set_texture_id(texture_id); + current_layer_->Add(std::move(layer)); +} + #if defined(OS_FUCHSIA) void DefaultLayerBuilder::PushChildScene( const SkPoint& offset, diff --git a/engine/src/flutter/flow/layers/default_layer_builder.h b/engine/src/flutter/flow/layers/default_layer_builder.h index 105758f3a6..85075657d3 100644 --- a/engine/src/flutter/flow/layers/default_layer_builder.h +++ b/engine/src/flutter/flow/layers/default_layer_builder.h @@ -62,6 +62,11 @@ class DefaultLayerBuilder final : public LayerBuilder { bool picture_is_complex, bool picture_will_change) override; + // |flow::LayerBuilder| + void PushTexture(const SkPoint& offset, + const SkSize& size, + int64_t texture_id) override; + #if defined(OS_FUCHSIA) // |flow::LayerBuilder| void PushChildScene(const SkPoint& offset, diff --git a/engine/src/flutter/flow/layers/layer.h b/engine/src/flutter/flow/layers/layer.h index 27aaf427ea..862b711769 100644 --- a/engine/src/flutter/flow/layers/layer.h +++ b/engine/src/flutter/flow/layers/layer.h @@ -10,6 +10,7 @@ #include "flutter/flow/instrumentation.h" #include "flutter/flow/raster_cache.h" +#include "flutter/flow/texture.h" #include "flutter/glue/trace_event.h" #include "lib/fxl/build_config.h" #include "lib/fxl/logging.h" @@ -56,6 +57,7 @@ class Layer { const Stopwatch& frame_time; const Stopwatch& engine_time; const CounterValues& memory_usage; + TextureRegistry& texture_registry; const bool checkerboard_offscreen_layers; }; diff --git a/engine/src/flutter/flow/layers/layer_builder.h b/engine/src/flutter/flow/layers/layer_builder.h index 2c645b2c8c..5754084f6a 100644 --- a/engine/src/flutter/flow/layers/layer_builder.h +++ b/engine/src/flutter/flow/layers/layer_builder.h @@ -60,6 +60,10 @@ class LayerBuilder { bool picture_is_complex, bool picture_will_change) = 0; + virtual void PushTexture(const SkPoint& offset, + const SkSize& size, + int64_t texture_id) = 0; + #if defined(OS_FUCHSIA) virtual void PushChildScene( const SkPoint& offset, diff --git a/engine/src/flutter/flow/layers/layer_tree.cc b/engine/src/flutter/flow/layers/layer_tree.cc index c922bdd900..ac7f809109 100644 --- a/engine/src/flutter/flow/layers/layer_tree.cc +++ b/engine/src/flutter/flow/layers/layer_tree.cc @@ -63,9 +63,11 @@ void LayerTree::UpdateScene(SceneUpdateContext& context, #endif void LayerTree::Paint(CompositorContext::ScopedFrame& frame) const { - Layer::PaintContext context = {*frame.canvas(), frame.context().frame_time(), + Layer::PaintContext context = {*frame.canvas(), + frame.context().frame_time(), frame.context().engine_time(), frame.context().memory_usage(), + frame.context().texture_registry(), checkerboard_offscreen_layers_}; TRACE_EVENT0("flutter", "LayerTree::Paint"); diff --git a/engine/src/flutter/flow/layers/texture_layer.cc b/engine/src/flutter/flow/layers/texture_layer.cc new file mode 100644 index 0000000000..cdc0819245 --- /dev/null +++ b/engine/src/flutter/flow/layers/texture_layer.cc @@ -0,0 +1,29 @@ +// Copyright 2017 The Chromium 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/flow/layers/texture_layer.h" + +#include "flutter/flow/texture.h" + +namespace flow { + +TextureLayer::TextureLayer() = default; + +TextureLayer::~TextureLayer() = default; + +void TextureLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) { + set_paint_bounds(SkRect::MakeXYWH(offset_.x(), offset_.y(), size_.width(), + size_.height())); +} + +void TextureLayer::Paint(PaintContext& context) const { + std::shared_ptr texture = + context.texture_registry.GetTexture(texture_id_); + if (!texture) { + return; + } + texture->Paint(context.canvas, paint_bounds()); +} + +} // namespace flow diff --git a/engine/src/flutter/flow/layers/texture_layer.h b/engine/src/flutter/flow/layers/texture_layer.h new file mode 100644 index 0000000000..75f0fe66ab --- /dev/null +++ b/engine/src/flutter/flow/layers/texture_layer.h @@ -0,0 +1,39 @@ +// Copyright 2017 The Chromium 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_FLOW_LAYERS_TEXTURE_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_TEXTURE_LAYER_H_ + +#include "flutter/flow/layers/layer.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/GrBackendSurface.h" +#include "third_party/skia/include/gpu/GrContext.h" +#include "third_party/skia/include/gpu/GrTexture.h" +#include "third_party/skia/include/gpu/GrTypes.h" + +namespace flow { + +class TextureLayer : public Layer { + public: + TextureLayer(); + ~TextureLayer() override; + + void set_offset(const SkPoint& offset) { offset_ = offset; } + void set_size(const SkSize& size) { size_ = size; } + void set_texture_id(int64_t texture_id) { texture_id_ = texture_id; } + + void Preroll(PrerollContext* context, const SkMatrix& matrix) override; + void Paint(PaintContext& context) const override; + + private: + SkPoint offset_; + SkSize size_; + int64_t texture_id_; + + FXL_DISALLOW_COPY_AND_ASSIGN(TextureLayer); +}; + +} // namespace flow + +#endif // FLUTTER_FLOW_LAYERS_TEXTURE_LAYER_H_ diff --git a/engine/src/flutter/flow/texture.cc b/engine/src/flutter/flow/texture.cc new file mode 100644 index 0000000000..57e8ce1c69 --- /dev/null +++ b/engine/src/flutter/flow/texture.cc @@ -0,0 +1,45 @@ +// Copyright 2017 The Chromium 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/flow/texture.h" + +namespace flow { + +TextureRegistry::TextureRegistry() = default; + +TextureRegistry::~TextureRegistry() = default; + +void TextureRegistry::RegisterTexture(std::shared_ptr texture) { + ASSERT_IS_GPU_THREAD + mapping_[texture->Id()] = texture; +} + +void TextureRegistry::UnregisterTexture(int64_t id) { + ASSERT_IS_GPU_THREAD + mapping_.erase(id); +} + +void TextureRegistry::OnGrContextCreated() { + ASSERT_IS_GPU_THREAD; + for (auto& it : mapping_) { + it.second->OnGrContextCreated(); + } +} + +void TextureRegistry::OnGrContextDestroyed() { + ASSERT_IS_GPU_THREAD; + for (auto& it : mapping_) { + it.second->OnGrContextDestroyed(); + } +} + +std::shared_ptr TextureRegistry::GetTexture(int64_t id) { + ASSERT_IS_GPU_THREAD + return mapping_[id]; +} + +Texture::Texture(int64_t id) : id_(id) {} +Texture::~Texture() = default; + +} // namespace flow diff --git a/engine/src/flutter/flow/texture.h b/engine/src/flutter/flow/texture.h new file mode 100644 index 0000000000..a602a6b45b --- /dev/null +++ b/engine/src/flutter/flow/texture.h @@ -0,0 +1,68 @@ +// Copyright 2017 The Chromium 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_FLOW_TEXTURE_H_ +#define FLUTTER_FLOW_TEXTURE_H_ + +#include +#include "flutter/common/threads.h" +#include "lib/fxl/synchronization/waitable_event.h" +#include "third_party/skia/include/core/SkCanvas.h" + +namespace flow { + +class Texture { + protected: + Texture(int64_t id); + + public: + // Called from GPU thread. + virtual ~Texture(); + + // Called from GPU thread. + virtual void Paint(SkCanvas& canvas, const SkRect& bounds) = 0; + + // Called from GPU thread. + virtual void OnGrContextCreated() = 0; + + // Called from GPU thread. + virtual void OnGrContextDestroyed() = 0; + + int64_t Id() { return id_; } + + private: + int64_t id_; + + FXL_DISALLOW_COPY_AND_ASSIGN(Texture); +}; + +class TextureRegistry { + public: + TextureRegistry(); + ~TextureRegistry(); + + // Called from GPU thread. + void RegisterTexture(std::shared_ptr texture); + + // Called from GPU thread. + void UnregisterTexture(int64_t id); + + // Called from GPU thread. + std::shared_ptr GetTexture(int64_t id); + + // Called from GPU thread. + void OnGrContextCreated(); + + // Called from GPU thread. + void OnGrContextDestroyed(); + + private: + std::map> mapping_; + + FXL_DISALLOW_COPY_AND_ASSIGN(TextureRegistry); +}; + +} // namespace flow + +#endif // FLUTTER_FLOW_TEXTURE_H_ diff --git a/engine/src/flutter/lib/ui/compositing.dart b/engine/src/flutter/lib/ui/compositing.dart index 7063489ac0..00a481f6b3 100644 --- a/engine/src/flutter/lib/ui/compositing.dart +++ b/engine/src/flutter/lib/ui/compositing.dart @@ -197,6 +197,15 @@ class SceneBuilder extends NativeFieldWrapperClass2 { } void _addPicture(double dx, double dy, Picture picture, int hints) native "SceneBuilder_addPicture"; + /// Adds a backend texture to the scene. + /// + /// The texture is scaled to the given size and rasterized at the given offset. + void addTexture(int textureId, { Offset offset: Offset.zero, double width: 0.0, double height: 0.0 }) { + assert(offset != null, 'Offset argument was null'); + _addTexture(offset.dx, offset.dy, width, height, textureId); + } + void _addTexture(double dx, double dy, double width, double height, int textureId) native "SceneBuilder_addTexture"; + /// (Fuchsia-only) Adds a scene rendered by another application to the scene /// for this application. void addChildScene({ diff --git a/engine/src/flutter/lib/ui/compositing/scene_builder.cc b/engine/src/flutter/lib/ui/compositing/scene_builder.cc index 9d4f1493b8..8879c7251e 100644 --- a/engine/src/flutter/lib/ui/compositing/scene_builder.cc +++ b/engine/src/flutter/lib/ui/compositing/scene_builder.cc @@ -35,6 +35,7 @@ IMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder); V(SceneBuilder, pushPhysicalModel) \ V(SceneBuilder, pop) \ V(SceneBuilder, addPicture) \ + V(SceneBuilder, addTexture) \ V(SceneBuilder, addChildScene) \ V(SceneBuilder, addPerformanceOverlay) \ V(SceneBuilder, setRasterizerTracingThreshold) \ @@ -124,6 +125,15 @@ void SceneBuilder::addPicture(double dx, ); } +void SceneBuilder::addTexture(double dx, + double dy, + double width, + double height, + int64_t textureId) { + layer_builder_->PushTexture(SkPoint::Make(dx, dy), + SkSize::Make(width, height), textureId); +} + void SceneBuilder::addChildScene(double dx, double dy, double width, diff --git a/engine/src/flutter/lib/ui/compositing/scene_builder.h b/engine/src/flutter/lib/ui/compositing/scene_builder.h index 688230ae73..bcccd23a74 100644 --- a/engine/src/flutter/lib/ui/compositing/scene_builder.h +++ b/engine/src/flutter/lib/ui/compositing/scene_builder.h @@ -56,7 +56,15 @@ class SceneBuilder : public fxl::RefCountedThreadSafe, double right, double top, double bottom); + void addPicture(double dx, double dy, Picture* picture, int hints); + + void addTexture(double dx, + double dy, + double width, + double height, + int64_t textureId); + void addChildScene(double dx, double dy, double width, diff --git a/engine/src/flutter/runtime/runtime_delegate.h b/engine/src/flutter/runtime/runtime_delegate.h index 2fb741a3f5..880ab83dab 100644 --- a/engine/src/flutter/runtime/runtime_delegate.h +++ b/engine/src/flutter/runtime/runtime_delegate.h @@ -18,7 +18,7 @@ namespace blink { class RuntimeDelegate { public: virtual std::string DefaultRouteName() = 0; - virtual void ScheduleFrame() = 0; + virtual void ScheduleFrame(bool regenerate_layer_tree = true) = 0; virtual void Render(std::unique_ptr layer_tree) = 0; virtual void UpdateSemantics(std::vector update) = 0; virtual void HandlePlatformMessage(fxl::RefPtr message) = 0; diff --git a/engine/src/flutter/shell/common/animator.cc b/engine/src/flutter/shell/common/animator.cc index ce6988f65d..30deb0638b 100644 --- a/engine/src/flutter/shell/common/animator.cc +++ b/engine/src/flutter/shell/common/animator.cc @@ -23,6 +23,7 @@ Animator::Animator(fml::WeakPtr rasterizer, pending_frame_semaphore_(1), frame_number_(1), paused_(false), + regenerate_layer_tree_(false), frame_scheduled_(false), weak_factory_(this) {} @@ -58,6 +59,7 @@ void Animator::BeginFrame(fxl::TimePoint frame_start_time, TRACE_EVENT_ASYNC_END0("flutter", "Frame Request Pending", frame_number_++); frame_scheduled_ = false; + regenerate_layer_tree_ = false; pending_frame_semaphore_.Signal(); if (!producer_continuation_) { @@ -116,14 +118,29 @@ void Animator::Render(std::unique_ptr layer_tree) { }); } -void Animator::RequestFrame() { +bool Animator::CanReuseLastLayerTree() { + return !regenerate_layer_tree_; +} + +void Animator::DrawLastLayerTree() { + pending_frame_semaphore_.Signal(); + blink::Threads::Gpu()->PostTask([rasterizer = rasterizer_]() { + if (rasterizer.get()) + rasterizer->DrawLastLayerTree(); + }); +} + +void Animator::RequestFrame(bool regenerate_layer_tree) { + if (regenerate_layer_tree) { + regenerate_layer_tree_ = true; + } if (paused_) { return; } if (!pending_frame_semaphore_.TryWait()) { - // Multiple calls to Animator::RequestFrame will still result in a single - // request to the VsyncWaiter. + // Multiple calls to Animator::RequestDrawOnVSync will still result in a + // single request to the VsyncWaiter. return; } @@ -149,8 +166,13 @@ void Animator::RequestFrame() { void Animator::AwaitVSync() { waiter_->AsyncWaitForVsync([self = weak_factory_.GetWeakPtr()]( fxl::TimePoint frame_start_time, fxl::TimePoint frame_target_time) { - if (self) - self->BeginFrame(frame_start_time, frame_target_time); + if (self) { + if (self->CanReuseLastLayerTree()) { + self->DrawLastLayerTree(); + } else { + self->BeginFrame(frame_start_time, frame_target_time); + } + } }); engine_->NotifyIdle(dart_frame_deadline_); diff --git a/engine/src/flutter/shell/common/animator.h b/engine/src/flutter/shell/common/animator.h index 7074864d64..300d422d59 100644 --- a/engine/src/flutter/shell/common/animator.h +++ b/engine/src/flutter/shell/common/animator.h @@ -28,7 +28,7 @@ class Animator { rasterizer_ = rasterizer; } - void RequestFrame(); + void RequestFrame(bool regenerate_layer_tree = true); void Render(std::unique_ptr layer_tree); @@ -42,6 +42,10 @@ class Animator { void BeginFrame(fxl::TimePoint frame_start_time, fxl::TimePoint frame_target_time); + bool CanReuseLastLayerTree(); + void DrawLastLayerTree(); + void RequestDrawOnVSync(); + void AwaitVSync(); const char* FrameParity(); @@ -57,6 +61,7 @@ class Animator { LayerTreePipeline::ProducerContinuation producer_continuation_; int64_t frame_number_; bool paused_; + bool regenerate_layer_tree_; bool frame_scheduled_; fml::WeakPtrFactory weak_factory_; diff --git a/engine/src/flutter/shell/common/engine.cc b/engine/src/flutter/shell/common/engine.cc index 91a9009729..b092ab2add 100644 --- a/engine/src/flutter/shell/common/engine.cc +++ b/engine/src/flutter/shell/common/engine.cc @@ -522,8 +522,8 @@ std::string Engine::DefaultRouteName() { return "/"; } -void Engine::ScheduleFrame() { - animator_->RequestFrame(); +void Engine::ScheduleFrame(bool regenerate_layer_tree) { + animator_->RequestFrame(regenerate_layer_tree); } void Engine::Render(std::unique_ptr layer_tree) { diff --git a/engine/src/flutter/shell/common/engine.h b/engine/src/flutter/shell/common/engine.h index 8568a22a47..6f7eb7c087 100644 --- a/engine/src/flutter/shell/common/engine.h +++ b/engine/src/flutter/shell/common/engine.h @@ -74,13 +74,13 @@ class Engine : public blink::RuntimeDelegate { void DispatchPointerDataPacket(const PointerDataPacket& packet); void DispatchSemanticsAction(int id, blink::SemanticsAction action); void SetSemanticsEnabled(bool enabled); + void ScheduleFrame(bool regenerate_layer_tree = true) override; void set_rasterizer(fml::WeakPtr rasterizer); private: // RuntimeDelegate methods: std::string DefaultRouteName() override; - void ScheduleFrame() override; void Render(std::unique_ptr layer_tree) override; void UpdateSemantics(std::vector update) override; void HandlePlatformMessage( diff --git a/engine/src/flutter/shell/common/null_rasterizer.cc b/engine/src/flutter/shell/common/null_rasterizer.cc index f774208ff2..adcb3bbacc 100644 --- a/engine/src/flutter/shell/common/null_rasterizer.cc +++ b/engine/src/flutter/shell/common/null_rasterizer.cc @@ -33,6 +33,14 @@ flow::LayerTree* NullRasterizer::GetLastLayerTree() { return nullptr; } +void NullRasterizer::DrawLastLayerTree() { + // Null rasterizer. Nothing to do. +} + +flow::TextureRegistry& NullRasterizer::GetTextureRegistry() { + return texture_registry_; +} + void NullRasterizer::Clear(SkColor color, const SkISize& size) { // Null rasterizer. Nothing to do. } diff --git a/engine/src/flutter/shell/common/null_rasterizer.h b/engine/src/flutter/shell/common/null_rasterizer.h index a5fee836c2..d629f167d1 100644 --- a/engine/src/flutter/shell/common/null_rasterizer.h +++ b/engine/src/flutter/shell/common/null_rasterizer.h @@ -28,6 +28,10 @@ class NullRasterizer : public Rasterizer { flow::LayerTree* GetLastLayerTree() override; + void DrawLastLayerTree() override; + + flow::TextureRegistry& GetTextureRegistry() override; + void Draw(fxl::RefPtr> pipeline) override; void AddNextFrameCallback(fxl::Closure nextFrameCallback) override; @@ -35,6 +39,7 @@ class NullRasterizer : public Rasterizer { private: std::unique_ptr surface_; fml::WeakPtrFactory weak_factory_; + flow::TextureRegistry texture_registry_; FXL_DISALLOW_COPY_AND_ASSIGN(NullRasterizer); }; diff --git a/engine/src/flutter/shell/common/platform_view.cc b/engine/src/flutter/shell/common/platform_view.cc index b71d6ac221..eaa293634e 100644 --- a/engine/src/flutter/shell/common/platform_view.cc +++ b/engine/src/flutter/shell/common/platform_view.cc @@ -135,6 +135,25 @@ void PlatformView::HandlePlatformMessage( response->CompleteEmpty(); } +void PlatformView::RegisterTexture(std::shared_ptr texture) { + ASSERT_IS_PLATFORM_THREAD + blink::Threads::Gpu()->PostTask([this, texture]() { + rasterizer_->GetTextureRegistry().RegisterTexture(texture); + }); +} + +void PlatformView::UnregisterTexture(int64_t texture_id) { + ASSERT_IS_PLATFORM_THREAD + blink::Threads::Gpu()->PostTask([this, texture_id]() { + rasterizer_->GetTextureRegistry().UnregisterTexture(texture_id); + }); +} + +void PlatformView::MarkTextureFrameAvailable(int64_t texture_id) { + ASSERT_IS_PLATFORM_THREAD + blink::Threads::UI()->PostTask([this]() { engine_->ScheduleFrame(false); }); +} + void PlatformView::SetupResourceContextOnIOThread() { fxl::AutoResetWaitableEvent latch; diff --git a/engine/src/flutter/shell/common/platform_view.h b/engine/src/flutter/shell/common/platform_view.h index a981b6a57d..29970ec3e6 100644 --- a/engine/src/flutter/shell/common/platform_view.h +++ b/engine/src/flutter/shell/common/platform_view.h @@ -7,6 +7,7 @@ #include +#include "flutter/flow/texture.h" #include "flutter/lib/ui/semantics/semantics_node.h" #include "flutter/shell/common/engine.h" #include "flutter/shell/common/shell.h" @@ -61,6 +62,15 @@ class PlatformView : public std::enable_shared_from_this { virtual void HandlePlatformMessage( fxl::RefPtr message); + // Called once per texture, on the platform thread. + void RegisterTexture(std::shared_ptr texture); + + // Called once per texture, on the platform thread. + void UnregisterTexture(int64_t texture_id); + + // Called once per texture update (e.g. video frame), on the platform thread. + virtual void MarkTextureFrameAvailable(int64_t texture_id); + void SetRasterizer(std::unique_ptr rasterizer); Rasterizer& rasterizer() { return *rasterizer_; } diff --git a/engine/src/flutter/shell/common/rasterizer.h b/engine/src/flutter/shell/common/rasterizer.h index 0a58871046..fdecdec7cf 100644 --- a/engine/src/flutter/shell/common/rasterizer.h +++ b/engine/src/flutter/shell/common/rasterizer.h @@ -33,6 +33,10 @@ class Rasterizer { virtual flow::LayerTree* GetLastLayerTree() = 0; + virtual void DrawLastLayerTree() = 0; + + virtual flow::TextureRegistry& GetTextureRegistry() = 0; + virtual void Draw( fxl::RefPtr> pipeline) = 0; diff --git a/engine/src/flutter/shell/gpu/gpu_rasterizer.cc b/engine/src/flutter/shell/gpu/gpu_rasterizer.cc index 4abe1e63f7..fe60f62486 100644 --- a/engine/src/flutter/shell/gpu/gpu_rasterizer.cc +++ b/engine/src/flutter/shell/gpu/gpu_rasterizer.cc @@ -29,6 +29,7 @@ void GPURasterizer::Setup(std::unique_ptr surface, fxl::Closure continuation, fxl::AutoResetWaitableEvent* setup_completion_event) { surface_ = std::move(surface); + compositor_context_.OnGrContextCreated(); continuation(); @@ -59,11 +60,11 @@ void GPURasterizer::Clear(SkColor color, const SkISize& size) { void GPURasterizer::Teardown( fxl::AutoResetWaitableEvent* teardown_completion_event) { + compositor_context_.OnGrContextDestroyed(); if (surface_) { surface_.reset(); } last_layer_tree_.reset(); - compositor_context_.OnGrContextDestroyed(); teardown_completion_event->Signal(); } @@ -71,6 +72,17 @@ flow::LayerTree* GPURasterizer::GetLastLayerTree() { return last_layer_tree_.get(); } +void GPURasterizer::DrawLastLayerTree() { + if (!last_layer_tree_ || !surface_) { + return; + } + DrawToSurface(*last_layer_tree_); +} + +flow::TextureRegistry& GPURasterizer::GetTextureRegistry() { + return compositor_context_.texture_registry(); +} + void GPURasterizer::Draw( fxl::RefPtr> pipeline) { TRACE_EVENT0("flutter", "GPURasterizer::Draw"); diff --git a/engine/src/flutter/shell/gpu/gpu_rasterizer.h b/engine/src/flutter/shell/gpu/gpu_rasterizer.h index b2a3e43ca3..d92fe63122 100644 --- a/engine/src/flutter/shell/gpu/gpu_rasterizer.h +++ b/engine/src/flutter/shell/gpu/gpu_rasterizer.h @@ -33,6 +33,10 @@ class GPURasterizer : public Rasterizer { flow::LayerTree* GetLastLayerTree() override; + void DrawLastLayerTree() override; + + flow::TextureRegistry& GetTextureRegistry() override; + void Draw(fxl::RefPtr> pipeline) override; // Set a callback to be called once when the next frame is drawn. diff --git a/engine/src/flutter/shell/platform/android/BUILD.gn b/engine/src/flutter/shell/platform/android/BUILD.gn index e1f7262b29..91b657fa66 100644 --- a/engine/src/flutter/shell/platform/android/BUILD.gn +++ b/engine/src/flutter/shell/platform/android/BUILD.gn @@ -17,6 +17,8 @@ shared_library("flutter_shell_native") { "android_context_gl.h", "android_environment_gl.cc", "android_environment_gl.h", + "android_external_texture_gl.h", + "android_external_texture_gl.cc", "android_native_window.cc", "android_native_window.h", "android_surface.cc", @@ -46,6 +48,7 @@ shared_library("flutter_shell_native") { "$flutter_root/shell/gpu", "//garnet/public/lib/fxl", "//third_party/skia", + "//third_party/skia:gpu", ] if (flutter_runtime_mode == "debug") { deps += [ "//third_party/dart/runtime:libdart_jit" ] @@ -114,6 +117,7 @@ java_library("flutter_shell_java") { "io/flutter/view/ResourceCleaner.java", "io/flutter/view/ResourceExtractor.java", "io/flutter/view/ResourcePaths.java", + "io/flutter/view/TextureRegistry.java", "io/flutter/view/VsyncWaiter.java", ] diff --git a/engine/src/flutter/shell/platform/android/android_external_texture_gl.cc b/engine/src/flutter/shell/platform/android/android_external_texture_gl.cc new file mode 100644 index 0000000000..41a89ccb95 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/android_external_texture_gl.cc @@ -0,0 +1,92 @@ +// Copyright 2017 The Chromium 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/shell/platform/android/android_external_texture_gl.h" + +// #include +#include +#include "flutter/common/threads.h" +#include "flutter/shell/platform/android/platform_view_android_jni.h" +#include "third_party/skia/include/gpu/GrTexture.h" + +namespace shell { + +AndroidExternalTextureGL::AndroidExternalTextureGL( + int64_t id, + const fml::jni::JavaObjectWeakGlobalRef& surfaceTexture) + : Texture(id), surface_texture_(surfaceTexture) {} + +AndroidExternalTextureGL::~AndroidExternalTextureGL() = default; + +void AndroidExternalTextureGL::OnGrContextCreated() { + ASSERT_IS_GPU_THREAD; + state_ = AttachmentState::uninitialized; +} + +void AndroidExternalTextureGL::MarkNewFrameAvailable() { + ASSERT_IS_GPU_THREAD; + new_frame_ready_ = true; +} + +void AndroidExternalTextureGL::Paint(SkCanvas& canvas, const SkRect& bounds) { + ASSERT_IS_GPU_THREAD; + if (state_ == AttachmentState::detached) { + return; + } + if (state_ == AttachmentState::uninitialized) { + glGenTextures(1, &texture_name_); + Attach(static_cast(texture_name_)); + state_ = AttachmentState::attached; + } + if (new_frame_ready_) { + Update(); + new_frame_ready_ = false; + } + GrGLTextureInfo textureInfo = {GL_TEXTURE_EXTERNAL_OES, texture_name_}; + GrBackendTexture backendTexture(bounds.width(), bounds.height(), + kRGBA_8888_GrPixelConfig, textureInfo); + sk_sp image = SkImage::MakeFromTexture( + canvas.getGrContext(), backendTexture, kTopLeft_GrSurfaceOrigin, + SkAlphaType::kPremul_SkAlphaType, nullptr); + if (image) { + canvas.drawImage(image, bounds.x(), bounds.y()); + } +} + +void AndroidExternalTextureGL::OnGrContextDestroyed() { + ASSERT_IS_GPU_THREAD; + if (state_ == AttachmentState::attached) { + Detach(); + } + state_ = AttachmentState::detached; +} + +void AndroidExternalTextureGL::Attach(jint textureName) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + fml::jni::ScopedJavaLocalRef surfaceTexture = + surface_texture_.get(env); + if (!surfaceTexture.is_null()) { + SurfaceTextureAttachToGLContext(env, surfaceTexture.obj(), textureName); + } +} + +void AndroidExternalTextureGL::Update() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + fml::jni::ScopedJavaLocalRef surfaceTexture = + surface_texture_.get(env); + if (!surfaceTexture.is_null()) { + SurfaceTextureUpdateTexImage(env, surfaceTexture.obj()); + } +} + +void AndroidExternalTextureGL::Detach() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + fml::jni::ScopedJavaLocalRef surfaceTexture = + surface_texture_.get(env); + if (!surfaceTexture.is_null()) { + SurfaceTextureDetachFromGLContext(env, surfaceTexture.obj()); + } +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/android/android_external_texture_gl.h b/engine/src/flutter/shell/platform/android/android_external_texture_gl.h new file mode 100644 index 0000000000..73b1de203b --- /dev/null +++ b/engine/src/flutter/shell/platform/android/android_external_texture_gl.h @@ -0,0 +1,53 @@ +// Copyright 2017 The Chromium 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_SHELL_PLATFORM_ANDROID_EXTERNAL_TEXTURE_GL_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_TEXTURE_GL_H_ + +#include +#include "flutter/flow/texture.h" +#include "flutter/fml/platform/android/jni_weak_ref.h" + +namespace shell { + +class AndroidExternalTextureGL : public flow::Texture { + public: + AndroidExternalTextureGL( + int64_t id, + const fml::jni::JavaObjectWeakGlobalRef& surfaceTexture); + + ~AndroidExternalTextureGL() override; + + virtual void Paint(SkCanvas& canvas, const SkRect& bounds) override; + + virtual void OnGrContextCreated() override; + + virtual void OnGrContextDestroyed() override; + + // Called on GPU thread. + void MarkNewFrameAvailable(); + + private: + void Attach(jint textureName); + + void Update(); + + void Detach(); + + enum class AttachmentState { uninitialized, attached, detached }; + + fml::jni::JavaObjectWeakGlobalRef surface_texture_; + + AttachmentState state_ = AttachmentState::uninitialized; + + bool new_frame_ready_ = false; + + GLuint texture_name_ = 0; + + FXL_DISALLOW_COPY_AND_ASSIGN(AndroidExternalTextureGL); +}; + +} // namespace shell + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_TEXTURE_GL_H_ diff --git a/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterActivityDelegate.java b/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterActivityDelegate.java index ba91f9eb99..0c3d71e646 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterActivityDelegate.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterActivityDelegate.java @@ -35,6 +35,7 @@ import io.flutter.plugin.platform.PlatformPlugin; import io.flutter.util.Preconditions; import io.flutter.view.FlutterMain; import io.flutter.view.FlutterView; +import io.flutter.view.TextureRegistry; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -422,6 +423,11 @@ public final class FlutterActivityDelegate return flutterView; } + @Override + public TextureRegistry textures() { + return flutterView; + } + @Override public FlutterView view() { return flutterView; diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java index 9257bb8312..b382aba0b4 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java @@ -1,3 +1,7 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + package io.flutter.plugin.common; import java.nio.ByteBuffer; diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java index bd4b52f591..78c09a9d49 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java @@ -1,3 +1,7 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + package io.flutter.plugin.common; import java.nio.ByteBuffer; diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java index 96c75bb70c..4586aea114 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java @@ -7,6 +7,7 @@ package io.flutter.plugin.common; import android.app.Activity; import android.content.Intent; import io.flutter.view.FlutterView; +import io.flutter.view.TextureRegistry; /** * Registry used by plugins to set up interaction with Android APIs. @@ -74,6 +75,12 @@ public interface PluginRegistry { */ BinaryMessenger messenger(); + /** + * Returns a {@link TextureRegistry} which the plugin can use for + * managing backend textures. + */ + TextureRegistry textures(); + /** * Returns the {@link FlutterView} that's instantiated by this plugin's * {@link #activity() activity}. diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java index fa0d579243..5e2374cf75 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java @@ -16,6 +16,7 @@ import android.graphics.Rect; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Matrix; +import android.graphics.SurfaceTexture; import android.os.Build; import android.text.format.DateFormat; import android.util.AttributeSet; @@ -52,12 +53,13 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; /** * An Android view containing a Flutter app. */ public class FlutterView extends SurfaceView - implements BinaryMessenger, AccessibilityManager.AccessibilityStateChangeListener { + implements BinaryMessenger, TextureRegistry, AccessibilityManager.AccessibilityStateChangeListener { /** * Interface for those objects that maintain and expose a reference to a @@ -106,6 +108,7 @@ public class FlutterView extends SurfaceView private final BroadcastReceiver mDiscoveryReceiver; private final List mActivityLifecycleListeners; private final List mFirstFrameListeners; + private final AtomicLong nextTextureId = new AtomicLong(0L); private long mNativePlatformView; private boolean mIsSoftwareRenderingEnabled = false; // using the software renderer or not @@ -681,6 +684,12 @@ public class FlutterView extends SurfaceView private static native boolean nativeGetIsSoftwareRenderingEnabled(); + private static native void nativeRegisterTexture(long nativePlatformViewAndroid, long textureId, SurfaceTexture surfaceTexture); + + private static native void nativeMarkTextureFrameAvailable(long nativePlatformViewAndroid, long textureId); + + private static native void nativeUnregisterTexture(long nativePlatformViewAndroid, long textureId); + private void updateViewportMetrics() { if (!isAttached()) return; @@ -952,4 +961,51 @@ public class FlutterView extends SurfaceView public interface FirstFrameListener { void onFirstFrame(); } + + @Override + public TextureRegistry.SurfaceTextureEntry createSurfaceTexture() { + final SurfaceTexture surfaceTexture = new SurfaceTexture(0); + surfaceTexture.detachFromGLContext(); + final SurfaceTextureRegistryEntry entry = new SurfaceTextureRegistryEntry( + nextTextureId.getAndIncrement(), surfaceTexture); + nativeRegisterTexture(mNativePlatformView, entry.id(), surfaceTexture); + return entry; + } + + final class SurfaceTextureRegistryEntry implements TextureRegistry.SurfaceTextureEntry { + private final long id; + private final SurfaceTexture surfaceTexture; + private boolean released; + + SurfaceTextureRegistryEntry(long id, SurfaceTexture surfaceTexture) { + this.id = id; + this.surfaceTexture = surfaceTexture; + this.surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() { + @Override + public void onFrameAvailable(SurfaceTexture texture) { + nativeMarkTextureFrameAvailable(mNativePlatformView, SurfaceTextureRegistryEntry.this.id); + } + }); + } + + @Override + public SurfaceTexture surfaceTexture() { + return surfaceTexture; + } + + @Override + public long id() { + return id; + } + + @Override + public void release() { + if (released) { + return; + } + released = true; + nativeUnregisterTexture(mNativePlatformView, id); + surfaceTexture.release(); + } + } } diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/TextureRegistry.java b/engine/src/flutter/shell/platform/android/io/flutter/view/TextureRegistry.java new file mode 100644 index 0000000000..992114dc07 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/TextureRegistry.java @@ -0,0 +1,42 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.view; + +import android.graphics.SurfaceTexture; + +/** + * Registry of backend textures used with a single {@link FlutterView} instance. + * Entries may be embedded into the Flutter view using the + * Texture + * widget. + */ +public interface TextureRegistry { + /** + * Creates and registers a SurfaceTexture managed by the Flutter engine. + * + * @return A SurfaceTextureEntry. + */ + SurfaceTextureEntry createSurfaceTexture(); + + /** + * A registry entry for a managed SurfaceTexture. + */ + interface SurfaceTextureEntry { + /** + * @return The managed SurfaceTexture. + */ + SurfaceTexture surfaceTexture(); + + /** + * @return The identity of this SurfaceTexture. + */ + long id(); + + /** + * Deregisters and releases this SurfaceTexture. + */ + void release(); + } +} diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.cc b/engine/src/flutter/shell/platform/android/platform_view_android.cc index 601752c2ee..1776d2744e 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android.cc @@ -18,6 +18,7 @@ #include "flutter/runtime/dart_service_isolate.h" #include "flutter/shell/common/null_rasterizer.h" #include "flutter/shell/gpu/gpu_rasterizer.h" +#include "flutter/shell/platform/android/android_external_texture_gl.h" #include "flutter/shell/platform/android/android_surface_gl.h" #include "flutter/shell/platform/android/android_surface_software.h" #include "flutter/shell/platform/android/platform_view_android_jni.h" @@ -546,6 +547,25 @@ void PlatformViewAndroid::RunFromSource(const std::string& assets_directory, fml::jni::DetachFromVM(); } +void PlatformViewAndroid::RegisterExternalTexture( + int64_t texture_id, + const fml::jni::JavaObjectWeakGlobalRef& surface_texture) { + RegisterTexture( + std::make_shared(texture_id, surface_texture)); +} + +void PlatformViewAndroid::MarkTextureFrameAvailable(int64_t texture_id) { + blink::Threads::Gpu()->PostTask([this, texture_id]() { + std::shared_ptr texture = + static_pointer_cast( + rasterizer_->GetTextureRegistry().GetTexture(texture_id)); + if (texture) { + texture->MarkNewFrameAvailable(); + } + }); + PlatformView::MarkTextureFrameAvailable(texture_id); +} + fml::jni::ScopedJavaLocalRef PlatformViewAndroid::GetBitmap( JNIEnv* env) { // Render the last frame to an array of pixels on the GPU thread. diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.h b/engine/src/flutter/shell/platform/android/platform_view_android.h index 9ea9ef7990..6edc492220 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.h +++ b/engine/src/flutter/shell/platform/android/platform_view_android.h @@ -99,6 +99,12 @@ class PlatformViewAndroid : public PlatformView { const std::string& main, const std::string& packages) override; + void RegisterExternalTexture( + int64_t texture_id, + const fml::jni::JavaObjectWeakGlobalRef& surface_texture); + + void MarkTextureFrameAvailable(int64_t texture_id) override; + void set_flutter_view(const fml::jni::JavaObjectWeakGlobalRef& flutter_view) { flutter_view_ = flutter_view; } diff --git a/engine/src/flutter/shell/platform/android/platform_view_android_jni.cc b/engine/src/flutter/shell/platform/android/platform_view_android_jni.cc index f9180d49a2..390a934750 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android_jni.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android_jni.cc @@ -3,11 +3,13 @@ // found in the LICENSE file. #include "flutter/shell/platform/android/platform_view_android_jni.h" + #include "flutter/common/settings.h" #include "flutter/fml/platform/android/jni_util.h" #include "flutter/fml/platform/android/jni_weak_ref.h" #include "flutter/fml/platform/android/scoped_java_ref.h" #include "flutter/runtime/dart_service_isolate.h" +#include "flutter/shell/platform/android/android_external_texture_gl.h" #include "lib/fxl/arraysize.h" #include "lib/fxl/logging.h" @@ -17,6 +19,7 @@ namespace shell { static fml::jni::ScopedJavaGlobalRef* g_flutter_view_class = nullptr; +static fml::jni::ScopedJavaGlobalRef* g_surface_texture_class = nullptr; // Called By Native @@ -56,6 +59,27 @@ void FlutterViewOnFirstFrame(JNIEnv* env, jobject obj) { FXL_CHECK(env->ExceptionCheck() == JNI_FALSE); } +static jmethodID g_attach_to_gl_context_method = nullptr; +void SurfaceTextureAttachToGLContext(JNIEnv* env, jobject obj, jint textureId) { + ASSERT_IS_GPU_THREAD; + env->CallVoidMethod(obj, g_attach_to_gl_context_method, textureId); + FXL_CHECK(env->ExceptionCheck() == JNI_FALSE); +} + +static jmethodID g_update_tex_image_method = nullptr; +void SurfaceTextureUpdateTexImage(JNIEnv* env, jobject obj) { + ASSERT_IS_GPU_THREAD; + env->CallVoidMethod(obj, g_update_tex_image_method); + FXL_CHECK(env->ExceptionCheck() == JNI_FALSE); +} + +static jmethodID g_detach_from_gl_context_method = nullptr; +void SurfaceTextureDetachFromGLContext(JNIEnv* env, jobject obj) { + ASSERT_IS_GPU_THREAD; + env->CallVoidMethod(obj, g_detach_from_gl_context_method); + FXL_CHECK(env->ExceptionCheck() == JNI_FALSE); +} + // Called By Java static jlong Attach(JNIEnv* env, jclass clazz, jobject flutterView) { @@ -198,6 +222,31 @@ static jboolean GetIsSoftwareRendering(JNIEnv* env, jobject jcaller) { return blink::Settings::Get().enable_software_rendering; } +static void RegisterTexture(JNIEnv* env, + jobject jcaller, + jlong platform_view, + jlong texture_id, + jobject surface_texture) { + PLATFORM_VIEW->RegisterExternalTexture( + static_cast(texture_id), + fml::jni::JavaObjectWeakGlobalRef(env, surface_texture)); +} + +static void MarkTextureFrameAvailable(JNIEnv* env, + jobject jcaller, + jlong platform_view, + jlong texture_id) { + return PLATFORM_VIEW->MarkTextureFrameAvailable( + static_cast(texture_id)); +} + +static void UnregisterTexture(JNIEnv* env, + jobject jcaller, + jlong platform_view, + jlong texture_id) { + PLATFORM_VIEW->UnregisterTexture(static_cast(texture_id)); +} + static void InvokePlatformMessageResponseCallback(JNIEnv* env, jobject jcaller, jlong platform_view, @@ -223,11 +272,16 @@ bool PlatformViewAndroid::Register(JNIEnv* env) { g_flutter_view_class = new fml::jni::ScopedJavaGlobalRef( env, env->FindClass("io/flutter/view/FlutterView")); - if (g_flutter_view_class->is_null()) { return false; } + g_surface_texture_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("android/graphics/SurfaceTexture")); + if (g_surface_texture_class->is_null()) { + return false; + } + static const JNINativeMethod methods[] = { { .name = "nativeAttach", @@ -324,6 +378,21 @@ bool PlatformViewAndroid::Register(JNIEnv* env) { .signature = "()Z", .fnPtr = reinterpret_cast(&shell::GetIsSoftwareRendering), }, + { + .name = "nativeRegisterTexture", + .signature = "(JJLandroid/graphics/SurfaceTexture;)V", + .fnPtr = reinterpret_cast(&shell::RegisterTexture), + }, + { + .name = "nativeMarkTextureFrameAvailable", + .signature = "(JJ)V", + .fnPtr = reinterpret_cast(&shell::MarkTextureFrameAvailable), + }, + { + .name = "nativeUnregisterTexture", + .signature = "(JJ)V", + .fnPtr = reinterpret_cast(&shell::UnregisterTexture), + }, }; if (env->RegisterNatives(g_flutter_view_class->obj(), methods, @@ -360,6 +429,28 @@ bool PlatformViewAndroid::Register(JNIEnv* env) { if (g_on_first_frame_method == nullptr) { return false; } + + g_attach_to_gl_context_method = env->GetMethodID( + g_surface_texture_class->obj(), "attachToGLContext", "(I)V"); + + if (g_attach_to_gl_context_method == nullptr) { + return false; + } + + g_update_tex_image_method = + env->GetMethodID(g_surface_texture_class->obj(), "updateTexImage", "()V"); + + if (g_update_tex_image_method == nullptr) { + return false; + } + + g_detach_from_gl_context_method = env->GetMethodID( + g_surface_texture_class->obj(), "detachFromGLContext", "()V"); + + if (g_detach_from_gl_context_method == nullptr) { + return false; + } + return true; } diff --git a/engine/src/flutter/shell/platform/android/platform_view_android_jni.h b/engine/src/flutter/shell/platform/android/platform_view_android_jni.h index 576dd589dd..76915734f3 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android_jni.h +++ b/engine/src/flutter/shell/platform/android/platform_view_android_jni.h @@ -29,6 +29,12 @@ void FlutterViewUpdateSemantics(JNIEnv* env, void FlutterViewOnFirstFrame(JNIEnv* env, jobject obj); +void SurfaceTextureAttachToGLContext(JNIEnv* env, jobject obj, jint textureId); + +void SurfaceTextureUpdateTexImage(JNIEnv* env, jobject obj); + +void SurfaceTextureDetachFromGLContext(JNIEnv* env, jobject obj); + } // namespace shell #endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_JNI_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn index ebffd7e431..4ba54b9372 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn +++ b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn @@ -22,6 +22,7 @@ _flutter_framework_headers = [ "framework/Headers/FlutterMacros.h", "framework/Headers/FlutterNavigationController.h", "framework/Headers/FlutterPlugin.h", + "framework/Headers/FlutterTexture.h", "framework/Headers/FlutterViewController.h", ] @@ -62,6 +63,8 @@ shared_library("create_flutter_framework_dylib") { "framework/Source/platform_message_router.mm", "framework/Source/vsync_waiter_ios.h", "framework/Source/vsync_waiter_ios.mm", + "ios_external_texture_gl.h", + "ios_external_texture_gl.mm", "ios_gl_context.h", "ios_gl_context.mm", "ios_surface.h", @@ -100,9 +103,10 @@ shared_library("create_flutter_framework_dylib") { defines = [ "FLUTTER_FRAMEWORK" ] libs = [ + "CoreMedia.framework", + "CoreVideo.framework", "UIKit.framework", "OpenGLES.framework", - "AVFoundation.framework", "AudioToolbox.framework", "QuartzCore.framework", ] diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h index 609eb70694..5ad9b64d76 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h @@ -14,6 +14,7 @@ #include "FlutterMacros.h" #include "FlutterNavigationController.h" #include "FlutterPlugin.h" +#include "FlutterTexture.h" #include "FlutterViewController.h" #endif // FLUTTER_FLUTTER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h index a2ad15742f..4f28e70b65 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h @@ -34,6 +34,12 @@ FLUTTER_EXPORT // Defaults to window's rootViewController. - (NSObject*)binaryMessenger; +// Can be overriden by subclasses to provide a custom FlutterTextureRegistry, +// typically a FlutterViewController, for plugin interop. +// +// Defaults to window's rootViewController. +- (NSObject*)textures; + @end #endif // FLUTTER_FLUTTERDARTPROJECT_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h index 660e14a2e7..fece7fee92 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h @@ -10,6 +10,7 @@ #include "FlutterBinaryMessenger.h" #include "FlutterChannels.h" #include "FlutterCodecs.h" +#include "FlutterTexture.h" NS_ASSUME_NONNULL_BEGIN @protocol FlutterPluginRegistrar; @@ -142,6 +143,14 @@ NS_ASSUME_NONNULL_BEGIN */ - (NSObject*)messenger; +/** + Returns a `FlutterTextureRegistry` for registering textures + provided by the plugin. + + - Returns: The texture registry. + */ +- (NSObject*)textures; + /** Publishes a value for external use of the plugin. diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterTexture.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterTexture.h new file mode 100644 index 0000000000..c755ebf711 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterTexture.h @@ -0,0 +1,29 @@ +// Copyright 2017 The Chromium 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_FLUTTERTEXTURE_H_ +#define FLUTTER_FLUTTERTEXTURE_H_ + +#import +#import + +#include "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +FLUTTER_EXPORT +@protocol FlutterTexture +- (CVPixelBufferRef)copyPixelBuffer; +@end + +FLUTTER_EXPORT +@protocol FlutterTextureRegistry +- (int64_t)registerTexture:(NSObject*)texture; +- (void)textureFrameAvailable:(int64_t)textureId; +- (void)unregisterTexture:(int64_t)textureId; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_FLUTTERTEXTURE_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h index 18480cb0ad..68e0d0f65a 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h @@ -11,9 +11,10 @@ #include "FlutterBinaryMessenger.h" #include "FlutterDartProject.h" #include "FlutterMacros.h" +#include "FlutterTexture.h" FLUTTER_EXPORT -@interface FlutterViewController : UIViewController +@interface FlutterViewController : UIViewController - (instancetype)initWithProject:(FlutterDartProject*)project nibName:(NSString*)nibNameOrNil diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm index ad52df61ec..63000fede1 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm @@ -219,6 +219,14 @@ return nil; } +- (NSObject*)textures { + UIViewController* rootViewController = _window.rootViewController; + if ([rootViewController conformsToProtocol:@protocol(FlutterTextureRegistry)]) { + return (NSObject*)rootViewController; + } + return nil; +} + - (NSObject*)registrarForPlugin:(NSString*)pluginKey { NSAssert(self.pluginPublications[pluginKey] == nil, @"Duplicate plugin key: %@", pluginKey); self.pluginPublications[pluginKey] = [NSNull null]; @@ -258,6 +266,10 @@ return [_appDelegate binaryMessenger]; } +- (NSObject*)textures { + return [_appDelegate textures]; +} + - (void)publish:(NSObject*)value { _appDelegate.pluginPublications[_pluginKey] = value; } diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm index c1b2dfcc4b..9c41fe03f8 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -7,6 +7,7 @@ #include #include "flutter/common/threads.h" +#include "flutter/flow/texture.h" #include "flutter/fml/platform/darwin/platform_version.h" #include "flutter/fml/platform/darwin/scoped_block.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" @@ -19,6 +20,7 @@ #include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #include "flutter/shell/platform/darwin/ios/framework/Source/flutter_main_ios.h" #include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h" +#include "flutter/shell/platform/darwin/ios/ios_external_texture_gl.h" #include "flutter/shell/platform/darwin/ios/platform_view_ios.h" #include "lib/fxl/functional/make_copyable.h" #include "lib/fxl/time/time_delta.h" @@ -74,6 +76,7 @@ class PlatformMessageResponseDarwin : public blink::PlatformMessageResponse { fml::scoped_nsprotocol _systemChannel; fml::scoped_nsprotocol _settingsChannel; fml::scoped_nsprotocol _launchView; + int64_t _nextTextureId; bool _platformSupportsTouchTypes; bool _platformSupportsTouchPressure; bool _platformSupportsTouchOrientationAndTilt; @@ -865,4 +868,20 @@ constexpr CGFloat kStandardStatusBarHeight = 20.0; NSAssert(channel, @"The channel must not be null"); _platformView->platform_message_router().SetMessageHandler(channel.UTF8String, handler); } + +#pragma mark - FlutterTextureRegistry + +- (int64_t)registerTexture:(NSObject*)texture { + int64_t textureId = _nextTextureId++; + _platformView->RegisterExternalTexture(textureId, texture); + return textureId; +} + +- (void)unregisterTexture:(int64_t)textureId { + _platformView->UnregisterTexture(textureId); +} + +- (void)textureFrameAvailable:(int64_t)textureId { + _platformView->MarkTextureFrameAvailable(textureId); +} @end diff --git a/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_gl.h b/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_gl.h new file mode 100644 index 0000000000..c26eb8c29c --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_gl.h @@ -0,0 +1,38 @@ +// Copyright 2017 The Chromium 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_SHELL_PLATFORM_IOS_EXTERNAL_TEXTURE_GL_H_ +#define FLUTTER_SHELL_PLATFORM_IOS_EXTERNAL_TEXTURE_GL_H_ + +#include "flutter/flow/texture.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#include "flutter/fml/platform/darwin/scoped_nsobject.h" +#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterTexture.h" + +namespace shell { + +class IOSExternalTextureGL : public flow::Texture { + public: + IOSExternalTextureGL(int64_t textureId, + NSObject* externalTexture); + + ~IOSExternalTextureGL() override; + + // Called from GPU thread. + virtual void Paint(SkCanvas& canvas, const SkRect& bounds) override; + + virtual void OnGrContextCreated() override; + + virtual void OnGrContextDestroyed() override; + + private: + fml::scoped_nsobject> external_texture_; + fml::CFRef cache_ref_; + fml::CFRef texture_ref_; + FXL_DISALLOW_COPY_AND_ASSIGN(IOSExternalTextureGL); +}; + +} // namespace shell + +#endif // FLUTTER_SHELL_PLATFORM_IOS_EXTERNAL_TEXTURE_GL_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_gl.mm b/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_gl.mm new file mode 100644 index 0000000000..270fdc634e --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_gl.mm @@ -0,0 +1,81 @@ +// Copyright 2017 The Chromium 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/shell/platform/darwin/ios/ios_external_texture_gl.h" + +#include +#import +#import +#include "flutter/common/threads.h" +#include "flutter/lib/ui/painting/resource_context.h" +#include "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/GrBackendSurface.h" +#include "third_party/skia/include/gpu/GrTexture.h" +#include "third_party/skia/include/gpu/GrTypes.h" + +namespace shell { + +IOSExternalTextureGL::IOSExternalTextureGL(int64_t textureId, + NSObject* externalTexture) + : Texture(textureId), external_texture_(externalTexture) { + FXL_DCHECK(external_texture_); +} + +IOSExternalTextureGL::~IOSExternalTextureGL() = default; + +void IOSExternalTextureGL::Paint(SkCanvas& canvas, const SkRect& bounds) { + ASSERT_IS_GPU_THREAD; + if (!cache_ref_) { + CVOpenGLESTextureCacheRef cache; + CVReturn err = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, NULL, + [EAGLContext currentContext], NULL, &cache); + if (err == noErr) { + cache_ref_.Reset(cache); + } else { + FXL_LOG(WARNING) << "Failed to create GLES texture cache: " << err; + return; + } + } + fml::CFRef bufferRef; + bufferRef.Reset([external_texture_ copyPixelBuffer]); + if (bufferRef != nullptr) { + CVOpenGLESTextureRef texture; + CVReturn err = CVOpenGLESTextureCacheCreateTextureFromImage( + kCFAllocatorDefault, cache_ref_, bufferRef, nullptr, GL_TEXTURE_2D, GL_RGBA, + static_cast(CVPixelBufferGetWidth(bufferRef)), + static_cast(CVPixelBufferGetHeight(bufferRef)), GL_BGRA, GL_UNSIGNED_BYTE, 0, + &texture); + texture_ref_.Reset(texture); + if (err != noErr) { + FXL_LOG(WARNING) << "Could not create texture from pixel buffer: " << err; + return; + } + } + if (!texture_ref_) { + return; + } + GrGLTextureInfo textureInfo = {CVOpenGLESTextureGetTarget(texture_ref_), + CVOpenGLESTextureGetName(texture_ref_)}; + GrBackendTexture backendTexture(bounds.width(), bounds.height(), kRGBA_8888_GrPixelConfig, + textureInfo); + sk_sp image = + SkImage::MakeFromTexture(canvas.getGrContext(), backendTexture, kTopLeft_GrSurfaceOrigin, + SkAlphaType::kPremul_SkAlphaType, nullptr); + if (image) { + canvas.drawImage(image, bounds.x(), bounds.y()); + } +} + +void IOSExternalTextureGL::OnGrContextCreated() { + ASSERT_IS_GPU_THREAD +} + +void IOSExternalTextureGL::OnGrContextDestroyed() { + ASSERT_IS_GPU_THREAD + texture_ref_.Reset(nullptr); + cache_ref_.Reset(nullptr); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h index f9c6cafacc..d13371d0db 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h @@ -9,6 +9,7 @@ #include "flutter/fml/memory/weak_ptr.h" #include "flutter/shell/common/platform_view.h" +#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterTexture.h" #include "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" #include "flutter/shell/platform/darwin/ios/framework/Source/platform_message_router.h" #include "flutter/shell/platform/darwin/ios/ios_surface.h" @@ -50,6 +51,8 @@ class PlatformViewIOS : public PlatformView { void HandlePlatformMessage( fxl::RefPtr message) override; + void RegisterExternalTexture(int64_t id, NSObject* texture); + void UpdateSemantics(std::vector update) override; void RunFromSource(const std::string& assets_directory, diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm index fa1871816c..caefbed22e 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm @@ -13,6 +13,7 @@ #include "flutter/shell/gpu/gpu_rasterizer.h" #include "flutter/shell/platform/darwin/common/process_info_mac.h" #include "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" +#include "flutter/shell/platform/darwin/ios/ios_external_texture_gl.h" #include "lib/fxl/synchronization/waitable_event.h" namespace shell { @@ -100,6 +101,11 @@ void PlatformViewIOS::HandlePlatformMessage(fxl::RefPtr platform_message_router_.HandlePlatformMessage(std::move(message)); } +void PlatformViewIOS::RegisterExternalTexture(int64_t texture_id, + NSObject* texture) { + RegisterTexture(std::make_shared(texture_id, texture)); +} + void PlatformViewIOS::RunFromSource(const std::string& assets_directory, const std::string& main, const std::string& packages) {