summaryrefslogtreecommitdiff
path: root/chromium/components/exo/buffer.cc
blob: d279d94b8630b15a30eaa97824467ddf234fd7d9 (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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// 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 "components/exo/buffer.h"

#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2extchromium.h>
#include <stdint.h>
#include <algorithm>
#include <utility>

#include "base/callback_helpers.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_event_argument.h"
#include "cc/output/context_provider.h"
#include "cc/resources/single_release_callback.h"
#include "cc/resources/texture_mailbox.h"
#include "gpu/command_buffer/client/context_support.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "ui/aura/env.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/gpu_memory_buffer.h"

namespace exo {
namespace {

// The amount of time before we wait for release queries using
// GetQueryObjectuivEXT(GL_QUERY_RESULT_EXT).
const int kWaitForReleaseDelayMs = 500;

GLenum GLInternalFormat(gfx::BufferFormat format) {
  const GLenum kGLInternalFormats[] = {
      GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD,  // ATC
      GL_COMPRESSED_RGB_S3TC_DXT1_EXT,     // ATCIA
      GL_COMPRESSED_RGB_S3TC_DXT1_EXT,     // DXT1
      GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,    // DXT5
      GL_ETC1_RGB8_OES,                    // ETC1
      GL_R8_EXT,                           // R_8
      GL_RGBA,                             // RGBA_4444
      GL_RGB,                              // RGBX_8888
      GL_RGBA,                             // RGBA_8888
      GL_RGB,                              // BGRX_8888
      GL_BGRA_EXT,                         // BGRA_8888
      GL_RGB_YUV_420_CHROMIUM,             // YUV_420
      GL_INVALID_ENUM,                     // YUV_420_BIPLANAR
      GL_RGB_YCBCR_422_CHROMIUM,           // UYVY_422
  };
  static_assert(arraysize(kGLInternalFormats) ==
                    (static_cast<int>(gfx::BufferFormat::LAST) + 1),
                "BufferFormat::LAST must be last value of kGLInternalFormats");

  DCHECK(format <= gfx::BufferFormat::LAST);
  return kGLInternalFormats[static_cast<int>(format)];
}

unsigned CreateGLTexture(gpu::gles2::GLES2Interface* gles2, GLenum target) {
  unsigned texture_id = 0;
  gles2->GenTextures(1, &texture_id);
  gles2->ActiveTexture(GL_TEXTURE0);
  gles2->BindTexture(target, texture_id);
  gles2->TexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  gles2->TexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  gles2->TexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  gles2->TexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  return texture_id;
}

void CreateGLTextureMailbox(gpu::gles2::GLES2Interface* gles2,
                            unsigned texture_id,
                            GLenum target,
                            gpu::Mailbox* mailbox) {
  gles2->ActiveTexture(GL_TEXTURE0);
  gles2->BindTexture(target, texture_id);
  gles2->GenMailboxCHROMIUM(mailbox->name);
  gles2->ProduceTextureCHROMIUM(target, mailbox->name);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// Buffer::Texture

// Encapsulates the state and logic needed to bind a buffer to a GLES2 texture.
class Buffer::Texture {
 public:
  explicit Texture(cc::ContextProvider* context_provider);
  Texture(cc::ContextProvider* context_provider,
          gfx::GpuMemoryBuffer* gpu_memory_buffer,
          unsigned texture_target,
          unsigned query_type);
  ~Texture();

  // Returns true if GLES2 resources for texture have been lost.
  bool IsLost();

  // Allow texture to be reused after |sync_token| has passed and runs
  // |callback|.
  void Release(const base::Closure& callback,
               const gpu::SyncToken& sync_token,
               bool is_lost);

  // Binds the contents referenced by |image_id_| to the texture returned by
  // mailbox(). Returns a sync token that can be used when accessing texture
  // from a different context.
  gpu::SyncToken BindTexImage();

  // Releases the contents referenced by |image_id_| after |sync_token| has
  // passed and runs |callback| when completed.
  void ReleaseTexImage(const base::Closure& callback,
                       const gpu::SyncToken& sync_token,
                       bool is_lost);

  // Copy the contents of texture to |destination| and runs |callback| when
  // completed. Returns a sync token that can be used when accessing texture
  // from a different context.
  gpu::SyncToken CopyTexImage(Texture* destination,
                              const base::Closure& callback);

  // Returns the mailbox for this texture.
  gpu::Mailbox mailbox() const { return mailbox_; }

 private:
  void ReleaseWhenQueryResultIsAvailable(const base::Closure& callback);
  void Released();
  void ScheduleWaitForRelease(base::TimeDelta delay);
  void WaitForRelease();

  scoped_refptr<cc::ContextProvider> context_provider_;
  const unsigned texture_target_;
  const unsigned query_type_;
  const GLenum internalformat_;
  unsigned image_id_;
  unsigned query_id_;
  unsigned texture_id_;
  gpu::Mailbox mailbox_;
  base::Closure release_callback_;
  base::TimeTicks wait_for_release_time_;
  bool wait_for_release_pending_;
  base::WeakPtrFactory<Texture> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(Texture);
};

Buffer::Texture::Texture(cc::ContextProvider* context_provider)
    : context_provider_(context_provider),
      texture_target_(GL_TEXTURE_2D),
      query_type_(GL_COMMANDS_COMPLETED_CHROMIUM),
      internalformat_(GL_RGBA),
      image_id_(0),
      query_id_(0),
      texture_id_(0),
      wait_for_release_pending_(false),
      weak_ptr_factory_(this) {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  texture_id_ = CreateGLTexture(gles2, texture_target_);
  // Generate a crypto-secure random mailbox name.
  CreateGLTextureMailbox(gles2, texture_id_, texture_target_, &mailbox_);
}

Buffer::Texture::Texture(cc::ContextProvider* context_provider,
                         gfx::GpuMemoryBuffer* gpu_memory_buffer,
                         unsigned texture_target,
                         unsigned query_type)
    : context_provider_(context_provider),
      texture_target_(texture_target),
      query_type_(query_type),
      internalformat_(GLInternalFormat(gpu_memory_buffer->GetFormat())),
      image_id_(0),
      query_id_(0),
      texture_id_(0),
      wait_for_release_pending_(false),
      weak_ptr_factory_(this) {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  gfx::Size size = gpu_memory_buffer->GetSize();
  image_id_ =
      gles2->CreateImageCHROMIUM(gpu_memory_buffer->AsClientBuffer(),
                                 size.width(), size.height(), internalformat_);
  gles2->GenQueriesEXT(1, &query_id_);
  texture_id_ = CreateGLTexture(gles2, texture_target_);
}

Buffer::Texture::~Texture() {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  gles2->DeleteTextures(1, &texture_id_);
  if (query_id_)
    gles2->DeleteQueriesEXT(1, &query_id_);
  if (image_id_)
    gles2->DestroyImageCHROMIUM(image_id_);
}

bool Buffer::Texture::IsLost() {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  return gles2->GetGraphicsResetStatusKHR() != GL_NO_ERROR;
}

void Buffer::Texture::Release(const base::Closure& callback,
                              const gpu::SyncToken& sync_token,
                              bool is_lost) {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  if (sync_token.HasData())
    gles2->WaitSyncTokenCHROMIUM(sync_token.GetConstData());

  // Run callback as texture can be reused immediately after waiting for sync
  // token.
  callback.Run();
}

gpu::SyncToken Buffer::Texture::BindTexImage() {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  gles2->ActiveTexture(GL_TEXTURE0);
  gles2->BindTexture(texture_target_, texture_id_);
  DCHECK_NE(image_id_, 0u);
  gles2->BindTexImage2DCHROMIUM(texture_target_, image_id_);
  // Generate a crypto-secure random mailbox name if not already done.
  if (mailbox_.IsZero())
    CreateGLTextureMailbox(gles2, texture_id_, texture_target_, &mailbox_);
  // Create and return a sync token that can be used to ensure that the
  // BindTexImage2DCHROMIUM call is processed before issuing any commands
  // that will read from the texture on a different context.
  uint64_t fence_sync = gles2->InsertFenceSyncCHROMIUM();
  gles2->OrderingBarrierCHROMIUM();
  gpu::SyncToken sync_token;
  gles2->GenUnverifiedSyncTokenCHROMIUM(fence_sync, sync_token.GetData());
  return sync_token;
}

void Buffer::Texture::ReleaseTexImage(const base::Closure& callback,
                                      const gpu::SyncToken& sync_token,
                                      bool is_lost) {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  if (sync_token.HasData())
    gles2->WaitSyncTokenCHROMIUM(sync_token.GetConstData());
  gles2->ActiveTexture(GL_TEXTURE0);
  gles2->BindTexture(texture_target_, texture_id_);
  DCHECK_NE(query_id_, 0u);
  gles2->BeginQueryEXT(query_type_, query_id_);
  gles2->ReleaseTexImage2DCHROMIUM(texture_target_, image_id_);
  gles2->EndQueryEXT(query_type_);
  // Run callback when query result is available and ReleaseTexImage has been
  // handled if sync token has data and buffer has been used. If buffer was
  // never used then run the callback immediately.
  if (sync_token.HasData()) {
    ReleaseWhenQueryResultIsAvailable(callback);
  } else {
    callback.Run();
  }
}

gpu::SyncToken Buffer::Texture::CopyTexImage(Texture* destination,
                                             const base::Closure& callback) {
  gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
  gles2->ActiveTexture(GL_TEXTURE0);
  gles2->BindTexture(texture_target_, texture_id_);
  DCHECK_NE(image_id_, 0u);
  gles2->BindTexImage2DCHROMIUM(texture_target_, image_id_);
  gles2->CopyTextureCHROMIUM(texture_id_, destination->texture_id_,
                             internalformat_, GL_UNSIGNED_BYTE, false, false,
                             false);
  DCHECK_NE(query_id_, 0u);
  gles2->BeginQueryEXT(query_type_, query_id_);
  gles2->ReleaseTexImage2DCHROMIUM(texture_target_, image_id_);
  gles2->EndQueryEXT(query_type_);
  // Run callback when query result is available and ReleaseTexImage has been
  // handled.
  ReleaseWhenQueryResultIsAvailable(callback);
  // Create and return a sync token that can be used to ensure that the
  // CopyTextureCHROMIUM call is processed before issuing any commands
  // that will read from the target texture on a different context.
  uint64_t fence_sync = gles2->InsertFenceSyncCHROMIUM();
  gles2->OrderingBarrierCHROMIUM();
  gpu::SyncToken sync_token;
  gles2->GenUnverifiedSyncTokenCHROMIUM(fence_sync, sync_token.GetData());
  return sync_token;
}

void Buffer::Texture::ReleaseWhenQueryResultIsAvailable(
    const base::Closure& callback) {
  DCHECK(release_callback_.is_null());
  release_callback_ = callback;
  base::TimeDelta wait_for_release_delay =
      base::TimeDelta::FromMilliseconds(kWaitForReleaseDelayMs);
  wait_for_release_time_ = base::TimeTicks::Now() + wait_for_release_delay;
  ScheduleWaitForRelease(wait_for_release_delay);
  context_provider_->ContextSupport()->SignalQuery(
      query_id_,
      base::Bind(&Buffer::Texture::Released, weak_ptr_factory_.GetWeakPtr()));
}

void Buffer::Texture::Released() {
  if (!release_callback_.is_null())
    base::ResetAndReturn(&release_callback_).Run();
}

void Buffer::Texture::ScheduleWaitForRelease(base::TimeDelta delay) {
  if (wait_for_release_pending_)
    return;

  wait_for_release_pending_ = true;
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE, base::Bind(&Buffer::Texture::WaitForRelease,
                            weak_ptr_factory_.GetWeakPtr()),
      delay);
}

void Buffer::Texture::WaitForRelease() {
  DCHECK(wait_for_release_pending_);
  wait_for_release_pending_ = false;

  if (release_callback_.is_null())
    return;

  base::TimeTicks current_time = base::TimeTicks::Now();
  if (current_time < wait_for_release_time_) {
    ScheduleWaitForRelease(wait_for_release_time_ - current_time);
    return;
  }

  base::Closure callback = base::ResetAndReturn(&release_callback_);

  {
    TRACE_EVENT0("exo", "Buffer::Texture::WaitForQueryResult");

    // We need to wait for the result to be available. Getting the result of
    // the query implies waiting for it to become available. The actual result
    // is unimportant and also not well defined.
    unsigned result = 0;
    gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
    gles2->GetQueryObjectuivEXT(query_id_, GL_QUERY_RESULT_EXT, &result);
  }

  callback.Run();
}

////////////////////////////////////////////////////////////////////////////////
// Buffer, public:

Buffer::Buffer(scoped_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer)
    : gpu_memory_buffer_(std::move(gpu_memory_buffer)),
      texture_target_(GL_TEXTURE_2D),
      query_type_(GL_COMMANDS_COMPLETED_CHROMIUM),
      use_zero_copy_(true),
      is_overlay_candidate_(false),
      use_count_(0) {}

Buffer::Buffer(scoped_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer,
               unsigned texture_target,
               unsigned query_type,
               bool use_zero_copy,
               bool is_overlay_candidate)
    : gpu_memory_buffer_(std::move(gpu_memory_buffer)),
      texture_target_(texture_target),
      query_type_(query_type),
      use_zero_copy_(use_zero_copy),
      is_overlay_candidate_(is_overlay_candidate),
      use_count_(0) {}

Buffer::~Buffer() {}

scoped_ptr<cc::SingleReleaseCallback> Buffer::ProduceTextureMailbox(
    cc::TextureMailbox* texture_mailbox,
    bool secure_output_only,
    bool lost_context) {
  DLOG_IF(WARNING, use_count_)
      << "Producing a texture mailbox for a buffer that has not been released";

  // Some clients think that they can reuse a buffer before it's released by
  // performing a fast blit into the buffer. This behavior is bad as it prevents
  // the client from knowing when the buffer is actually released (e.g. the
  // release notification for the previous use of buffer can arrive after the
  // buffer has been reused). We stop running the release callback when this
  // type of behavior is detected as having the buffer always be busy will
  // result in fewer drawing artifacts.
  if (use_count_ && !lost_context)
    release_callback_.Reset();

  // Increment the use count for this buffer.
  ++use_count_;

  // If textures are lost, destroy them to ensure that we create new ones below.
  if (contents_texture_ && contents_texture_->IsLost())
    contents_texture_.reset();
  if (texture_ && texture_->IsLost())
    texture_.reset();

  // Note: This can fail if GPU acceleration has been disabled.
  scoped_refptr<cc::ContextProvider> context_provider =
      aura::Env::GetInstance()
          ->context_factory()
          ->SharedMainThreadContextProvider();
  if (!context_provider) {
    DLOG(WARNING) << "Failed to acquire a context provider";
    Release();  // Decrements the use count
    return nullptr;
  }

  // Create a new image texture for |gpu_memory_buffer_| with |texture_target_|
  // if one doesn't already exist. The contents of this buffer are copied to
  // |texture| using a call to CopyTexImage.
  if (!contents_texture_) {
    contents_texture_ = make_scoped_ptr(
        new Texture(context_provider.get(), gpu_memory_buffer_.get(),
                    texture_target_, query_type_));
  }

  if (use_zero_copy_) {
    // Zero-copy means using the contents texture directly.
    Texture* texture = contents_texture_.get();

    // This binds the latest contents of this buffer to |texture|.
    gpu::SyncToken sync_token = texture->BindTexImage();

    *texture_mailbox =
        cc::TextureMailbox(texture->mailbox(), sync_token, texture_target_,
                           gpu_memory_buffer_->GetSize(), is_overlay_candidate_,
                           secure_output_only);
    // The contents texture will be released when no longer used by the
    // compositor.
    return cc::SingleReleaseCallback::Create(
        base::Bind(&Buffer::Texture::ReleaseTexImage, base::Unretained(texture),
                   base::Bind(&Buffer::ReleaseContentsTexture, AsWeakPtr(),
                              base::Passed(&contents_texture_))));
  }

  // Create a mailbox texture that we copy the buffer contents to.
  if (!texture_)
    texture_ = make_scoped_ptr(new Texture(context_provider.get()));

  // Copy the contents of |contents_texture| to |texture| and produce a
  // texture mailbox from the result in |texture|.
  Texture* contents_texture = contents_texture_.get();
  Texture* texture = texture_.get();

  // The contents texture will be released when copy has completed.
  gpu::SyncToken sync_token = contents_texture->CopyTexImage(
      texture, base::Bind(&Buffer::ReleaseContentsTexture, AsWeakPtr(),
                          base::Passed(&contents_texture_)));
  *texture_mailbox =
      cc::TextureMailbox(texture->mailbox(), sync_token, GL_TEXTURE_2D,
                         gpu_memory_buffer_->GetSize(),
                         false /* is_overlay_candidate */, secure_output_only);
  // The mailbox texture will be released when no longer used by the
  // compositor.
  return cc::SingleReleaseCallback::Create(
      base::Bind(&Buffer::Texture::Release, base::Unretained(texture),
                 base::Bind(&Buffer::ReleaseTexture, AsWeakPtr(),
                            base::Passed(&texture_))));
}

gfx::Size Buffer::GetSize() const {
  return gpu_memory_buffer_->GetSize();
}

scoped_ptr<base::trace_event::TracedValue> Buffer::AsTracedValue() const {
  scoped_ptr<base::trace_event::TracedValue> value(
      new base::trace_event::TracedValue());
  gfx::Size size = gpu_memory_buffer_->GetSize();
  value->SetInteger("width", size.width());
  value->SetInteger("height", size.height());
  value->SetInteger("format",
                    static_cast<int>(gpu_memory_buffer_->GetFormat()));
  return value;
}

////////////////////////////////////////////////////////////////////////////////
// Buffer, private:

void Buffer::Release() {
  DCHECK_GT(use_count_, 0u);
  if (--use_count_)
    return;

  // Run release callback to notify the client that buffer has been released.
  if (!release_callback_.is_null())
    release_callback_.Run();
}

void Buffer::ReleaseTexture(scoped_ptr<Texture> texture) {
  texture_ = std::move(texture);
}

void Buffer::ReleaseContentsTexture(scoped_ptr<Texture> texture) {
  TRACE_EVENT0("exo", "Buffer::ReleaseContentsTexture");

  contents_texture_ = std::move(texture);
  Release();
}

}  // namespace exo