1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/android/scoped_hardware_buffer_handle.h"
7 #include "base/android/android_hardware_buffer_compat.h"
8 #include "base/logging.h"
9 #include "base/posix/unix_domain_socket.h"
14 ScopedHardwareBufferHandle::ScopedHardwareBufferHandle() = default;
16 ScopedHardwareBufferHandle::ScopedHardwareBufferHandle(
17 ScopedHardwareBufferHandle&& other) {
18 *this = std::move(other);
21 ScopedHardwareBufferHandle::~ScopedHardwareBufferHandle() {
26 ScopedHardwareBufferHandle ScopedHardwareBufferHandle::Adopt(
27 AHardwareBuffer* buffer) {
28 return ScopedHardwareBufferHandle(buffer);
32 ScopedHardwareBufferHandle ScopedHardwareBufferHandle::Create(
33 AHardwareBuffer* buffer) {
34 AndroidHardwareBufferCompat::GetInstance().Acquire(buffer);
35 return ScopedHardwareBufferHandle(buffer);
38 ScopedHardwareBufferHandle& ScopedHardwareBufferHandle::operator=(
39 ScopedHardwareBufferHandle&& other) {
41 std::swap(buffer_, other.buffer_);
45 bool ScopedHardwareBufferHandle::is_valid() const {
46 return buffer_ != nullptr;
49 AHardwareBuffer* ScopedHardwareBufferHandle::get() const {
53 void ScopedHardwareBufferHandle::reset() {
55 AndroidHardwareBufferCompat::GetInstance().Release(buffer_);
60 AHardwareBuffer* ScopedHardwareBufferHandle::Take() {
61 AHardwareBuffer* buffer = buffer_;
66 ScopedHardwareBufferHandle ScopedHardwareBufferHandle::Clone() const {
68 AndroidHardwareBufferCompat::GetInstance().Acquire(buffer_);
69 return ScopedHardwareBufferHandle(buffer_);
72 ScopedFD ScopedHardwareBufferHandle::SerializeAsFileDescriptor() const {
75 ScopedFD reader, writer;
76 if (!CreateSocketPair(&reader, &writer)) {
77 PLOG(ERROR) << "socketpair";
81 // NOTE: SendHandleToUnixSocket does NOT acquire or retain a reference to the
82 // buffer object. The caller is therefore responsible for ensuring that the
83 // buffer remains alive through the lifetime of this file descriptor.
85 AndroidHardwareBufferCompat::GetInstance().SendHandleToUnixSocket(
86 buffer_, writer.get());
88 PLOG(ERROR) << "send";
96 ScopedHardwareBufferHandle
97 ScopedHardwareBufferHandle::DeserializeFromFileDescriptor(ScopedFD fd) {
98 DCHECK(fd.is_valid());
99 DCHECK(AndroidHardwareBufferCompat::IsSupportAvailable());
100 AHardwareBuffer* buffer = nullptr;
102 // NOTE: Upon success, RecvHandleFromUnixSocket acquires a new reference to
103 // the AHardwareBuffer.
105 AndroidHardwareBufferCompat::GetInstance().RecvHandleFromUnixSocket(
108 PLOG(ERROR) << "recv";
109 return ScopedHardwareBufferHandle();
112 return ScopedHardwareBufferHandle(buffer);
115 ScopedHardwareBufferHandle::ScopedHardwareBufferHandle(AHardwareBuffer* buffer)
117 DCHECK(AndroidHardwareBufferCompat::IsSupportAvailable());
120 } // namespace android