Add texture support (eg video, camera) (flutter/engine#4159)

This commit is contained in:
Chinmay Garde
2017-11-02 02:57:29 -07:00
committed by Mikkel Nygaard Ravn
parent a802554df1
commit d0ec6228a5
52 changed files with 955 additions and 16 deletions

View File

@@ -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 = [

View File

@@ -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();
}

View File

@@ -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<ProcessInfo> process_info_;
Counter frame_count_;
Stopwatch frame_time_;

View File

@@ -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<flow::TextureLayer>();
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,

View File

@@ -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,

View File

@@ -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;
};

View File

@@ -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,

View File

@@ -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");

View File

@@ -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> texture =
context.texture_registry.GetTexture(texture_id_);
if (!texture) {
return;
}
texture->Paint(context.canvas, paint_bounds());
}
} // namespace flow

View File

@@ -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_

View File

@@ -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> 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<Texture> TextureRegistry::GetTexture(int64_t id) {
ASSERT_IS_GPU_THREAD
return mapping_[id];
}
Texture::Texture(int64_t id) : id_(id) {}
Texture::~Texture() = default;
} // namespace flow

View File

@@ -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 <map>
#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> texture);
// Called from GPU thread.
void UnregisterTexture(int64_t id);
// Called from GPU thread.
std::shared_ptr<Texture> GetTexture(int64_t id);
// Called from GPU thread.
void OnGrContextCreated();
// Called from GPU thread.
void OnGrContextDestroyed();
private:
std::map<int64_t, std::shared_ptr<Texture>> mapping_;
FXL_DISALLOW_COPY_AND_ASSIGN(TextureRegistry);
};
} // namespace flow
#endif // FLUTTER_FLOW_TEXTURE_H_

View File

@@ -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({

View File

@@ -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,

View File

@@ -56,7 +56,15 @@ class SceneBuilder : public fxl::RefCountedThreadSafe<SceneBuilder>,
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,

View File

@@ -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<flow::LayerTree> layer_tree) = 0;
virtual void UpdateSemantics(std::vector<SemanticsNode> update) = 0;
virtual void HandlePlatformMessage(fxl::RefPtr<PlatformMessage> message) = 0;

View File

@@ -23,6 +23,7 @@ Animator::Animator(fml::WeakPtr<Rasterizer> 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<flow::LayerTree> 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_);

View File

@@ -28,7 +28,7 @@ class Animator {
rasterizer_ = rasterizer;
}
void RequestFrame();
void RequestFrame(bool regenerate_layer_tree = true);
void Render(std::unique_ptr<flow::LayerTree> 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<Animator> weak_factory_;

View File

@@ -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<flow::LayerTree> layer_tree) {

View File

@@ -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> rasterizer);
private:
// RuntimeDelegate methods:
std::string DefaultRouteName() override;
void ScheduleFrame() override;
void Render(std::unique_ptr<flow::LayerTree> layer_tree) override;
void UpdateSemantics(std::vector<blink::SemanticsNode> update) override;
void HandlePlatformMessage(

View File

@@ -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.
}

View File

@@ -28,6 +28,10 @@ class NullRasterizer : public Rasterizer {
flow::LayerTree* GetLastLayerTree() override;
void DrawLastLayerTree() override;
flow::TextureRegistry& GetTextureRegistry() override;
void Draw(fxl::RefPtr<flutter::Pipeline<flow::LayerTree>> pipeline) override;
void AddNextFrameCallback(fxl::Closure nextFrameCallback) override;
@@ -35,6 +39,7 @@ class NullRasterizer : public Rasterizer {
private:
std::unique_ptr<Surface> surface_;
fml::WeakPtrFactory<NullRasterizer> weak_factory_;
flow::TextureRegistry texture_registry_;
FXL_DISALLOW_COPY_AND_ASSIGN(NullRasterizer);
};

View File

@@ -135,6 +135,25 @@ void PlatformView::HandlePlatformMessage(
response->CompleteEmpty();
}
void PlatformView::RegisterTexture(std::shared_ptr<flow::Texture> 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;

View File

@@ -7,6 +7,7 @@
#include <memory>
#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<PlatformView> {
virtual void HandlePlatformMessage(
fxl::RefPtr<blink::PlatformMessage> message);
// Called once per texture, on the platform thread.
void RegisterTexture(std::shared_ptr<flow::Texture> 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& rasterizer() { return *rasterizer_; }

View File

@@ -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<flutter::Pipeline<flow::LayerTree>> pipeline) = 0;

View File

@@ -29,6 +29,7 @@ void GPURasterizer::Setup(std::unique_ptr<Surface> 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<flutter::Pipeline<flow::LayerTree>> pipeline) {
TRACE_EVENT0("flutter", "GPURasterizer::Draw");

View File

@@ -33,6 +33,10 @@ class GPURasterizer : public Rasterizer {
flow::LayerTree* GetLastLayerTree() override;
void DrawLastLayerTree() override;
flow::TextureRegistry& GetTextureRegistry() override;
void Draw(fxl::RefPtr<flutter::Pipeline<flow::LayerTree>> pipeline) override;
// Set a callback to be called once when the next frame is drawn.

View File

@@ -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",
]

View File

@@ -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 <GLES/gl.h>
#include <GLES/glext.h>
#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<jint>(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<SkImage> 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<jobject> 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<jobject> surfaceTexture =
surface_texture_.get(env);
if (!surfaceTexture.is_null()) {
SurfaceTextureUpdateTexImage(env, surfaceTexture.obj());
}
}
void AndroidExternalTextureGL::Detach() {
JNIEnv* env = fml::jni::AttachCurrentThread();
fml::jni::ScopedJavaLocalRef<jobject> surfaceTexture =
surface_texture_.get(env);
if (!surfaceTexture.is_null()) {
SurfaceTextureDetachFromGLContext(env, surfaceTexture.obj());
}
}
} // namespace shell

View File

@@ -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 <GLES/gl.h>
#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_

View File

@@ -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;

View File

@@ -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;

View File

@@ -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;

View File

@@ -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}.

View File

@@ -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<ActivityLifecycleListener> mActivityLifecycleListeners;
private final List<FirstFrameListener> 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();
}
}
}

