blob: a83bf32ef2f045a4fbc397b2c62ee4e7852b8bcc [file] [edit]
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/command_buffer/service/raster_decoder.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/containers/span.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_span.h"
#include "build/build_config.h"
#include "cc/paint/paint_cache.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/paint_op.h"
#include "cc/paint/paint_op_buffer.h"
#include "cc/paint/paint_op_buffer_serializer.h"
#include "gpu/command_buffer/client/client_font_manager.h"
#include "gpu/command_buffer/client/client_test_helper.h"
#include "gpu/command_buffer/common/buffer.h"
#include "gpu/command_buffer/common/discardable_handle.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"
#include "gpu/command_buffer/common/mailbox.h"
#include "gpu/command_buffer/common/raster_cmd_format.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "gpu/command_buffer/service/query_manager.h"
#include "gpu/command_buffer/service/raster_decoder_unittest_base.h"
#include "gpu/command_buffer/service/shared_context_state.h"
#include "gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/shared_image_factory.h"
#include "gpu/command_buffer/service/shared_image/shared_image_manager.h"
#include "gpu/command_buffer/service/shared_image/shared_image_representation.h"
#include "gpu/command_buffer/service/shared_image/test_image_backing.h"
#include "gpu/command_buffer/service/test_helper.h"
#include "gpu/config/gpu_preferences.h"
#include "skia/ext/font_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkFont.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/core/SkTextBlob.h"
#include "third_party/skia/include/gpu/ganesh/GrBackendSemaphore.h"
#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLTypes.h"
#include "third_party/skia/include/private/chromium/GrPromiseImageTexture.h"
#include "ui/gl/gl_context_stub.h"
#include "ui/gl/gl_mock.h"
#include "ui/gl/gl_surface_stub.h"
#include "ui/gl/init/gl_factory.h"
#include "ui/gl/test/gl_surface_test_support.h"
using ::testing::_;
using ::testing::Return;
using ::testing::SetArgPointee;
namespace gpu {
namespace raster {
namespace {
void CopyMailboxes(GLbyte (&output)[sizeof(Mailbox) * 2],
const Mailbox& source,
const Mailbox& dest) {
UNSAFE_TODO(memcpy(output, source.name, sizeof(source.name)));
UNSAFE_TODO(
memcpy(output + sizeof(source.name), dest.name, sizeof(dest.name)));
}
} // anonymous namespace
class RasterDecoderTest : public RasterDecoderTestBase {
public:
RasterDecoderTest() = default;
};
INSTANTIATE_TEST_SUITE_P(Service, RasterDecoderTest, ::testing::Bool());
INSTANTIATE_TEST_SUITE_P(Service,
RasterDecoderManualInitTest,
::testing::Bool());
const GLsync kGlSync = reinterpret_cast<GLsync>(0xdeadbeef);
TEST_P(RasterDecoderTest, BeginEndQueryEXTCommandsCompletedCHROMIUM) {
GenHelper<cmds::GenQueriesEXTImmediate>(kNewClientId);
cmds::BeginQueryEXT begin_cmd;
begin_cmd.Init(GL_COMMANDS_COMPLETED_CHROMIUM, kNewClientId,
shared_memory_id_, kSharedMemoryOffset);
EXPECT_EQ(error::kNoError, ExecuteCmd(begin_cmd));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
QueryManager* query_manager = decoder_->GetQueryManager();
ASSERT_TRUE(query_manager != nullptr);
QueryManager::Query* query = query_manager->GetQuery(kNewClientId);
ASSERT_TRUE(query != nullptr);
EXPECT_FALSE(query->IsPending());
EXPECT_TRUE(query->IsActive());
EXPECT_CALL(*gl_, Flush()).RetiresOnSaturation();
EXPECT_CALL(*gl_, FenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0))
.WillOnce(Return(kGlSync))
.RetiresOnSaturation();
#if DCHECK_IS_ON()
EXPECT_CALL(*gl_, IsSync(kGlSync))
.WillOnce(Return(GL_TRUE))
.RetiresOnSaturation();
#endif
cmds::EndQueryEXT end_cmd;
end_cmd.Init(GL_COMMANDS_COMPLETED_CHROMIUM, 1);
EXPECT_EQ(error::kNoError, ExecuteCmd(end_cmd));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
EXPECT_TRUE(query->IsPending());
EXPECT_FALSE(query->IsActive());
#if DCHECK_IS_ON()
EXPECT_CALL(*gl_, IsSync(kGlSync))
.WillOnce(Return(GL_TRUE))
.RetiresOnSaturation();
#endif
EXPECT_CALL(*gl_, ClientWaitSync(kGlSync, _, _))
.WillOnce(Return(GL_TIMEOUT_EXPIRED))
.RetiresOnSaturation();
query_manager->ProcessPendingQueries(false);
EXPECT_TRUE(query->IsPending());
#if DCHECK_IS_ON()
EXPECT_CALL(*gl_, IsSync(kGlSync))
.WillOnce(Return(GL_TRUE))
.RetiresOnSaturation();
#endif
EXPECT_CALL(*gl_, ClientWaitSync(kGlSync, _, _))
.WillOnce(Return(GL_ALREADY_SIGNALED))
.RetiresOnSaturation();
query_manager->ProcessPendingQueries(false);
EXPECT_FALSE(query->IsPending());
#if DCHECK_IS_ON()
EXPECT_CALL(*gl_, IsSync(kGlSync))
.WillOnce(Return(GL_TRUE))
.RetiresOnSaturation();
#endif
EXPECT_CALL(*gl_, DeleteSync(kGlSync)).Times(1).RetiresOnSaturation();
ResetDecoder();
}
TEST_P(RasterDecoderTest, BeginEndQueryEXTCommandsIssuedCHROMIUM) {
cmds::BeginQueryEXT begin_cmd;
GenHelper<cmds::GenQueriesEXTImmediate>(kNewClientId);
// Test valid parameters work.
begin_cmd.Init(GL_COMMANDS_ISSUED_CHROMIUM, kNewClientId, shared_memory_id_,
kSharedMemoryOffset);
EXPECT_EQ(error::kNoError, ExecuteCmd(begin_cmd));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
QueryManager* query_manager = decoder_->GetQueryManager();
ASSERT_TRUE(query_manager != nullptr);
QueryManager::Query* query = query_manager->GetQuery(kNewClientId);
ASSERT_TRUE(query != nullptr);
EXPECT_FALSE(query->IsPending());
EXPECT_TRUE(query->IsActive());
// Test end succeeds.
cmds::EndQueryEXT end_cmd;
end_cmd.Init(GL_COMMANDS_ISSUED_CHROMIUM, 1);
EXPECT_EQ(error::kNoError, ExecuteCmd(end_cmd));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
EXPECT_FALSE(query->IsPending());
EXPECT_FALSE(query->IsActive());
}
TEST_P(RasterDecoderManualInitTest, GetCapabilitiesHalfFloatLinear) {
InitState init;
init.extensions.push_back("GL_OES_texture_half_float_linear");
InitDecoder(init);
AddExpectationsForGetCapabilities();
const auto& caps = decoder_->GetCapabilities();
EXPECT_TRUE(caps.texture_half_float_linear);
}
TEST_P(RasterDecoderManualInitTest, GetCapabilitiesNorm16) {
// R16 requires an ES3 context plus the extension to be available.
InitState init;
init.context_type = CONTEXT_TYPE_OPENGLES3;
init.gl_version = "OpenGL ES 3.0";
init.extensions.push_back("GL_EXT_texture_norm16");
InitDecoder(init);
AddExpectationsForGetCapabilities();
const auto& caps = decoder_->GetCapabilities();
EXPECT_TRUE(caps.texture_norm16);
}
class RasterDecoderOOPTest : public testing::Test, public DecoderClient {
public:
void SetUp() override {
display_ = gl::GLSurfaceTestSupport::InitializeOneOff();
gpu::GpuDriverBugWorkarounds workarounds;
scoped_refptr<gl::GLShareGroup> share_group = new gl::GLShareGroup();
scoped_refptr<gl::GLSurface> surface =
gl::init::CreateOffscreenGLSurface(display_, gfx::Size());
scoped_refptr<gl::GLContext> context = gl::init::CreateGLContext(
share_group.get(), surface.get(), gl::GLContextAttribs());
ASSERT_TRUE(context->MakeCurrent(surface.get()));
gpu_feature_info_.status_values[GPU_FEATURE_TYPE_GPU_TILE_RASTERIZATION] =
kGpuFeatureStatusEnabled;
context_state_ = base::MakeRefCounted<SharedContextState>(
std::move(share_group), std::move(surface), std::move(context),
false /* use_virtualized_gl_contexts */, base::DoNothing(),
GpuPreferences().gr_context_type);
context_state_->InitializeSkia(GpuPreferences(), workarounds);
context_state_->InitializeGL(GpuPreferences(), workarounds,
gpu_feature_info_);
decoder_ = CreateDecoder();
scoped_refptr<gpu::Buffer> buffer =
command_buffer_service_->CreateTransferBufferHelper(kSharedBufferSize,
&shared_memory_id_);
shared_memory_offset_ = kSharedMemoryOffset;
shared_memory_address_ = UNSAFE_TODO(
static_cast<int8_t*>(buffer->memory()) + shared_memory_offset_);
workarounds.webgl_or_caps_max_texture_size = INT_MAX - 1;
shared_image_factory_ = std::make_unique<SharedImageFactory>(
GpuPreferences(), workarounds, GpuFeatureInfo(), context_state_.get(),
&shared_image_manager_, nullptr,
/*is_for_display_compositor=*/false);
client_texture_mailbox_ =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888, /*width=*/2,
/*height=*/2, /*cleared=*/false);
// When creating the mailbox, we create a WrappedSkImage shared image which
// sets this flag to true. Some tests expect this flag to be false when
// testing so we reset it back here to false.
context_state_->set_need_context_state_reset(/*reset=*/false);
}
void TearDown() override {
context_state_->MakeCurrent(nullptr);
decoder_->EndDecoding();
decoder_->Destroy(!decoder_->WasContextLost());
decoder_.reset();
command_buffer_service_.reset();
shared_image_factory_->DestroyAllSharedImages(true);
shared_image_factory_.reset();
context_state_.reset();
context_state_ = nullptr;
gl::GLSurfaceTestSupport::ShutdownGL(display_);
}
RasterDecoderOOPTest() : memory_tracker_(nullptr) {
UNSAFE_TODO(memset(immediate_buffer_, 0xEE, sizeof(immediate_buffer_)));
}
// DecoderClient implementation.
void OnConsoleMessage(int32_t id, const std::string& message) override {}
void CacheBlob(gpu::GpuDiskCacheType type,
const std::string& key,
const std::string& blob) override {}
void OnFenceSyncRelease(uint64_t release) override {}
void OnDescheduleUntilFinished() override {}
void OnRescheduleAfterFinished() override {}
void ScheduleGrContextCleanup() override {}
void HandleReturnData(base::span<const uint8_t> data) override {}
std::unique_ptr<RasterDecoder> CreateDecoder() {
command_buffer_service_ =
std::make_unique<testing::NiceMock<MockClientCommandBuffer>>();
auto decoder = RasterDecoder::Create(
this, command_buffer_service_.get(), &outputter_, gpu_feature_info_,
GpuPreferences(), /*memory_tracker=*/nullptr, &shared_image_manager_,
context_state_, /*is_priviliged=*/true);
CHECK_EQ(decoder->Initialize(), ContextResult::kSuccess);
return decoder;
}
gpu::Mailbox CreateMailbox(viz::SharedImageFormat format,
GLsizei width,
GLsizei height,
bool cleared) {
gpu::Mailbox mailbox = gpu::Mailbox::Generate();
gfx::Size size(width, height);
auto color_space = format.is_single_plane()
? gfx::ColorSpace::CreateSRGB()
: gfx::ColorSpace::CreateREC709();
// Via this function, this test creates mailboxes that are used as both the
// sources of reads and destinations of writes via the raster interface.
shared_image_factory_->CreateSharedImage(
mailbox,
SharedImageInfo(
format, size, color_space, kTopLeft_GrSurfaceOrigin,
format.is_single_plane() ? kPremul_SkAlphaType
: kOpaque_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"TestLabel"),
gpu::kNullSurfaceHandle);
if (cleared) {
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(mailbox, context_state_.get());
representation->SetCleared();
}
return mailbox;
}
template <typename T>
T* GetImmediateAs() {
return reinterpret_cast<T*>(immediate_buffer_);
}
template <typename T>
error::Error ExecuteCmd(RasterDecoder* decoder, const T& cmd) {
static_assert(T::kArgFlags == cmd::kFixed,
"T::kArgFlags should equal cmd::kFixed");
int entries_processed = 0;
return decoder->DoCommands(1, reinterpret_cast<const void*>(&cmd),
ComputeNumEntries(sizeof(cmd)),
&entries_processed);
}
template <typename T>
error::Error ExecuteImmediateCmd(const T& cmd, size_t data_size) {
static_assert(T::kArgFlags == cmd::kAtLeastN,
"T::kArgFlags should equal cmd::kAtLeastN");
int entries_processed = 0;
return decoder_->DoCommands(1, reinterpret_cast<const void*>(&cmd),
ComputeNumEntries(sizeof(cmd) + data_size),
&entries_processed);
}
template <typename T>
T GetSharedMemoryAs() {
return reinterpret_cast<T>(shared_memory_address_.get());
}
GLint GetGLError() {
cmds::GetError cmd;
cmd.Init(shared_memory_id_, shared_memory_offset_);
EXPECT_EQ(error::kNoError, ExecuteCmd(decoder_.get(), cmd));
return static_cast<GLint>(*GetSharedMemoryAs<GLenum*>());
}
SharedImageManager* shared_image_manager() { return &shared_image_manager_; }
protected:
GpuFeatureInfo gpu_feature_info_;
gles2::TraceOutputter outputter_;
std::unique_ptr<MockClientCommandBuffer> command_buffer_service_;
MemoryTypeTracker memory_tracker_;
scoped_refptr<SharedContextState> context_state_;
gpu::Mailbox client_texture_mailbox_;
std::unique_ptr<RasterDecoder> decoder_;
int32_t shared_memory_id_ = 0;
uint32_t shared_memory_offset_ = 0;
raw_ptr<void> shared_memory_address_ = nullptr;
const size_t kSharedBufferSize = 2048;
const uint32_t kSharedMemoryOffset = 132;
uint32_t immediate_buffer_[64];
std::unique_ptr<SharedImageFactory> shared_image_factory_;
SharedImageManager shared_image_manager_;
raw_ptr<gl::GLDisplay> display_ = nullptr;
};
TEST_F(RasterDecoderOOPTest, CopyTexSubImage2DSizeMismatch) {
context_state_->set_need_context_state_reset(true);
// Create uninitialized source texture mailbox.
gpu::Mailbox source_texture_mailbox =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888,
/*width=*/1, /*height=*/1,
/*cleared=*/true);
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_texture_mailbox, client_texture_mailbox_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(client_texture_mailbox_, context_state_.get());
{
// This will initialize the bottom right corner of destination.
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(1, 1, 0, 0, 1, 1, 1, 1, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect(1, 1, 1, 1));
}
{
// Dest rect outside of dest bounds
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(2, 2, 0, 0, 1, 1, 1, 1, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect(1, 1, 1, 1));
}
{
// Source rect outside of source bounds
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 2, 2, 2, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect(1, 1, 1, 1));
}
{
// Empty source rect (zero width) with non-empty dest rect.
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 0, 1, 2, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect(1, 1, 1, 1));
}
{
// Empty dest rect (zero height) with non-empty source rect.
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 1, 1, 2, 0, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect(1, 1, 1, 1));
}
}
TEST_F(RasterDecoderOOPTest, CopySharedImageEmptyRect) {
context_state_->set_need_context_state_reset(true);
gpu::Mailbox source_texture_mailbox =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888,
/*width=*/2, /*height=*/2,
/*cleared=*/true);
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_texture_mailbox, client_texture_mailbox_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(client_texture_mailbox_, context_state_.get());
ASSERT_TRUE(representation);
EXPECT_FALSE(representation->IsCleared());
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
// Empty source width with non-empty destination rect.
cmd.Init(0, 0, 0, 0, 0, 2, 2, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect());
EXPECT_FALSE(representation->IsCleared());
// Empty source height with non-empty destination rect.
cmd.Init(0, 0, 0, 0, 2, 0, 2, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect());
EXPECT_FALSE(representation->IsCleared());
// Empty destination width with non-empty source rect.
cmd.Init(0, 0, 0, 0, 2, 2, 0, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect());
EXPECT_FALSE(representation->IsCleared());
// Empty destination height with non-empty source rect.
cmd.Init(0, 0, 0, 0, 2, 2, 2, 0, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect());
EXPECT_FALSE(representation->IsCleared());
// Both source and destination rects empty.
cmd.Init(1, 1, 0, 0, 0, 0, 0, 0, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(representation->ClearedRect(), gfx::Rect());
EXPECT_FALSE(representation->IsCleared());
}
TEST_F(RasterDecoderOOPTest, CopyTexSubImage2DTwiceClearsUnclearedTexture) {
context_state_->set_need_context_state_reset(true);
// Create uninitialized source texture mailbox.
gpu::Mailbox source_texture_mailbox =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888,
/*width=*/2, /*height=*/2,
/*cleared=*/true);
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_texture_mailbox, client_texture_mailbox_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(client_texture_mailbox_, context_state_.get());
EXPECT_FALSE(representation->IsCleared());
// This will initialize the top half of destination.
{
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 2, 1, 2, 1, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
}
EXPECT_EQ(gfx::Rect(0, 0, 2, 1), representation->ClearedRect());
EXPECT_FALSE(representation->IsCleared());
// This will initialize bottom half of the destination.
{
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 1, 0, 0, 2, 1, 2, 1, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
}
EXPECT_TRUE(representation->IsCleared());
}
// Unlike the GLES2 version, RasterInterface's CopySharedImage does not allow
// initializing a texture in parts *unless* the rectangles being cleared
// can be trivially combined into a larger rectangle.
TEST_F(RasterDecoderOOPTest, CopyTexSubImage2DPartialFailsWithUnalignedRect) {
context_state_->set_need_context_state_reset(true);
// Create uninitialized source texture mailbox.
gpu::Mailbox source_texture_mailbox =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888,
/*width=*/2, /*height=*/2,
/*cleared=*/true);
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_texture_mailbox, client_texture_mailbox_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(client_texture_mailbox_, context_state_.get());
EXPECT_FALSE(representation->IsCleared());
// This will initialize the top half of destination.
{
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 2, 1, 2, 1, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
}
EXPECT_EQ(gfx::Rect(0, 0, 2, 1), representation->ClearedRect());
EXPECT_FALSE(representation->IsCleared());
// This will attempt to initialize the bottom corner of the destination. As
// the new rect cannot be trivially combined with the previous cleared rect,
// this will fail.
{
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(1, 1, 0, 0, 1, 1, 1, 1, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
}
EXPECT_EQ(gfx::Rect(0, 0, 2, 1), representation->ClearedRect());
EXPECT_FALSE(representation->IsCleared());
}
TEST_F(RasterDecoderOOPTest, StateRestoreAcrossDecoders) {
// First decoder receives a skia command requiring context state reset.
auto decoder1 = CreateDecoder();
EXPECT_FALSE(context_state_->need_context_state_reset());
decoder1->MakeCurrent();
decoder1->SetUpForRasterCHROMIUMForTest();
cmds::EndRasterCHROMIUM end_raster_cmd;
end_raster_cmd.Init();
EXPECT_FALSE(error::IsError(ExecuteCmd(decoder1.get(), end_raster_cmd)));
EXPECT_TRUE(context_state_->need_context_state_reset());
// Another decoder receives a command which does not require consistent state,
// it should be processed without state restoration.
auto decoder2 = CreateDecoder();
decoder2->MakeCurrent();
decoder2->SetUpForRasterCHROMIUMForTest();
EXPECT_FALSE(error::IsError(ExecuteCmd(decoder2.get(), end_raster_cmd)));
EXPECT_TRUE(context_state_->need_context_state_reset());
decoder1->Destroy(true);
context_state_->MakeCurrent(nullptr);
decoder2->Destroy(true);
// Make sure the context is preserved across decoders.
EXPECT_FALSE(context_state_->gr_context()->abandoned());
}
TEST_F(RasterDecoderOOPTest, SharedImageProviderRejectsActiveOutputMailbox) {
context_state_->set_need_context_state_reset(true);
gpu::Mailbox mailbox =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888,
/*width=*/2, /*height=*/2,
/*cleared=*/true);
auto& cmd = *GetImmediateAs<cmds::BeginRasterCHROMIUMImmediate>();
cmd.Init(0.0f, 0.0f, 0.0f, 0.0f, false, 0, kNoMSAA, false, 1.0f,
mailbox.name);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailbox.name)));
cc::SharedImageProvider* provider = decoder_->GetSharedImageProviderForTest();
ASSERT_TRUE(provider);
cc::SharedImageProvider::Error error;
sk_sp<SkImage> image = provider->OpenSharedImageForRead(mailbox, error);
EXPECT_FALSE(image);
EXPECT_EQ(error, cc::SharedImageProvider::Error::kNoAccess);
}
namespace {
// Source backing which raises a GL error when accessed. ProduceMemory()
// returns a working CPU representation, while ProduceSkiaGanesh() fails.
class GLErrorOnAccessTestImageBacking : public TestImageBacking {
public:
GLErrorOnAccessTestImageBacking(const Mailbox& mailbox,
const SharedImageInfo& si_info,
bool raise_gl_error)
: TestImageBacking(mailbox, si_info, /*estimated_size=*/0),
raise_gl_error_(raise_gl_error) {
bitmap_.allocN32Pixels(si_info.size.width(), si_info.size.height());
bitmap_.eraseColor(SK_ColorRED);
SetCleared();
}
void MaybeRaiseGLError() {
if (raise_gl_error_) {
glEnable(GL_NONE);
}
}
SkPixmap pixmap() const { return bitmap_.pixmap(); }
protected:
std::unique_ptr<MemoryImageRepresentation> ProduceMemory(
SharedImageManager* manager,
MemoryTypeTracker* tracker) override;
std::unique_ptr<SkiaGaneshImageRepresentation> ProduceSkiaGanesh(
SharedImageManager* manager,
MemoryTypeTracker* tracker,
scoped_refptr<SharedContextState> context_state) override {
MaybeRaiseGLError();
return nullptr;
}
private:
const bool raise_gl_error_;
SkBitmap bitmap_;
};
class GLErrorOnAccessMemoryImageRepresentation
: public MemoryImageRepresentation {
public:
GLErrorOnAccessMemoryImageRepresentation(
SharedImageManager* manager,
GLErrorOnAccessTestImageBacking* backing,
MemoryTypeTracker* tracker)
: MemoryImageRepresentation(manager, backing, tracker) {}
protected:
SkPixmap BeginReadAccess() override {
auto* backing =
static_cast<GLErrorOnAccessTestImageBacking*>(this->backing());
backing->MaybeRaiseGLError();
return backing->pixmap();
}
};
std::unique_ptr<MemoryImageRepresentation>
GLErrorOnAccessTestImageBacking::ProduceMemory(SharedImageManager* manager,
MemoryTypeTracker* tracker) {
return std::make_unique<GLErrorOnAccessMemoryImageRepresentation>(
manager, this, tracker);
}
class CpuSurfaceTestImageBacking;
class CpuScopedWriteAccess : public SkiaImageRepresentation::ScopedWriteAccess {
public:
CpuScopedWriteAccess(SkiaImageRepresentation* representation,
std::vector<sk_sp<SkSurface>> surfaces)
: SkiaImageRepresentation::ScopedWriteAccess(representation,
std::move(surfaces)) {}
bool HasBackendSurfaceEndState() override { return true; }
void ApplyBackendSurfaceEndState() override {}
};
class CpuScopedReadAccess : public SkiaImageRepresentation::ScopedReadAccess {
public:
CpuScopedReadAccess(
SkiaImageRepresentation* representation,
std::vector<sk_sp<GrPromiseImageTexture>> promise_image_textures,
sk_sp<SkImage> image)
: SkiaImageRepresentation::ScopedReadAccess(
representation,
std::move(promise_image_textures)),
image_(std::move(image)) {}
sk_sp<SkImage> CreateSkImage(
SharedContextState* context_state,
SkImages::TextureReleaseProc texture_release_proc = nullptr,
SkImages::ReleaseContext release_context = nullptr) override {
return image_;
}
sk_sp<SkImage> CreateSkImageForPlane(
size_t plane_index,
SharedContextState* context_state,
SkImages::TextureReleaseProc texture_release_proc = nullptr,
SkImages::ReleaseContext release_context = nullptr) override {
return nullptr;
}
bool HasBackendSurfaceEndState() override { return false; }
void ApplyBackendSurfaceEndState() override {}
private:
sk_sp<SkImage> image_;
};
class CpuSurfaceTestImageBacking : public TestImageBacking {
public:
CpuSurfaceTestImageBacking(const Mailbox& mailbox,
const SharedImageInfo& si_info)
: TestImageBacking(mailbox, si_info, /*estimated_size=*/0) {
const int num_planes = format().NumberOfPlanes();
plane_bitmaps_.resize(num_planes);
for (int plane = 0; plane < num_planes; ++plane) {
gfx::Size plane_size = format().GetPlaneSize(plane, size());
SkColorType color_type = viz::ToClosestSkColorType(format(), plane);
SkAlphaType alpha =
format().is_multi_plane() ? kOpaque_SkAlphaType : alpha_type();
SkImageInfo info = SkImageInfo::Make(
plane_size.width(), plane_size.height(), color_type, alpha);
plane_bitmaps_[plane].allocPixels(info);
}
}
SkBitmap& plane_bitmap(int plane) { return plane_bitmaps_[plane]; }
const SkBitmap& plane_bitmap(int plane) const {
return plane_bitmaps_[plane];
}
void set_fail_produce_skia(bool fail) { fail_produce_skia_ = fail; }
bool fail_produce_skia() const { return fail_produce_skia_; }
protected:
std::unique_ptr<SkiaGaneshImageRepresentation> ProduceSkiaGanesh(
SharedImageManager* manager,
MemoryTypeTracker* tracker,
scoped_refptr<SharedContextState> context_state) override;
private:
std::vector<SkBitmap> plane_bitmaps_;
bool fail_produce_skia_ = false;
};
class CpuSurfaceSkiaGaneshImageRepresentation
: public SkiaGaneshImageRepresentation {
public:
CpuSurfaceSkiaGaneshImageRepresentation(
SharedImageManager* manager,
CpuSurfaceTestImageBacking* backing,
MemoryTypeTracker* tracker,
scoped_refptr<SharedContextState> context_state)
: SkiaGaneshImageRepresentation(context_state->gr_context(),
manager,
backing,
tracker) {}
CpuSurfaceTestImageBacking* cpu_backing() {
return static_cast<CpuSurfaceTestImageBacking*>(backing());
}
std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess(
int final_msaa_count,
const SkSurfaceProps& surface_props,
const gfx::Rect& update_rect,
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
AllowUnclearedAccess allow_uncleared,
bool use_sk_surface = true) override {
if (!cpu_backing()->can_access()) {
return nullptr;
}
const int num_planes = format().NumberOfPlanes();
std::vector<sk_sp<SkSurface>> surfaces(num_planes);
for (int plane = 0; plane < num_planes; ++plane) {
surfaces[plane] = SkSurfaces::WrapPixels(
cpu_backing()->plane_bitmap(plane).pixmap(), &surface_props);
if (!surfaces[plane]) {
return nullptr;
}
}
return std::make_unique<CpuScopedWriteAccess>(this, std::move(surfaces));
}
std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess(
int final_msaa_count,
const SkSurfaceProps& surface_props,
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
AllowUnclearedAccess allow_uncleared,
bool use_sk_surface = true) override {
return BeginScopedWriteAccess(
final_msaa_count, surface_props, gfx::Rect(size()), begin_semaphores,
end_semaphores, allow_uncleared, use_sk_surface);
}
std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess(
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
AllowUnclearedAccess allow_uncleared,
bool use_sk_surface = true) override {
return BeginScopedWriteAccess(1, SkSurfaceProps(), begin_semaphores,
end_semaphores, allow_uncleared,
use_sk_surface);
}
std::unique_ptr<ScopedReadAccess> BeginScopedReadAccess(
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores) override {
if (!cpu_backing()->can_access()) {
return nullptr;
}
auto backend_texture =
GrBackendTextures::MakeGL(1, 1, skgpu::Mipmapped::kNo,
GrGLTextureInfo{GL_TEXTURE_2D, 1, GL_RGBA8});
auto promise_texture = GrPromiseImageTexture::Make(backend_texture);
std::vector<sk_sp<GrPromiseImageTexture>> promise_textures;
promise_textures.push_back(std::move(promise_texture));
sk_sp<SkImage> image =
SkImages::RasterFromBitmap(cpu_backing()->plane_bitmap(0));
return std::make_unique<CpuScopedReadAccess>(
this, std::move(promise_textures), std::move(image));
}
protected:
std::vector<sk_sp<SkSurface>> BeginWriteAccess(
int final_msaa_count,
const SkSurfaceProps& surface_props,
const gfx::Rect& update_rect,
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
std::unique_ptr<skgpu::MutableTextureState>* end_state) override {
return {};
}
std::vector<sk_sp<GrPromiseImageTexture>> BeginWriteAccess(
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
std::unique_ptr<skgpu::MutableTextureState>* end_state) override {
return {};
}
void EndWriteAccess() override {}
std::vector<sk_sp<GrPromiseImageTexture>> BeginReadAccess(
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
std::unique_ptr<skgpu::MutableTextureState>* end_state) override {
return {};
}
void EndReadAccess() override {}
};
std::unique_ptr<SkiaGaneshImageRepresentation>
CpuSurfaceTestImageBacking::ProduceSkiaGanesh(
SharedImageManager* manager,
MemoryTypeTracker* tracker,
scoped_refptr<SharedContextState> context_state) {
if (fail_produce_skia_) {
return nullptr;
}
return std::make_unique<CpuSurfaceSkiaGaneshImageRepresentation>(
manager, this, tracker, std::move(context_state));
}
} // namespace
class RasterDecoderOOPCopyGLErrorTest
: public RasterDecoderOOPTest,
public testing::WithParamInterface<bool> {
public:
bool raise_gl_error() const { return GetParam(); }
std::unique_ptr<SharedImageRepresentationFactoryRef> CreateSourceImage(
const Mailbox& mailbox) {
SharedImageInfo si_info(viz::SinglePlaneFormat::kRGBA_8888, gfx::Size(2, 2),
gfx::ColorSpace::CreateSRGB(),
kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ, "TestLabel");
return shared_image_manager()->Register(
std::make_unique<GLErrorOnAccessTestImageBacking>(mailbox, si_info,
raise_gl_error()),
&memory_tracker_);
}
};
INSTANTIATE_TEST_SUITE_P(All, RasterDecoderOOPCopyGLErrorTest, testing::Bool());
// A GL error raised while copying from a CPU-backed source must leave the
// destination uncleared.
TEST_P(RasterDecoderOOPCopyGLErrorTest, CopyFromMemory) {
if (!context_state_->GrContextIsGL()) {
GTEST_SKIP() << "GL error checks only apply to Ganesh-GL.";
}
Mailbox source_mailbox = Mailbox::Generate();
auto source_ref = CreateSourceImage(source_mailbox);
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_mailbox, client_texture_mailbox_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(client_texture_mailbox_, context_state_.get());
EXPECT_FALSE(representation->IsCleared());
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 2, 2, 2, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(raise_gl_error() ? GL_INVALID_ENUM : GL_NO_ERROR, GetGLError());
EXPECT_EQ(!raise_gl_error(), representation->IsCleared());
}
// A GL error raised on the path that clears the destination when the source
// can't be read must leave the destination uncleared.
TEST_P(RasterDecoderOOPCopyGLErrorTest, ClearWhenSourceUnavailable) {
if (!context_state_->GrContextIsGL()) {
GTEST_SKIP() << "GL error checks only apply to Ganesh-GL.";
}
Mailbox source_mailbox = Mailbox::Generate();
auto source_ref = CreateSourceImage(source_mailbox);
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_mailbox, client_texture_mailbox_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto representation =
repr_factory.ProduceSkia(client_texture_mailbox_, context_state_.get());
EXPECT_FALSE(representation->IsCleared());
// Scaling skips the CPU upload path.
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 1, 1, 2, 2, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(!raise_gl_error(), representation->IsCleared());
}
namespace {
// Source backing which counts attempts to produce a Skia representation, e.g.
// to check that a command doesn't produce one (which can allocate, see
// CompoundImageBacking) before validating its arguments.
class CountingProduceSkiaTestImageBacking : public TestImageBacking {
public:
CountingProduceSkiaTestImageBacking(const Mailbox& mailbox,
const SharedImageInfo& si_info)
: TestImageBacking(mailbox, si_info, /*estimated_size=*/0) {
SetCleared();
}
int produce_skia_count() const { return produce_skia_count_; }
protected:
std::unique_ptr<SkiaGaneshImageRepresentation> ProduceSkiaGanesh(
SharedImageManager* manager,
MemoryTypeTracker* tracker,
scoped_refptr<SharedContextState> context_state) override {
++produce_skia_count_;
return nullptr;
}
std::unique_ptr<SkiaGraphiteImageRepresentation> ProduceSkiaGraphite(
SharedImageManager* manager,
MemoryTypeTracker* tracker,
scoped_refptr<SharedContextState> context_state) override {
++produce_skia_count_;
return nullptr;
}
private:
int produce_skia_count_ = 0;
};
} // namespace
// Readbacks must validate their arguments and shared memory before producing
// the source image. Each param runs a readback whose last shared memory check
// fails (true), or a valid readback as a control (false).
class RasterDecoderOOPReadbackOrderTest
: public RasterDecoderOOPTest,
public testing::WithParamInterface<bool> {
public:
bool invalid_shm() const { return GetParam(); }
void SetUp() override {
RasterDecoderOOPTest::SetUp();
source_mailbox_ = Mailbox::Generate();
SharedImageInfo si_info(viz::SinglePlaneFormat::kRGBA_8888, gfx::Size(2, 2),
gfx::ColorSpace::CreateSRGB(),
kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ, "TestLabel");
auto backing = std::make_unique<CountingProduceSkiaTestImageBacking>(
source_mailbox_, si_info);
source_backing_ = backing.get();
source_ref_ =
shared_image_manager()->Register(std::move(backing), &memory_tracker_);
}
void TearDown() override {
source_backing_ = nullptr;
source_ref_.reset();
RasterDecoderOOPTest::TearDown();
}
// Checks that the source was only produced for the valid readback.
void ExpectProducedOnlyIfValid() {
if (invalid_shm()) {
EXPECT_EQ(GL_INVALID_OPERATION, GetGLError());
EXPECT_EQ(0, source_backing_->produce_skia_count());
} else {
// The backing can't produce a Skia representation, so the readback fails
// after producing it.
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(1, source_backing_->produce_skia_count());
}
}
protected:
// Past the end of the shared memory buffer.
static constexpr GLuint kOutOfRangeOffset = 4096;
Mailbox source_mailbox_;
raw_ptr<CountingProduceSkiaTestImageBacking> source_backing_ = nullptr;
std::unique_ptr<SharedImageRepresentationFactoryRef> source_ref_;
};
INSTANTIATE_TEST_SUITE_P(All,
RasterDecoderOOPReadbackOrderTest,
testing::Bool());
TEST_P(RasterDecoderOOPReadbackOrderTest, ARGB) {
using Result = cmds::ReadbackARGBImagePixelsINTERNALImmediate::Result;
const GLuint pixels_offset =
invalid_shm() ? kOutOfRangeOffset : sizeof(Result);
auto& cmd = *GetImmediateAs<cmds::ReadbackARGBImagePixelsINTERNALImmediate>();
cmd.Init(/*src_x=*/0, /*src_y=*/0, /*plane_index=*/0, /*dst_width=*/2,
/*dst_height=*/2, /*row_bytes=*/8, kRGBA_8888_SkColorType,
kPremul_SkAlphaType, shared_memory_id_, shared_memory_offset_,
/*color_space_offset=*/pixels_offset, pixels_offset,
source_mailbox_.name);
EXPECT_EQ(error::kNoError,
ExecuteImmediateCmd(cmd, sizeof(source_mailbox_.name)));
ExpectProducedOnlyIfValid();
}
TEST_P(RasterDecoderOOPReadbackOrderTest, YUV) {
using Result = cmds::ReadbackARGBImagePixelsINTERNALImmediate::Result;
// 2x2 Y plane followed by 1x1 U and V planes.
const GLuint y_offset = sizeof(Result);
const GLuint u_offset = y_offset + 4;
const GLuint v_offset = invalid_shm() ? kOutOfRangeOffset : u_offset + 1;
auto& cmd = *GetImmediateAs<cmds::ReadbackYUVImagePixelsINTERNALImmediate>();
cmd.Init(/*src_x=*/0, /*src_y=*/0, /*src_width=*/2, /*src_height=*/2,
/*dst_width=*/2, /*dst_height=*/2, shared_memory_id_,
shared_memory_offset_, y_offset, /*y_stride=*/2, u_offset,
/*u_stride=*/1, v_offset, /*v_stride=*/1, source_mailbox_.name);
EXPECT_EQ(error::kNoError,
ExecuteImmediateCmd(cmd, sizeof(source_mailbox_.name)));
ExpectProducedOnlyIfValid();
}
TEST_F(RasterDecoderOOPTest,
ReadbackARGBLargeRowBytesRejectedBeforeProduceSkia) {
Mailbox source_mailbox = Mailbox::Generate();
SharedImageInfo si_info(viz::SinglePlaneFormat::kRGBA_8888, gfx::Size(4, 4),
gfx::ColorSpace::CreateSRGB(),
kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ, "TestLabel");
auto backing = std::make_unique<CountingProduceSkiaTestImageBacking>(
source_mailbox, si_info);
CountingProduceSkiaTestImageBacking* backing_ptr = backing.get();
auto source_ref =
shared_image_manager()->Register(std::move(backing), &memory_tracker_);
using Result = cmds::ReadbackARGBImagePixelsINTERNALImmediate::Result;
constexpr GLuint kPixelsOffset = sizeof(Result);
auto* result = GetSharedMemoryAs<Result*>();
for (GLuint large_row_bytes : {0x10000000u, 0x1FFFFFF0u}) {
*result = 0;
auto& cmd =
*GetImmediateAs<cmds::ReadbackARGBImagePixelsINTERNALImmediate>();
cmd.Init(/*src_x=*/0, /*src_y=*/0, /*plane_index=*/0, /*dst_width=*/2,
/*dst_height=*/2, large_row_bytes, kRGBA_8888_SkColorType,
kPremul_SkAlphaType, shared_memory_id_, shared_memory_offset_,
/*color_space_offset=*/kPixelsOffset, kPixelsOffset,
source_mailbox.name);
EXPECT_EQ(error::kNoError,
ExecuteImmediateCmd(cmd, sizeof(source_mailbox.name)));
EXPECT_EQ(0u, *result);
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
EXPECT_EQ(0, backing_ptr->produce_skia_count());
}
}
TEST_F(RasterDecoderOOPTest, CopySharedImageOddSizeMultiplanar) {
gpu::Mailbox source_mailbox = gpu::Mailbox::Generate();
SharedImageInfo source_si_info(
viz::SinglePlaneFormat::kRGBA_8888, gfx::Size(3, 3),
gfx::ColorSpace::CreateSRGB(), kTopLeft_GrSurfaceOrigin,
kPremul_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"TestLabel");
auto source_backing_unique = std::make_unique<CpuSurfaceTestImageBacking>(
source_mailbox, source_si_info);
source_backing_unique->plane_bitmap(0).eraseColor(
SkColorSetARGB(0xFF, 0xFF, 0x00, 0x00));
source_backing_unique->SetCleared();
auto source_ref = shared_image_manager()->Register(
std::move(source_backing_unique), &memory_tracker_);
gpu::Mailbox dest_mailbox = gpu::Mailbox::Generate();
SharedImageInfo dest_si_info(
viz::MultiPlaneFormat::kNV12, gfx::Size(3, 3),
gfx::ColorSpace::CreateREC709(), kTopLeft_GrSurfaceOrigin,
kOpaque_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"TestLabel");
auto dest_backing_unique =
std::make_unique<CpuSurfaceTestImageBacking>(dest_mailbox, dest_si_info);
dest_backing_unique->plane_bitmap(0).eraseColor(
SkColorSetARGB(0xFF, 0xAB, 0x00, 0x00));
dest_backing_unique->plane_bitmap(1).eraseColor(
SkColorSetARGB(0xFF, 0xAB, 0xCD, 0x00));
CpuSurfaceTestImageBacking* dest_backing = dest_backing_unique.get();
auto dest_ref = shared_image_manager()->Register(
std::move(dest_backing_unique), &memory_tracker_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto dest_repr = repr_factory.ProduceSkia(dest_mailbox, context_state_.get());
ASSERT_TRUE(dest_repr);
EXPECT_FALSE(dest_repr->IsCleared());
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_mailbox, dest_mailbox);
{
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 3, 3, 3, 3, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
}
EXPECT_TRUE(dest_repr->IsCleared());
EXPECT_EQ(dest_repr->ClearedRect(), gfx::Rect(3, 3));
const SkBitmap& uv_bitmap = dest_backing->plane_bitmap(1);
const SkPixmap uv_pixmap = uv_bitmap.pixmap();
const uint16_t expected_uv = *uv_pixmap.addr16(0, 0);
EXPECT_NE(expected_uv, 0xCDABu);
const uint8_t u = expected_uv & 0xFF;
const uint8_t v = (expected_uv >> 8) & 0xFF;
EXPECT_TRUE(u == 90 || u == 102) << "u=" << static_cast<int>(u);
EXPECT_EQ(v, 240);
for (int y = 0; y < 2; ++y) {
for (int x = 0; x < 2; ++x) {
EXPECT_EQ(*uv_pixmap.addr16(x, y), expected_uv)
<< "at (" << x << ", " << y << ")";
}
}
}
TEST_F(RasterDecoderOOPTest,
CopySharedImageOddSizeMultiplanarClearWhenSourceUnavailable) {
gpu::Mailbox source_mailbox = gpu::Mailbox::Generate();
SharedImageInfo source_si_info(
viz::SinglePlaneFormat::kRGBA_8888, gfx::Size(3, 3),
gfx::ColorSpace::CreateSRGB(), kTopLeft_GrSurfaceOrigin,
kPremul_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"TestLabel");
auto source_backing_unique = std::make_unique<CpuSurfaceTestImageBacking>(
source_mailbox, source_si_info);
source_backing_unique->set_fail_produce_skia(true);
auto source_ref = shared_image_manager()->Register(
std::move(source_backing_unique), &memory_tracker_);
gpu::Mailbox dest_mailbox = gpu::Mailbox::Generate();
SharedImageInfo dest_si_info(
viz::MultiPlaneFormat::kNV12, gfx::Size(3, 3),
gfx::ColorSpace::CreateREC709(), kTopLeft_GrSurfaceOrigin,
kOpaque_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"TestLabel");
auto dest_backing_unique =
std::make_unique<CpuSurfaceTestImageBacking>(dest_mailbox, dest_si_info);
dest_backing_unique->plane_bitmap(0).eraseColor(
SkColorSetARGB(0xFF, 0xCD, 0x00, 0x00));
dest_backing_unique->plane_bitmap(1).eraseColor(
SkColorSetARGB(0xFF, 0xCD, 0xCD, 0x00));
CpuSurfaceTestImageBacking* dest_backing = dest_backing_unique.get();
auto dest_ref = shared_image_manager()->Register(
std::move(dest_backing_unique), &memory_tracker_);
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto dest_repr = repr_factory.ProduceSkia(dest_mailbox, context_state_.get());
ASSERT_TRUE(dest_repr);
EXPECT_FALSE(dest_repr->IsCleared());
GLbyte mailboxes[sizeof(gpu::Mailbox) * 2];
CopyMailboxes(mailboxes, source_mailbox, dest_mailbox);
{
auto& cmd = *GetImmediateAs<cmds::CopySharedImageINTERNALImmediate>();
cmd.Init(0, 0, 0, 0, 3, 3, 3, 3, mailboxes);
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(mailboxes)));
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
}
EXPECT_TRUE(dest_repr->IsCleared());
EXPECT_EQ(dest_repr->ClearedRect(), gfx::Rect(3, 3));
const SkBitmap& uv_bitmap = dest_backing->plane_bitmap(1);
const SkPixmap uv_pixmap = uv_bitmap.pixmap();
constexpr uint16_t kNeutralChromaUV = 0x8080;
for (int y = 0; y < 2; ++y) {
for (int x = 0; x < 2; ++x) {
EXPECT_EQ(*uv_pixmap.addr16(x, y), kNeutralChromaUV)
<< "at (" << x << ", " << y << ")";
EXPECT_NE(*uv_pixmap.addr16(x, y), 0xCDCDu);
}
}
}
// WritePixels only supports single-plane destinations (multiplanar images are
// written with WritePixelsYUV). A multiplanar destination must produce a GL
// error rather than crash the GPU process.
TEST_F(RasterDecoderOOPTest, WritePixelsMultiplanarDestinationFails) {
gpu::Mailbox dest_mailbox = gpu::Mailbox::Generate();
SharedImageInfo dest_si_info(
viz::MultiPlaneFormat::kNV12, gfx::Size(2, 2),
gfx::ColorSpace::CreateREC709(), kTopLeft_GrSurfaceOrigin,
kOpaque_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"TestLabel");
auto dest_backing_unique =
std::make_unique<CpuSurfaceTestImageBacking>(dest_mailbox, dest_si_info);
auto dest_ref = shared_image_manager()->Register(
std::move(dest_backing_unique), &memory_tracker_);
// One byte per pixel, matching the Y plane of NV12.
constexpr GLuint kWidth = 2;
constexpr GLuint kHeight = 2;
// SAFETY: the shared memory buffer is kSharedBufferSize bytes, far larger
// than the kWidth * kHeight bytes written here.
std::ranges::fill(UNSAFE_BUFFERS(base::span(
static_cast<uint8_t*>(shared_memory_address_.get()),
kWidth * kHeight)),
0x42);
auto& cmd = *GetImmediateAs<cmds::WritePixelsINTERNALImmediate>();
cmd.Init(/*x_offset=*/0, /*y_offset=*/0, kWidth, kHeight,
/*src_row_bytes=*/kWidth, kAlpha_8_SkColorType, kPremul_SkAlphaType,
shared_memory_id_, shared_memory_offset_,
/*pixels_offset=*/0, reinterpret_cast<GLbyte*>(&dest_mailbox));
EXPECT_EQ(error::kNoError, ExecuteImmediateCmd(cmd, sizeof(dest_mailbox)));
EXPECT_EQ(GL_INVALID_OPERATION, GetGLError());
SharedImageRepresentationFactory repr_factory(shared_image_manager(),
nullptr);
auto dest_repr = repr_factory.ProduceSkia(dest_mailbox, context_state_.get());
ASSERT_TRUE(dest_repr);
EXPECT_FALSE(dest_repr->IsCleared());
}
TEST_F(RasterDecoderOOPTest, MakeCurrentAndDestroyWithGrContextTypeNone) {
gpu::GpuDriverBugWorkarounds workarounds;
scoped_refptr<gl::GLShareGroup> share_group = new gl::GLShareGroup();
scoped_refptr<gl::GLSurface> surface =
gl::init::CreateOffscreenGLSurface(display_, gfx::Size());
scoped_refptr<gl::GLContext> context = gl::init::CreateGLContext(
share_group.get(), surface.get(), gl::GLContextAttribs());
ASSERT_TRUE(context->MakeCurrent(surface.get()));
auto none_context_state = base::MakeRefCounted<SharedContextState>(
std::move(share_group), std::move(surface), std::move(context),
/*use_virtualized_gl_contexts=*/false, base::DoNothing(),
GrContextType::kNone);
ASSERT_TRUE(
none_context_state->InitializeSkia(GpuPreferences(), workarounds));
ASSERT_TRUE(none_context_state->InitializeGL(GpuPreferences(), workarounds,
gpu_feature_info_));
FakeCommandBufferServiceBase command_buffer_service;
std::unique_ptr<RasterDecoder> decoder = RasterDecoder::Create(
this, &command_buffer_service, &outputter_, gpu_feature_info_,
GpuPreferences(), /*memory_tracker=*/nullptr, &shared_image_manager_,
none_context_state, /*is_privileged=*/true);
ASSERT_EQ(decoder->Initialize(), ContextResult::kSuccess);
// Simulate another GL context becoming current on the thread before
// RasterDecoder is destroyed.
ASSERT_TRUE(context_state_->MakeCurrent(nullptr));
EXPECT_FALSE(none_context_state->IsCurrent(nullptr));
EXPECT_TRUE(decoder->MakeCurrent());
EXPECT_TRUE(none_context_state->IsCurrent(nullptr));
decoder->Destroy(/*have_context=*/true);
}
namespace {
class TestFontBufferClient : public ClientFontManager::Client {
public:
explicit TestFontBufferClient(base::span<uint8_t> buffer) : buffer_(buffer) {}
base::span<uint8_t> MapFontBuffer(uint32_t size) override {
mapped_size_ = size;
return base::span(buffer_).first(size);
}
uint32_t TakeMappedSize() { return std::exchange(mapped_size_, 0u); }
private:
base::raw_span<uint8_t> buffer_;
uint32_t mapped_size_ = 0u;
};
} // namespace
#if BUILDFLAG(IS_FUCHSIA) && defined(ARCH_CPU_ARM64) && !defined(NDEBUG)
// SwiftShader crashes when running this test on ARM64 debug builds on Fuchsia,
// see crbug.com/40194695.
#define MAYBE_DeserializesFontsWhenBeginRasterFails \
DISABLED_DeserializesFontsWhenBeginRasterFails
#else
#define MAYBE_DeserializesFontsWhenBeginRasterFails \
DeserializesFontsWhenBeginRasterFails
#endif
TEST_F(RasterDecoderOOPTest, MAYBE_DeserializesFontsWhenBeginRasterFails) {
absl::Cleanup purge_fonts = [] { SkGraphics::PurgeFontCache(); };
int32_t raster_shm_id = 0;
int32_t font_shm_id = 0;
auto raster_buf = command_buffer_service_->CreateTransferBufferHelper(
16384, &raster_shm_id);
auto font_buf =
command_buffer_service_->CreateTransferBufferHelper(16384, &font_shm_id);
TestFontBufferClient font_client(font_buf->as_byte_span());
ClientFontManager font_manager(&font_client, command_buffer_service_.get());
cc::ClientPaintCache paint_cache(std::numeric_limits<size_t>::max());
SkFont font(skia::DefaultTypeface(), 16.0f);
auto serialize_tile = [&](const char* text) {
cc::PaintOpBuffer ops;
ops.push<cc::DrawTextBlobOp>(SkTextBlob::MakeFromString(text, font), 2.0f,
20.0f, cc::PaintFlags());
const Capabilities caps = decoder_->GetCapabilities();
cc::PaintOp::SerializeOptions options;
options.paint_cache = &paint_cache;
options.strike_server = font_manager.strike_server();
options.color_space = SkColorSpace::MakeSRGB();
options.context_supports_distance_field_text =
caps.context_supports_distance_field_text;
options.max_texture_size = caps.max_texture_size;
cc::SimpleBufferSerializer serializer(raster_buf->as_byte_span(), options);
serializer.Serialize(ops);
font_manager.Serialize();
return std::pair{static_cast<uint32_t>(serializer.written()),
font_client.TakeMappedSize()};
};
auto run_tile = [&](const Mailbox& mailbox, GLint expected_begin_err,
uint32_t raster_size, uint32_t font_size,
GLint expected_raster_err) {
auto& begin = *GetImmediateAs<cmds::BeginRasterCHROMIUMImmediate>();
begin.Init(0, 0, 0, 1, /*needs_clear=*/true, 0, kNoMSAA, false, 1.0f,
mailbox.name);
EXPECT_EQ(error::kNoError,
ExecuteImmediateCmd(begin, sizeof(mailbox.name)));
EXPECT_EQ(expected_begin_err, GetGLError());
cmds::RasterCHROMIUM raster;
raster.Init(raster_shm_id, 0, raster_size, font_shm_id, 0, font_size);
EXPECT_EQ(error::kNoError, ExecuteCmd(decoder_.get(), raster));
EXPECT_EQ(expected_raster_err, GetGLError());
cmds::EndRasterCHROMIUM end;
end.Init();
EXPECT_EQ(error::kNoError, ExecuteCmd(decoder_.get(), end));
EXPECT_EQ(expected_raster_err, GetGLError());
};
int32_t handle_shm_id =
command_buffer_service_->GetNextFreeTransferBufferId();
auto [raster_size1, font_size1] = serialize_tile("A");
ASSERT_GT(font_size1, 0u);
ServiceDiscardableHandle handle(
command_buffer_service_->GetTransferBuffer(handle_shm_id), 0,
handle_shm_id);
EXPECT_TRUE(handle.IsLockedForTesting());
// Tile 1 fails BeginRasterCHROMIUM (`!sk_surface_`); its font delta must
// still be deserialized and unlocked so Tile 2's glyph delta succeeds.
run_tile(Mailbox::Generate(), GL_INVALID_VALUE, raster_size1, font_size1,
GL_INVALID_OPERATION);
EXPECT_FALSE(handle.IsLockedForTesting());
auto [raster_size2, font_size2] = serialize_tile("B");
ASSERT_GT(font_size2, 0u);
Mailbox valid_mailbox =
CreateMailbox(viz::SinglePlaneFormat::kRGBA_8888, 32, 32, false);
run_tile(valid_mailbox, GL_NO_ERROR, raster_size2, font_size2, GL_NO_ERROR);
EXPECT_FALSE(handle.IsLockedForTesting());
}
// Exercises RasterDecoderImpl::DoReadbackARGBImagePixelsINTERNAL ->
// CopySharedImageHelper::ReadPixels -> Skia Ganesh GrGLGpu::onReadPixels over a
// mock GLES 3.0 interface to verify GL_PACK_ROW_LENGTH, pitch validation, and
// single-row stride normalization.
class RasterDecoderGaneshGLReadbackTest : public testing::Test,
public DecoderClient {
public:
RasterDecoderGaneshGLReadbackTest() = default;
void SetUp() override {
gl::SetGLGetProcAddressProc(gl::MockGLInterface::GetGLProcAddress);
display_ = gl::GLSurfaceTestSupport::InitializeOneOffWithMockBindings();
ASSERT_NE(display_, nullptr);
gl_ = std::make_unique<testing::NiceMock<gl::MockGLInterface>>();
gl::MockGLInterface::SetGLInterface(gl_.get());
ON_CALL(*gl_, GetString(GL_VERSION))
.WillByDefault(Return(reinterpret_cast<const GLubyte*>(kGLVersion)));
ON_CALL(*gl_, GetString(GL_SHADING_LANGUAGE_VERSION))
.WillByDefault(Return(reinterpret_cast<const GLubyte*>(kGLSLVersion)));
ON_CALL(*gl_, GetString(GL_VENDOR))
.WillByDefault(Return(reinterpret_cast<const GLubyte*>("TestVendor")));
ON_CALL(*gl_, GetString(GL_RENDERER))
.WillByDefault(
Return(reinterpret_cast<const GLubyte*>("TestRenderer")));
ON_CALL(*gl_, GetString(GL_EXTENSIONS))
.WillByDefault(Return(reinterpret_cast<const GLubyte*>(kGLExtensions)));
ON_CALL(*gl_, GetIntegerv(GL_NUM_EXTENSIONS, _))
.WillByDefault(SetArgPointee<1>(1));
ON_CALL(*gl_, GetStringi(GL_EXTENSIONS, 0))
.WillByDefault(Return(reinterpret_cast<const GLubyte*>(kGLExtensions)));
ON_CALL(*gl_, GetIntegerv(GL_MAX_TEXTURE_SIZE, _))
.WillByDefault(SetArgPointee<1>(8192));
ON_CALL(*gl_, GetIntegerv(GL_MAX_RENDERBUFFER_SIZE, _))
.WillByDefault(SetArgPointee<1>(8192));
ON_CALL(*gl_, GetIntegerv(GL_MAX_VERTEX_ATTRIBS, _))
.WillByDefault(SetArgPointee<1>(16));
ON_CALL(*gl_, GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, _))
.WillByDefault(SetArgPointee<1>(16));
ON_CALL(*gl_, GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, _))
.WillByDefault(SetArgPointee<1>(16));
ON_CALL(*gl_,
GetInternalformativ(GL_RENDERBUFFER, _, GL_NUM_SAMPLE_COUNTS, 1, _))
.WillByDefault(SetArgPointee<4>(1));
ON_CALL(*gl_, GetInternalformativ(GL_RENDERBUFFER, _, GL_SAMPLES, 1, _))
.WillByDefault(SetArgPointee<4>(1));
ON_CALL(*gl_, CheckFramebufferStatusEXT(_))
.WillByDefault(Return(GL_FRAMEBUFFER_COMPLETE));
ON_CALL(*gl_, GenFramebuffersEXT(1, _))
.WillByDefault([this](GLsizei, GLuint* ids) { *ids = next_gl_id_++; });
ON_CALL(*gl_, GenTextures(1, _))
.WillByDefault([this](GLsizei, GLuint* ids) { *ids = next_gl_id_++; });
ON_CALL(*gl_, GetError()).WillByDefault(Return(GL_NO_ERROR));
share_group_ = base::MakeRefCounted<gl::GLShareGroup>();
surface_ = base::MakeRefCounted<gl::GLSurfaceStub>();
context_ = base::MakeRefCounted<gl::GLContextStub>(share_group_.get());
context_->SetGLVersionString(kGLVersion);
context_->SetExtensionsString(kGLExtensions);
ASSERT_TRUE(context_->Initialize(surface_.get(), {}));
ASSERT_TRUE(context_->MakeCurrent(surface_.get()));
GpuPreferences gpu_preferences;
gpu_preferences.gr_context_type = GrContextType::kGL;
GpuDriverBugWorkarounds workarounds;
GpuFeatureInfo gpu_feature_info;
context_state_ = base::MakeRefCounted<SharedContextState>(
share_group_, surface_, context_,
/*use_virtualized_gl_contexts=*/false, base::DoNothing(),
GrContextType::kGL);
ASSERT_TRUE(context_state_->InitializeGL(gpu_preferences, workarounds,
gpu_feature_info));
ASSERT_TRUE(context_state_->InitializeSkia(gpu_preferences, workarounds));
ASSERT_NE(context_state_->gr_context(), nullptr);
ASSERT_TRUE(context_state_->GrContextIsGL());
backing_factory_ = std::make_unique<GLTextureImageBackingFactory>(
gpu_preferences, workarounds, context_state_->feature_info(),
/*progress_reporter=*/nullptr, /*supports_cpu_upload=*/true);
command_buffer_service_ = std::make_unique<FakeCommandBufferServiceBase>();
decoder_ = RasterDecoder::Create(
this, command_buffer_service_.get(), &outputter_, gpu_feature_info,
gpu_preferences, /*memory_tracker=*/nullptr, &shared_image_manager_,
context_state_, /*is_priviliged=*/true);
ASSERT_EQ(decoder_->Initialize(), ContextResult::kSuccess);
ASSERT_TRUE(decoder_->MakeCurrent());
decoder_->BeginDecoding();
decoding_started_ = true;
small_buffer_ = command_buffer_service_->CreateTransferBufferHelper(
kSmallBufferSize, &shared_memory_id_);
ASSERT_NE(small_buffer_, nullptr);
}
void TearDown() override {
bool has_context =
context_ && surface_ && context_->MakeCurrent(surface_.get());
if (context_ && surface_) {
EXPECT_TRUE(has_context);
}
shared_image_ref_.reset();
backing_factory_.reset();
if (decoder_) {
if (decoding_started_ && small_buffer_) {
EXPECT_EQ(GL_NO_ERROR, GetGLError());
}
if (decoding_started_) {
decoder_->EndDecoding();
decoding_started_ = false;
}
decoder_->Destroy(
/*have_context=*/has_context && !decoder_->WasContextLost());
decoder_.reset();
}
command_buffer_service_.reset();
small_buffer_.reset();
if (context_state_) {
has_context =
context_ && surface_ && context_->MakeCurrent(surface_.get());
if (!has_context && !context_state_->context_lost()) {
context_state_->MarkContextLost();
}
context_state_.reset();
}
if (context_ && surface_ && has_context) {
context_->ReleaseCurrent(surface_.get());
}
context_.reset();
surface_.reset();
share_group_.reset();
gl::MockGLInterface::SetGLInterface(nullptr);
gl_.reset();
if (display_) {
gl::GLSurfaceTestSupport::ShutdownGL(display_);
display_ = nullptr;
}
}
// DecoderClient implementation.
void OnConsoleMessage(int32_t id, const std::string& message) override {}
void CacheBlob(gpu::GpuDiskCacheType type,
const std::string& key,
const std::string& blob) override {}
void OnFenceSyncRelease(uint64_t release) override {}
void OnDescheduleUntilFinished() override {}
void OnRescheduleAfterFinished() override {}
void ScheduleGrContextCleanup() override {}
void HandleReturnData(base::span<const uint8_t> data) override {}
protected:
static constexpr char kGLVersion[] = "OpenGL ES 3.0";
static constexpr char kGLSLVersion[] = "OpenGL ES GLSL ES 3.00";
static constexpr char kGLExtensions[] = "GL_EXT_texture_storage";
static constexpr uint32_t kSmallBufferSize = 2048;
static constexpr uint32_t kSharedMemoryOffset = 128;
Mailbox CreateClearedGLSharedImage(const gfx::Size& size) {
Mailbox mailbox = Mailbox::Generate();
SharedImageInfo si_info(
viz::SinglePlaneFormat::kRGBA_8888, size, gfx::ColorSpace::CreateSRGB(),
kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType,
SHARED_IMAGE_USAGE_RASTER_READ | SHARED_IMAGE_USAGE_RASTER_WRITE,
"ReadbackTest");
std::unique_ptr<SharedImageBacking> backing =
backing_factory_->CreateSharedImage(mailbox, si_info,
kNullSurfaceHandle,
/*is_thread_safe=*/false);
EXPECT_NE(backing, nullptr);
if (!backing) {
return Mailbox();
}
backing->SetCleared();
shared_image_ref_ =
shared_image_manager_.Register(std::move(backing), &memory_tracker_);
return mailbox;
}
error::Error ExecuteReadbackCmd(GLuint dst_width,
GLuint dst_height,
GLuint row_bytes,
SkColorType dst_color_type,
GLint shm_id,
uint32_t shm_offset,
uint32_t pixels_offset,
const Mailbox& mailbox) {
static_assert(sizeof(immediate_buffer_) >=
sizeof(cmds::ReadbackARGBImagePixelsINTERNALImmediate) +
sizeof(Mailbox::Name));
auto& cmd =
*reinterpret_cast<cmds::ReadbackARGBImagePixelsINTERNALImmediate*>(
immediate_buffer_);
cmd.Init(/*src_x=*/0, /*src_y=*/0, /*plane_index=*/0, dst_width, dst_height,
row_bytes, dst_color_type, kPremul_SkAlphaType, shm_id, shm_offset,
/*color_space_offset=*/pixels_offset, pixels_offset, mailbox.name);
int entries_processed = 0;
return decoder_->DoCommands(
1, &cmd, ComputeNumEntries(sizeof(cmd) + sizeof(mailbox.name)),
&entries_processed);
}
GLint GetGLError() {
cmds::GetError cmd;
cmd.Init(shared_memory_id_, kSharedMemoryOffset);
int entries_processed = 0;
EXPECT_EQ(error::kNoError,
decoder_->DoCommands(1, &cmd, ComputeNumEntries(sizeof(cmd)),
&entries_processed));
auto* error_ptr = static_cast<GLenum*>(
small_buffer_->GetDataAddress(kSharedMemoryOffset, sizeof(GLenum)));
EXPECT_NE(error_ptr, nullptr);
return error_ptr ? static_cast<GLint>(*error_ptr) : GL_INVALID_OPERATION;
}
std::unique_ptr<testing::NiceMock<gl::MockGLInterface>> gl_;
GLuint next_gl_id_ = 100;
scoped_refptr<gl::GLShareGroup> share_group_;
scoped_refptr<gl::GLSurfaceStub> surface_;
scoped_refptr<gl::GLContextStub> context_;
scoped_refptr<SharedContextState> context_state_;
SharedImageManager shared_image_manager_;
MemoryTypeTracker memory_tracker_{nullptr};
std::unique_ptr<GLTextureImageBackingFactory> backing_factory_;
std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image_ref_;
std::unique_ptr<FakeCommandBufferServiceBase> command_buffer_service_;
gles2::TraceOutputter outputter_;
std::unique_ptr<RasterDecoder> decoder_;
scoped_refptr<gpu::Buffer> small_buffer_;
int32_t shared_memory_id_ = 0;
bool decoding_started_ = false;
uint32_t immediate_buffer_[64] = {};
raw_ptr<gl::GLDisplay> display_ = nullptr;
};
// Verifies that sub-threshold non-tight row_bytes (< 0x10000000) programs
// GL_PACK_ROW_LENGTH in pixels and issues a single multi-row glReadPixels.
TEST_F(RasterDecoderGaneshGLReadbackTest,
ReadbackARGBSubThresholdRowBytesUsesPackRowLength) {
constexpr GLuint kDstWidth = 4;
constexpr GLuint kDstHeight = 2;
constexpr GLuint kRowPixelBytes = kDstWidth * 4;
constexpr GLuint kRowBytes = 32; // 8 pixels (< 0x10000000)
constexpr uint32_t kPixelsOffset = 32;
Mailbox mailbox =
CreateClearedGLSharedImage(gfx::Size(kDstWidth, kDstHeight));
ASSERT_FALSE(mailbox.IsZero());
using Result = cmds::ReadbackARGBImagePixelsINTERNALImmediate::Result;
auto* result =
static_cast<Result*>(small_buffer_->GetDataAddress(0, sizeof(Result)));
ASSERT_NE(result, nullptr);
*result = 0;
base::span<uint8_t> shm_span = small_buffer_->as_byte_span();
base::span<uint8_t> dst_span =
shm_span.subspan(kPixelsOffset, kRowBytes + kRowPixelBytes);
std::ranges::fill(dst_span, 0xAAu);
const std::array<uint8_t, kRowPixelBytes> kRow0Bytes = {
0x10, 0x20, 0x30, 0xFF, 0x11, 0x21, 0x31, 0xFF,
0x12, 0x22, 0x32, 0xFF, 0x13, 0x23, 0x33, 0xFF};
const std::array<uint8_t, kRowPixelBytes> kRow1Bytes = {
0x40, 0x50, 0x60, 0xFF, 0x41, 0x51, 0x61, 0xFF,
0x42, 0x52, 0x62, 0xFF, 0x43, 0x53, 0x63, 0xFF};
EXPECT_CALL(*gl_, PixelStorei(testing::Ne(GL_PACK_ROW_LENGTH), _))
.Times(testing::AnyNumber());
{
testing::InSequence seq;
EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ROW_LENGTH, 0))
.Times(testing::AnyNumber());
EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ROW_LENGTH, 8));
EXPECT_CALL(*gl_, ReadPixels(0, 0, kDstWidth, kDstHeight, GL_RGBA,
GL_UNSIGNED_BYTE, dst_span.data()))
.WillOnce([&](GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) {
dst_span.first(kRowPixelBytes).copy_from(kRow0Bytes);
dst_span.subspan(kRowBytes, kRowPixelBytes).copy_from(kRow1Bytes);
});
EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ROW_LENGTH, 0));
}
EXPECT_EQ(error::kNoError,
ExecuteReadbackCmd(kDstWidth, kDstHeight, kRowBytes,
kRGBA_8888_SkColorType, shared_memory_id_,
/*shm_offset=*/0, kPixelsOffset, mailbox));
EXPECT_EQ(1u, *result);
EXPECT_EQ(GL_NO_ERROR, GetGLError());
EXPECT_EQ(dst_span.first(kRowPixelBytes), base::span(kRow0Bytes));
for (uint8_t pad_byte :
dst_span.subspan(kRowPixelBytes, kRowBytes - kRowPixelBytes)) {
EXPECT_EQ(0xAAu, pad_byte);
}
EXPECT_EQ(dst_span.subspan(kRowBytes, kRowPixelBytes),
base::span(kRow1Bytes));
}
// Verifies that row_bytes >= 0x10000000 and SkImageInfo::computeByteSize
// overflows (including > SK_MaxS32 and 32-bit size_t wraparound) are rejected
// with GL_INVALID_VALUE without calling glReadPixels.
TEST_F(RasterDecoderGaneshGLReadbackTest,
ReadbackARGBRejectsLargeRowBytesAndByteSizeOverflow) {
constexpr GLuint kDstWidth = 4;
constexpr uint32_t kPixelsOffset = 32;
Mailbox mailbox = CreateClearedGLSharedImage(gfx::Size(kDstWidth, 17));
ASSERT_FALSE(mailbox.IsZero());
using Result = cmds::ReadbackARGBImagePixelsINTERNALImmediate::Result;
auto* result =
static_cast<Result*>(small_buffer_->GetDataAddress(0, sizeof(Result)));
ASSERT_NE(result, nullptr);
struct Case {
GLuint dst_height;
GLuint row_bytes;
};
constexpr std::array<Case, 7> kCases = {{
{.dst_height = 2, .row_bytes = 0x10000000u},
{.dst_height = 1, .row_bytes = 0x10000000u},
{.dst_height = 2, .row_bytes = 0x1FFFFFF0u},
{.dst_height = 1, .row_bytes = 0x80000000u},
{.dst_height = 2, .row_bytes = 0x80000000u},
// Sub-threshold row_bytes where computeByteSize exceeds SK_MaxS32
// (returns SIZE_MAX, caught via SkImageInfo::ByteSizeOverflowed).
{.dst_height = 10, .row_bytes = 0x0FFFFFFCu},
{.dst_height = 17, .row_bytes = 0x0FFFFFFCu},
}};
EXPECT_CALL(*gl_, ReadPixels(_, _, _, _, _, _, _)).Times(0);
for (const auto& test_case : kCases) {
*result = 0;
EXPECT_EQ(
error::kNoError,
ExecuteReadbackCmd(kDstWidth, test_case.dst_height, test_case.row_bytes,
kRGBA_8888_SkColorType, shared_memory_id_,
/*shm_offset=*/0, kPixelsOffset, mailbox));
EXPECT_EQ(0u, *result);
EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
}
}
// Verifies that single-row readbacks with a sub-threshold large row_bytes
// (0x0FFFFFFCu) normalize the unused inter-row pitch to minRowBytes(), never
// setting a non-zero GL_PACK_ROW_LENGTH for either direct or format-converted
// readbacks.
TEST_F(RasterDecoderGaneshGLReadbackTest,
ReadbackARGBSingleRowNormalizesSubThresholdPitch) {
constexpr GLuint kDstWidth = 4;
constexpr GLuint kSubThresholdLargeRowBytes = 0x0FFFFFFCu;
constexpr uint32_t kPixelsOffset = 32;
Mailbox mailbox = CreateClearedGLSharedImage(gfx::Size(kDstWidth, 2));
ASSERT_FALSE(mailbox.IsZero());
using Result = cmds::ReadbackARGBImagePixelsINTERNALImmediate::Result;
auto* result =
static_cast<Result*>(small_buffer_->GetDataAddress(0, sizeof(Result)));
ASSERT_NE(result, nullptr);
// 1. Direct single-row RGBA8 readback with row_bytes = 0x0FFFFFFCu.
{
constexpr GLuint kRowPixelBytes = kDstWidth * 4;
*result = 0;
base::span<uint8_t> row0_span =
small_buffer_->as_byte_span().subspan(kPixelsOffset, kRowPixelBytes);
std::ranges::fill(row0_span, 0u);
const std::array<uint8_t, kRowPixelBytes> kRow0Bytes = {
0xAA, 0xBB, 0xCC, 0xED, 0xDD, 0xEE, 0x11, 0xEC,
0x22, 0x33, 0x44, 0xEB, 0x55, 0x66, 0x77, 0xEA};
EXPECT_CALL(*gl_, PixelStorei(_, _)).Times(testing::AnyNumber());
EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ROW_LENGTH, testing::Ne(0))).Times(0);
EXPECT_CALL(*gl_, ReadPixels(0, 0, kDstWidth, 1, GL_RGBA, GL_UNSIGNED_BYTE,
row0_span.data()))
.WillOnce([&](GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) {
row0_span.copy_from(kRow0Bytes);
});
EXPECT_EQ(error::kNoError,
ExecuteReadbackCmd(kDstWidth, /*dst_height=*/1,
kSubThresholdLargeRowBytes,
kRGBA_8888_SkColorType, shared_memory_id_,
/*shm_offset=*/0, kPixelsOffset, mailbox));
EXPECT_EQ(1u, *result);
EXPECT_EQ(GL_NO_ERROR, GetGLError());
EXPECT_EQ(row0_span, base::span(kRow0Bytes));
testing::Mock::VerifyAndClearExpectations(gl_.get());
}
// 2. Converted single-row Alpha8 readback with row_bytes = 0x0FFFFFFCu.
{
constexpr GLuint kSrcRowBytes = kDstWidth * 4;
*result = 0;
base::span<uint8_t> alpha_span =
small_buffer_->as_byte_span().subspan(kPixelsOffset, kDstWidth);
std::ranges::fill(alpha_span, 0u);
const std::array<uint8_t, kSrcRowBytes> kSrcRgbaRow = {
0x10, 0x20, 0x30, 0xA1, 0x10, 0x20, 0x30, 0xB2,
0x10, 0x20, 0x30, 0xC3, 0x10, 0x20, 0x30, 0xD4};
EXPECT_CALL(*gl_, PixelStorei(_, _)).Times(testing::AnyNumber());
EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ROW_LENGTH, testing::Ne(0))).Times(0);
EXPECT_CALL(*gl_,
ReadPixels(0, 0, kDstWidth, 1, GL_RGBA, GL_UNSIGNED_BYTE, _))
.WillOnce([&](GLint, GLint, GLsizei, GLsizei, GLenum, GLenum,
void* dst) {
// SAFETY: Skia allocates a `kDstWidth * 4`-byte staging buffer.
UNSAFE_BUFFERS(base::span(static_cast<uint8_t*>(dst), kSrcRowBytes))
.copy_from(kSrcRgbaRow);
});
EXPECT_EQ(error::kNoError,
ExecuteReadbackCmd(kDstWidth, /*dst_height=*/1,
kSubThresholdLargeRowBytes,
kAlpha_8_SkColorType, shared_memory_id_,
/*shm_offset=*/0, kPixelsOffset, mailbox));
EXPECT_EQ(1u, *result);
EXPECT_EQ(GL_NO_ERROR, GetGLError());
const std::array<uint8_t, kDstWidth> kExpectedAlpha = {0xA1, 0xB2, 0xC3,
0xD4};
EXPECT_EQ(alpha_span, base::span(kExpectedAlpha));
testing::Mock::VerifyAndClearExpectations(gl_.get());
}
}
} // namespace raster
} // namespace gpu