summaryrefslogtreecommitdiffstats
path: root/gpu/perftests/texture_upload_perftest.cc
blob: f691c9e76d91f1b744f2609309ba91266e15f8b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright 2015 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 <algorithm>
#include <vector>

#include "base/containers/small_map.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "gpu/perftests/measurements.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_surface.h"
#include "ui/gl/scoped_make_current.h"

namespace gpu {
namespace {

const int kUploadPerfWarmupRuns = 10;
const int kUploadPerfTestRuns = 100;

#define SHADER(Src) #Src

// clang-format off
const char kVertexShader[] =
SHADER(
  attribute vec2 a_position;
  varying vec2 v_texCoord;
  void main() {
    gl_Position = vec4(a_position.x, a_position.y, 0.0, 1.0);
    v_texCoord = vec2((a_position.x + 1) * 0.5, (a_position.y + 1) * 0.5);
  }
);
const char kFragmentShader[] =
SHADER(
  uniform sampler2D a_texture;
  varying vec2 v_texCoord;
  void main() {
    gl_FragColor = texture2D(a_texture, v_texCoord.xy);
  }
);
// clang-format on

void CheckNoGlError() {
  CHECK_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError());
}

// Utility function to compile a shader from a string.
GLuint LoadShader(const GLenum type, const char* const src) {
  GLuint shader = 0;
  shader = glCreateShader(type);
  CHECK_NE(0u, shader);
  glShaderSource(shader, 1, &src, NULL);
  glCompileShader(shader);

  GLint compiled = 0;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  if (compiled == 0) {
    GLint len = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
    if (len > 1) {
      scoped_ptr<char> error_log(new char[len]);
      glGetShaderInfoLog(shader, len, NULL, error_log.get());
      LOG(ERROR) << "Error compiling shader: " << error_log.get();
    }
  }
  CHECK_NE(0, compiled);
  return shader;
}

void GenerateTextureData(const gfx::Size& size,
                         const int seed,
                         std::vector<uint8>* const pixels) {
  pixels->resize(size.GetArea() * 4);
  for (int y = 0; y < size.height(); ++y) {
    for (int x = 0; x < size.width(); ++x) {
      const size_t offset = (y * size.width() + x) * 4;
      pixels->at(offset) = (y + seed) % 256;
      pixels->at(offset + 1) = (x + seed) % 256;
      pixels->at(offset + 2) = (y + x + seed) % 256;
      pixels->at(offset + 3) = 255;
    }
  }
}

// PerfTest to check costs of texture upload at different stages
// on different platforms.
class TextureUploadPerfTest : public testing::Test {
 public:
  TextureUploadPerfTest() : size_(512, 512) {}

  // Overridden from testing::Test
  void SetUp() override {
    // Initialize an offscreen surface and a gl context.
    gfx::GLSurface::InitializeOneOff();
    surface_ = gfx::GLSurface::CreateOffscreenGLSurface(size_);
    gl_context_ = gfx::GLContext::CreateGLContext(NULL,  // share_group
                                                  surface_.get(),
                                                  gfx::PreferIntegratedGpu);

    ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());
    if (gpu_timing_.Initialize(gl_context_.get())) {
      LOG(INFO) << "Gpu timing initialized with timer type: "
                << gpu_timing_.GetTimerTypeName();
      gpu_timing_.CheckAndResetTimerErrors();
      gpu_timing_.InvalidateTimerOffset();
    } else {
      LOG(WARNING) << "Can't initialize gpu timing";
    }

    // Prepare a simple program and a vertex buffer that will be
    // used to draw a quad on the offscreen surface.
    vertex_shader_ = LoadShader(GL_VERTEX_SHADER, kVertexShader);
    fragment_shader_ = LoadShader(GL_FRAGMENT_SHADER, kFragmentShader);
    program_object_ = glCreateProgram();
    CHECK_NE(0u, program_object_);

    glAttachShader(program_object_, vertex_shader_);
    glAttachShader(program_object_, fragment_shader_);
    glBindAttribLocation(program_object_, 0, "a_position");
    glLinkProgram(program_object_);

    GLint linked = -1;
    glGetProgramiv(program_object_, GL_LINK_STATUS, &linked);
    CHECK_NE(0, linked);

