xref: /aosp_15_r20/external/drm_hwcomposer/drm/DrmFbImporter.h (revision 0a9764fe0a15e71ebbeb85e87e10990c23aab47f)
1 /*
2  * Copyright (C) 2021 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 #pragma once
18 
19 #include <drm/drm_fourcc.h>
20 #include <hardware/gralloc.h>
21 
22 #include <array>
23 #include <map>
24 
25 #include "bufferinfo/BufferInfo.h"
26 #include "drm/DrmDevice.h"
27 #include "utils/fd.h"
28 
29 #ifndef DRM_FORMAT_INVALID
30 #define DRM_FORMAT_INVALID 0
31 #endif
32 
33 using GemHandle = uint32_t;
34 
35 namespace android {
36 
37 class DrmFbIdHandle {
38  public:
39   static auto CreateInstance(BufferInfo *bo, GemHandle first_gem_handle,
40                              DrmDevice &drm) -> std::shared_ptr<DrmFbIdHandle>;
41 
42   ~DrmFbIdHandle();
43   DrmFbIdHandle(DrmFbIdHandle &&) = delete;
44   DrmFbIdHandle(const DrmFbIdHandle &) = delete;
45   auto operator=(const DrmFbIdHandle &) = delete;
46   auto operator=(DrmFbIdHandle &&) = delete;
47 
48   auto GetFbId [[nodiscard]] () const -> uint32_t {
49     return fb_id_;
50   }
51 
52  private:
DrmFbIdHandle(DrmDevice & drm)53   explicit DrmFbIdHandle(DrmDevice &drm) : drm_fd_(drm.GetFd()) {};
54 
55   SharedFd drm_fd_;
56 
57   uint32_t fb_id_{};
58   std::array<GemHandle, kBufferMaxPlanes> gem_handles_{};
59 };
60 
61 class DrmFbImporter {
62  public:
DrmFbImporter(DrmDevice & drm)63   explicit DrmFbImporter(DrmDevice &drm) : drm_(&drm){};
64   ~DrmFbImporter() = default;
65   DrmFbImporter(const DrmFbImporter &) = delete;
66   DrmFbImporter(DrmFbImporter &&) = delete;
67   auto operator=(const DrmFbImporter &) = delete;
68   auto operator=(DrmFbImporter &&) = delete;
69 
70   auto GetOrCreateFbId(BufferInfo *bo) -> std::shared_ptr<DrmFbIdHandle>;
71 
72  private:
CleanupEmptyCacheElements()73   void CleanupEmptyCacheElements() {
74     for (auto it = drm_fb_id_handle_cache_.begin();
75          it != drm_fb_id_handle_cache_.end();) {
76       if (it->second.expired()) {
77         it = drm_fb_id_handle_cache_.erase(it);
78       } else {
79         ++it;
80       }
81     }
82   }
83 
84   DrmDevice *const drm_;
85   SharedFd drm_fd_;
86 
87   std::map<GemHandle, std::weak_ptr<DrmFbIdHandle>> drm_fb_id_handle_cache_;
88 };
89 
90 }  // namespace android
91