View File

@@ -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
* <a href="https://docs.flutter.io/flutter/widgets/Texture-class.html">Texture</a>
* 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();
}
}

View File

@@ -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<AndroidExternalTextureGL>(texture_id, surface_texture));
}
void PlatformViewAndroid::MarkTextureFrameAvailable(int64_t texture_id) {
blink::Threads::Gpu()->PostTask([this, texture_id]() {
std::shared_ptr<AndroidExternalTextureGL> texture =
static_pointer_cast<AndroidExternalTextureGL>(
rasterizer_->GetTextureRegistry().GetTexture(texture_id));
if (texture) {
texture->MarkNewFrameAvailable();
}
});
PlatformView::MarkTextureFrameAvailable(texture_id);
}
fml::jni::ScopedJavaLocalRef<jobject> PlatformViewAndroid::GetBitmap(
JNIEnv* env) {
// Render the last frame to an array of pixels on the GPU thread.

View File

@@ -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;
}

View File

@@ -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<jclass>* g_flutter_view_class = nullptr;
static fml::jni::ScopedJavaGlobalRef<jclass>* 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<int64_t>(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<int64_t>(texture_id));
}
static void UnregisterTexture(JNIEnv* env,
jobject jcaller,
jlong platform_view,
jlong texture_id) {
PLATFORM_VIEW->UnregisterTexture(static_cast<int64_t>(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<jclass>(
env, env->FindClass("io/flutter/view/FlutterView"));
if (g_flutter_view_class->is_null()) {
return false;
}
g_surface_texture_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
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<void*>(&shell::GetIsSoftwareRendering),
},
{
.name = "nativeRegisterTexture",
.signature = "(JJLandroid/graphics/SurfaceTexture;)V",
.fnPtr = reinterpret_cast<void*>(&shell::RegisterTexture),
},
{
.name = "nativeMarkTextureFrameAvailable",
.signature = "(JJ)V",
.fnPtr = reinterpret_cast<void*>(&shell::MarkTextureFrameAvailable),
},
{
.name = "nativeUnregisterTexture",
.signature = "(JJ)V",
.fnPtr = reinterpret_cast<void*>(&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;
}

View File

@@ -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_

View File

@@ -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",
]

View File

@@ -14,6 +14,7 @@
#include "FlutterMacros.h"
#include "FlutterNavigationController.h"
#include "FlutterPlugin.h"
#include "FlutterTexture.h"
#include "FlutterViewController.h"
#endif // FLUTTER_FLUTTER_H_

View File

@@ -34,6 +34,12 @@ FLUTTER_EXPORT
// Defaults to window's rootViewController.
- (NSObject<FlutterBinaryMessenger>*)binaryMessenger;
// Can be overriden by subclasses to provide a custom FlutterTextureRegistry,
// typically a FlutterViewController, for plugin interop.
//
// Defaults to window's rootViewController.
- (NSObject<FlutterTextureRegistry>*)textures;
@end
#endif // FLUTTER_FLUTTERDARTPROJECT_H_

View File

@@ -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<FlutterBinaryMessenger>*)messenger;
/**
Returns a `FlutterTextureRegistry` for registering textures
provided by the plugin.
- Returns: The texture registry.
*/
- (NSObject<FlutterTextureRegistry>*)textures;
/**
Publishes a value for external use of the plugin.

View File

@@ -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 <CoreMedia/CoreMedia.h>
#import <Foundation/Foundation.h>
#include "FlutterMacros.h"
NS_ASSUME_NONNULL_BEGIN
FLUTTER_EXPORT
@protocol FlutterTexture<NSObject>
- (CVPixelBufferRef)copyPixelBuffer;
@end
FLUTTER_EXPORT
@protocol FlutterTextureRegistry<NSObject>
- (int64_t)registerTexture:(NSObject<FlutterTexture>*)texture;
- (void)textureFrameAvailable:(int64_t)textureId;
- (void)unregisterTexture:(int64_t)textureId;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_FLUTTERTEXTURE_H_

View File

@@ -11,9 +11,10 @@
#include "FlutterBinaryMessenger.h"
#include "FlutterDartProject.h"
#include "FlutterMacros.h"
#include "FlutterTexture.h"
FLUTTER_EXPORT
@interface FlutterViewController : UIViewController<FlutterBinaryMessenger>
@interface FlutterViewController : UIViewController<FlutterBinaryMessenger, FlutterTextureRegistry>
- (instancetype)initWithProject:(FlutterDartProject*)project
nibName:(NSString*)nibNameOrNil

View File

@@ -219,6 +219,14 @@
return nil;
}
- (NSObject<FlutterTextureRegistry>*)textures {
UIViewController* rootViewController = _window.rootViewController;
if ([rootViewController conformsToProtocol:@protocol(FlutterTextureRegistry)]) {
return (NSObject<FlutterTextureRegistry>*)rootViewController;
}
return nil;
}
- (NSObject<FlutterPluginRegistrar>*)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<FlutterTextureRegistry>*)textures {
return [_appDelegate textures];
}
- (void)publish:(NSObject*)value {
_appDelegate.pluginPublications[_pluginKey] = value;
}

View File

@@ -7,6 +7,7 @@
#include <memory>
#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<FlutterBasicMessageChannel*> _systemChannel;
fml::scoped_nsprotocol<FlutterBasicMessageChannel*> _settingsChannel;
fml::scoped_nsprotocol<UIView*> _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<FlutterTexture>*)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

View File

@@ -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<FlutterTexture>* 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<NSObject<FlutterTexture>> external_texture_;
fml::CFRef<CVOpenGLESTextureCacheRef> cache_ref_;
fml::CFRef<CVOpenGLESTextureRef> texture_ref_;
FXL_DISALLOW_COPY_AND_ASSIGN(IOSExternalTextureGL);
};
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_IOS_EXTERNAL_TEXTURE_GL_H_

View File

@@ -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 <OpenGLES/EAGL.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#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<FlutterTexture>* 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<CVPixelBufferRef> 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<int>(CVPixelBufferGetWidth(bufferRef)),
static_cast<int>(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<SkImage> 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

View File

@@ -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<blink::PlatformMessage> message) override;
void RegisterExternalTexture(int64_t id, NSObject<FlutterTexture>* texture);
void UpdateSemantics(std::vector<blink::SemanticsNode> update) override;
void RunFromSource(const std::string& assets_directory,

View File

@@ -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<blink::PlatformMessage>
platform_message_router_.HandlePlatformMessage(std::move(message));
}
void PlatformViewIOS::RegisterExternalTexture(int64_t texture_id,
NSObject<FlutterTexture>* texture) {
RegisterTexture(std::make_shared<IOSExternalTextureGL>(texture_id, texture));
}
void PlatformViewIOS::RunFromSource(const std::string& assets_directory,
const std::string& main,
const std::string& packages) {