    sampler_location_ = glGetUniformLocation(program_object_, "a_texture");
    CHECK_NE(-1, sampler_location_);

    glGenBuffersARB(1, &vertex_buffer_);
    CHECK_NE(0u, vertex_buffer_);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
    static GLfloat positions[] = {
        -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
    CheckNoGlError();
  }

  void TearDown() override {
    ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());
    if (program_object_ != 0) {
      glDeleteProgram(program_object_);
    }
    if (vertex_shader_ != 0) {
      glDeleteShader(vertex_shader_);
    }
    if (fragment_shader_ != 0) {
      glDeleteShader(fragment_shader_);
    }
    if (vertex_buffer_ != 0) {
      glDeleteShader(vertex_buffer_);
    }

    gl_context_ = nullptr;
    surface_ = nullptr;
  }

 protected:
  // Upload and draw on the offscren surface.
  // Return a list of pair. Each pair describe a gl operation and the wall
  // time elapsed in milliseconds.
  std::vector<Measurement> UploadAndDraw(const std::vector<uint8>& pixels,
                                         const GLenum format,
                                         const GLenum type) {
    ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());

    MeasurementTimers total_timers(&gpu_timing_);
    GLuint texture_id = 0;

    MeasurementTimers tex_timers(&gpu_timing_);
    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1, &texture_id);
    glBindTexture(GL_TEXTURE_2D, texture_id);

    glTexImage2D(GL_TEXTURE_2D, 0, format, size_.width(), size_.height(), 0,
                 format, type, &pixels[0]);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    CheckNoGlError();
    tex_timers.Record();

    MeasurementTimers draw_timers(&gpu_timing_);
    glUseProgram(program_object_);
    glUniform1i(sampler_location_, 0);

    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(0);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    draw_timers.Record();

    MeasurementTimers finish_timers(&gpu_timing_);
    glFinish();
    CheckNoGlError();
    finish_timers.Record();
    total_timers.Record();

    glDeleteTextures(1, &texture_id);

    std::vector<uint8> pixels_rendered(size_.GetArea() * 4);
    glReadPixels(0, 0, size_.width(), size_.height(), GL_RGBA, type,
                 &pixels_rendered[0]);
    CheckNoGlError();

    // TODO(dcastagna): don't assume the format of the texture and do
    // the appropriate format conversion.
    EXPECT_EQ(static_cast<GLenum>(GL_RGBA), format);
    EXPECT_EQ(pixels, pixels_rendered);

    std::vector<Measurement> measurements;
    measurements.push_back(total_timers.GetAsMeasurement("total"));
    measurements.push_back(tex_timers.GetAsMeasurement("teximage2d"));
    measurements.push_back(draw_timers.GetAsMeasurement("drawarrays"));
    measurements.push_back(finish_timers.GetAsMeasurement("finish"));
    return measurements;
  }

  const gfx::Size size_;  // for the offscreen surface and the texture
  scoped_refptr<gfx::GLContext> gl_context_;
  scoped_refptr<gfx::GLSurface> surface_;
  GPUTiming gpu_timing_;

  GLuint vertex_shader_ = 0;
  GLuint fragment_shader_ = 0;
  GLuint program_object_ = 0;
  GLint sampler_location_ = -1;
  GLuint vertex_buffer_ = 0;
};

// Perf test that generates, uploads and draws a texture on a surface repeatedly
// and prints out aggregated measurements for all the runs.
TEST_F(TextureUploadPerfTest, glTexImage2d) {
  std::vector<uint8> pixels;
  base::SmallMap<std::map<std::string, Measurement>>
      aggregates;  // indexed by name
  for (int i = 0; i < kUploadPerfWarmupRuns + kUploadPerfTestRuns; ++i) {
    GenerateTextureData(size_, i + 1, &pixels);
    auto run = UploadAndDraw(pixels, GL_RGBA, GL_UNSIGNED_BYTE);
    if (i >= kUploadPerfWarmupRuns) {
      for (const Measurement& m : run) {
        auto& agg = aggregates[m.name];
        agg.name = m.name;
        agg.Increment(m);
      }
    }
  }

  for (const auto& entry : aggregates) {
    const auto m = entry.second.Divide(kUploadPerfTestRuns);
    m.PrintResult();
  }
}

}  // namespace
}  // namespace gpu