1 /*
2  * Copyright 2019 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 <condition_variable>
20 #include <mutex>
21 #include <queue>
22 #include <thread>
23 
24 #include <ui/GraphicBuffer.h>
25 
26 namespace android {
27 namespace renderengine {
28 namespace gl {
29 
30 class GLESRenderEngine;
31 
32 class ImageManager {
33 public:
34     struct Barrier {
35         std::mutex mutex;
36         std::condition_variable_any condition;
37         bool isOpen GUARDED_BY(mutex) = false;
38         status_t result GUARDED_BY(mutex) = NO_ERROR;
39     };
40     ImageManager(GLESRenderEngine* engine);
41     ~ImageManager();
42     // Starts the background thread for the ImageManager
43     // We need this to guarantee that the class is fully-constructed before the
44     // thread begins running.
45     void initThread();
46     void cacheAsync(const sp<GraphicBuffer>& buffer, const std::shared_ptr<Barrier>& barrier)
47             EXCLUDES(mMutex);
48     status_t cache(const sp<GraphicBuffer>& buffer);
49     void releaseAsync(uint64_t bufferId, const std::shared_ptr<Barrier>& barrier) EXCLUDES(mMutex);
50 
51 private:
52     struct QueueEntry {
53         enum class Operation { Delete, Insert };
54 
55         Operation op = Operation::Delete;
56         sp<GraphicBuffer> buffer = nullptr;
57         uint64_t bufferId = 0;
58         std::shared_ptr<Barrier> barrier = nullptr;
59     };
60 
61     void queueOperation(const QueueEntry&& entry);
62     void threadMain();
63     GLESRenderEngine* const mEngine;
64     std::thread mThread;
65     std::condition_variable_any mCondition;
66     std::mutex mMutex;
67     std::queue<QueueEntry> mQueue GUARDED_BY(mMutex);
68 
69     bool mRunning GUARDED_BY(mMutex) = true;
70 };
71 
72 } // namespace gl
73 } // namespace renderengine
74 } // namespace android
75