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.
5 #include "ui/gl/gl_image_shared_memory.h"
7 #include "base/logging.h"
8 #include "base/numerics/safe_math.h"
9 #include "base/process/process_handle.h"
14 // Returns true if the size is valid and false otherwise.
15 bool SizeInBytes(const gfx::Size& size,
16 gfx::GpuMemoryBuffer::Format format,
17 size_t* size_in_bytes) {
20 base::CheckedNumeric<size_t> s = GLImageMemory::BytesPerPixel(format);
25 *size_in_bytes = s.ValueOrDie();
31 GLImageSharedMemory::GLImageSharedMemory(const gfx::Size& size,
32 unsigned internalformat)
33 : GLImageMemory(size, internalformat) {
36 GLImageSharedMemory::~GLImageSharedMemory() {
37 DCHECK(!shared_memory_);
40 bool GLImageSharedMemory::Initialize(const gfx::GpuMemoryBufferHandle& handle,
41 gfx::GpuMemoryBuffer::Format format) {
43 if (!SizeInBytes(GetSize(), format, &size_in_bytes))
46 if (!base::SharedMemory::IsHandleValid(handle.handle))
49 base::SharedMemory shared_memory(handle.handle, true);
51 // Duplicate the handle.
52 base::SharedMemoryHandle duped_shared_memory_handle;
53 if (!shared_memory.ShareToProcess(base::GetCurrentProcessHandle(),
54 &duped_shared_memory_handle)) {
55 DVLOG(0) << "Failed to duplicate shared memory handle.";
59 scoped_ptr<base::SharedMemory> duped_shared_memory(
60 new base::SharedMemory(duped_shared_memory_handle, true));
61 if (!duped_shared_memory->Map(size_in_bytes)) {
62 DVLOG(0) << "Failed to map shared memory.";
66 if (!GLImageMemory::Initialize(
67 static_cast<unsigned char*>(duped_shared_memory->memory()), format)) {
71 DCHECK(!shared_memory_);
72 shared_memory_ = duped_shared_memory.Pass();
76 void GLImageSharedMemory::Destroy(bool have_context) {
77 GLImageMemory::Destroy(have_context);
78 shared_memory_.reset();