1 /*
2  * Copyright 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 #ifndef ANDROID_HWC_FENCEDBUFFER_H
18 #define ANDROID_HWC_FENCEDBUFFER_H
19 
20 #include <aidlcommonsupport/NativeHandle.h>
21 #include <android-base/unique_fd.h>
22 #include <cutils/native_handle.h>
23 
24 namespace aidl::android::hardware::graphics::composer3::impl {
25 
26 class FencedBuffer {
27    public:
FencedBuffer()28     FencedBuffer() : mBuffer(nullptr) {}
29 
set(buffer_handle_t buffer,const ndk::ScopedFileDescriptor & fence)30     void set(buffer_handle_t buffer, const ndk::ScopedFileDescriptor& fence) {
31         mBuffer = buffer;
32         mFence = GetUniqueFd(fence);
33     }
34 
getBuffer()35     buffer_handle_t getBuffer() const { return mBuffer; }
36 
getFence()37     ::android::base::unique_fd getFence() const {
38         if (mFence.ok()) {
39             return ::android::base::unique_fd(dup(mFence.get()));
40         } else {
41             return ::android::base::unique_fd();
42         }
43     }
44 
45    private:
GetUniqueFd(const ndk::ScopedFileDescriptor & in)46     static ::android::base::unique_fd GetUniqueFd(const ndk::ScopedFileDescriptor& in) {
47         auto& sfd = const_cast<ndk::ScopedFileDescriptor&>(in);
48         ::android::base::unique_fd ret(sfd.get());
49         *sfd.getR() = -1;
50         return ret;
51     }
52 
53     buffer_handle_t mBuffer;
54     ::android::base::unique_fd mFence;
55 };
56 
57 }  // namespace aidl::android::hardware::graphics::composer3::impl
58 
59 #endif
60