1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "content/common/gpu/gpu_memory_buffer_factory.h"
6
7#include "base/logging.h"
8#include "content/common/gpu/gpu_memory_buffer_factory_io_surface.h"
9#include "ui/gl/gl_image.h"
10#include "ui/gl/gl_image_shared_memory.h"
11
12namespace content {
13namespace {
14
15class GpuMemoryBufferFactoryImpl : public GpuMemoryBufferFactory {
16 public:
17  // Overridden from GpuMemoryBufferFactory:
18  virtual gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer(
19      const gfx::GpuMemoryBufferHandle& handle,
20      const gfx::Size& size,
21      unsigned internalformat,
22      unsigned usage) OVERRIDE {
23    switch (handle.type) {
24      case gfx::IO_SURFACE_BUFFER:
25        return io_surface_factory_.CreateGpuMemoryBuffer(
26            handle.global_id, size, internalformat);
27      default:
28        NOTREACHED();
29        return gfx::GpuMemoryBufferHandle();
30    }
31  }
32  virtual void DestroyGpuMemoryBuffer(
33      const gfx::GpuMemoryBufferHandle& handle) OVERRIDE {
34    switch (handle.type) {
35      case gfx::IO_SURFACE_BUFFER:
36        io_surface_factory_.DestroyGpuMemoryBuffer(handle.global_id);
37        break;
38      default:
39        NOTREACHED();
40        break;
41    }
42  }
43  virtual scoped_refptr<gfx::GLImage> CreateImageForGpuMemoryBuffer(
44      const gfx::GpuMemoryBufferHandle& handle,
45      const gfx::Size& size,
46      unsigned internalformat,
47      int client_id) OVERRIDE {
48    switch (handle.type) {
49      case gfx::SHARED_MEMORY_BUFFER: {
50        scoped_refptr<gfx::GLImageSharedMemory> image(
51            new gfx::GLImageSharedMemory(size, internalformat));
52        if (!image->Initialize(handle))
53          return NULL;
54
55        return image;
56      }
57      case gfx::IO_SURFACE_BUFFER: {
58        // Verify that client is the owner of the buffer we're about to use.
59        if (handle.global_id.secondary_id != client_id)
60          return scoped_refptr<gfx::GLImage>();
61
62        return io_surface_factory_.CreateImageForGpuMemoryBuffer(
63            handle.global_id, size, internalformat);
64      }
65      default:
66        NOTREACHED();
67        return scoped_refptr<gfx::GLImage>();
68    }
69  }
70
71 private:
72  GpuMemoryBufferFactoryIOSurface io_surface_factory_;
73};
74
75}  // namespace
76
77// static
78scoped_ptr<GpuMemoryBufferFactory> GpuMemoryBufferFactory::Create() {
79  return make_scoped_ptr<GpuMemoryBufferFactory>(
80      new GpuMemoryBufferFactoryImpl);
81}
82
83}  // namespace content
84