1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "Utils.h"
18 
19 #include <aidl/android/hardware/automotive/evs/BufferDesc.h>
20 #include <aidlcommonsupport/NativeHandle.h>
21 #include <android-base/logging.h>
22 
23 namespace {
24 
25 using aidl::android::hardware::automotive::evs::BufferDesc;
26 using aidl::android::hardware::common::NativeHandle;
27 using aidl::android::hardware::graphics::common::HardwareBuffer;
28 
dupNativeHandle(const NativeHandle & handle)29 NativeHandle dupNativeHandle(const NativeHandle& handle) {
30     NativeHandle dup;
31 
32     dup.fds = std::vector<::ndk::ScopedFileDescriptor>(handle.fds.size());
33     const size_t n = handle.fds.size();
34     for (size_t i = 0; i < n; ++i) {
35         dup.fds[i] = handle.fds[i].dup();
36     }
37     dup.ints = handle.ints;
38 
39     return dup;
40 }
41 
dupHardwareBuffer(const HardwareBuffer & buffer)42 HardwareBuffer dupHardwareBuffer(const HardwareBuffer& buffer) {
43     HardwareBuffer dup = {
44             .description = buffer.description,
45             .handle = dupNativeHandle(buffer.handle),
46     };
47 
48     return dup;
49 }
50 
51 }  // namespace
52 
dupBufferDesc(const BufferDesc & src)53 BufferDesc dupBufferDesc(const BufferDesc& src) {
54     BufferDesc dup = {
55             .buffer = dupHardwareBuffer(src.buffer),
56             .pixelSizeBytes = src.pixelSizeBytes,
57             .bufferId = src.bufferId,
58             .deviceId = src.deviceId,
59             .timestamp = src.timestamp,
60             .metadata = src.metadata,
61     };
62 
63     return dup;
64 }
65 
getNativeHandle(const BufferDesc & buffer)66 native_handle_t* getNativeHandle(const BufferDesc& buffer) {
67     native_handle_t* nativeHandle = android::makeFromAidl(buffer.buffer.handle);
68     if (nativeHandle == nullptr ||
69         !std::all_of(nativeHandle->data + 0, nativeHandle->data + nativeHandle->numFds,
70                      [](int fd) { return fd >= 0; })) {
71         LOG(ERROR) << "Buffer " << buffer.bufferId << " contains an invalid native handle.";
72         free(nativeHandle);
73         return nullptr;
74     }
75 
76     return nativeHandle;
77 }
78