OSDN Git Service

c1d389160c27f5b33e69757371f00001002ad566
[android-x86/frameworks-native.git] / libs / gui / include / gui / BLASTBufferQueue.h
1 /*
2  * Copyright (C) 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 #ifndef ANDROID_GUI_BLAST_BUFFER_QUEUE_H
18 #define ANDROID_GUI_BLAST_BUFFER_QUEUE_H
19
20 #include <gui/IGraphicBufferProducer.h>
21 #include <gui/BufferItemConsumer.h>
22 #include <gui/BufferItem.h>
23 #include <gui/SurfaceComposerClient.h>
24
25 #include <utils/Condition.h>
26 #include <utils/Mutex.h>
27 #include <utils/RefBase.h>
28
29 #include <system/window.h>
30 #include <thread>
31 #include <queue>
32
33 namespace android {
34
35 class BLASTBufferQueue;
36 class BufferItemConsumer;
37
38 class BLASTBufferItemConsumer : public BufferItemConsumer {
39 public:
40     BLASTBufferItemConsumer(const sp<IGraphicBufferConsumer>& consumer, uint64_t consumerUsage,
41                             int bufferCount, bool controlledByApp)
42           : BufferItemConsumer(consumer, consumerUsage, bufferCount, controlledByApp),
43             mCurrentlyConnected(false),
44             mPreviouslyConnected(false),
45             mBLASTBufferQueue(nullptr) {}
46
47     void onDisconnect() override;
48     void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
49                                   FrameEventHistoryDelta* outDelta) override REQUIRES(mMutex);
50     void updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
51                                const sp<Fence>& gpuCompositionDoneFence,
52                                const sp<Fence>& presentFence, const sp<Fence>& prevReleaseFence,
53                                CompositorTiming compositorTiming, nsecs_t latchTime,
54                                nsecs_t dequeueReadyTime) REQUIRES(mMutex);
55     void getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect);
56     void setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) REQUIRES(mMutex);
57
58 protected:
59     void onSidebandStreamChanged() override REQUIRES(mMutex);
60
61 private:
62     uint64_t mCurrentFrameNumber = 0;
63
64     Mutex mMutex;
65     std::mutex mBufferQueueMutex;
66     ConsumerFrameEventHistory mFrameEventHistory GUARDED_BY(mMutex);
67     std::queue<uint64_t> mDisconnectEvents GUARDED_BY(mMutex);
68     bool mCurrentlyConnected GUARDED_BY(mMutex);
69     bool mPreviouslyConnected GUARDED_BY(mMutex);
70     BLASTBufferQueue* mBLASTBufferQueue GUARDED_BY(mBufferQueueMutex);
71 };
72
73 class BLASTBufferQueue
74     : public ConsumerBase::FrameAvailableListener, public BufferItemConsumer::BufferFreedListener
75 {
76 public:
77     BLASTBufferQueue(const std::string& name);
78     BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface, int width,
79                      int height, int32_t format);
80
81     sp<IGraphicBufferProducer> getIGraphicBufferProducer() const {
82         return mProducer;
83     }
84     sp<Surface> getSurface(bool includeSurfaceControlHandle);
85
86     void onBufferFreed(const wp<GraphicBuffer>&/* graphicBuffer*/) override { /* TODO */ }
87     void onFrameReplaced(const BufferItem& item) override;
88     void onFrameAvailable(const BufferItem& item) override;
89     void onFrameDequeued(const uint64_t) override;
90     void onFrameCancelled(const uint64_t) override;
91
92     void transactionCommittedCallback(nsecs_t latchTime, const sp<Fence>& presentFence,
93                                       const std::vector<SurfaceControlStats>& stats);
94     void transactionCallback(nsecs_t latchTime, const sp<Fence>& presentFence,
95             const std::vector<SurfaceControlStats>& stats);
96     void releaseBufferCallback(const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
97                                uint32_t transformHint, uint32_t currentMaxAcquiredBufferCount);
98     void setNextTransaction(SurfaceComposerClient::Transaction *t);
99     void mergeWithNextTransaction(SurfaceComposerClient::Transaction* t, uint64_t frameNumber);
100     void setTransactionCompleteCallback(uint64_t frameNumber,
101                                         std::function<void(int64_t)>&& transactionCompleteCallback);
102
103     void update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height, int32_t format,
104                 SurfaceComposerClient::Transaction* outTransaction = nullptr);
105
106     status_t setFrameRate(float frameRate, int8_t compatibility, bool shouldBeSeamless);
107     status_t setFrameTimelineInfo(const FrameTimelineInfo& info);
108
109     void setSidebandStream(const sp<NativeHandle>& stream);
110
111     uint32_t getLastTransformHint() const;
112     void flushShadowQueue();
113
114     uint64_t getLastAcquiredFrameNum();
115
116     virtual ~BLASTBufferQueue();
117
118 private:
119     friend class BLASTBufferQueueHelper;
120
121     // can't be copied
122     BLASTBufferQueue& operator = (const BLASTBufferQueue& rhs);
123     BLASTBufferQueue(const BLASTBufferQueue& rhs);
124     void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
125                            sp<IGraphicBufferConsumer>* outConsumer);
126
127     void acquireNextBufferLocked(
128             const std::optional<SurfaceComposerClient::Transaction*> transaction) REQUIRES(mMutex);
129     Rect computeCrop(const BufferItem& item) REQUIRES(mMutex);
130     // Return true if we need to reject the buffer based on the scaling mode and the buffer size.
131     bool rejectBuffer(const BufferItem& item) REQUIRES(mMutex);
132     bool maxBuffersAcquired(bool includeExtraAcquire) const REQUIRES(mMutex);
133     static PixelFormat convertBufferFormat(PixelFormat& format);
134
135     void flushShadowQueueLocked() REQUIRES(mMutex);
136     void acquireAndReleaseBuffer() REQUIRES(mMutex);
137
138     std::string mName;
139     // Represents the queued buffer count from buffer queue,
140     // pre-BLAST. This is mNumFrameAvailable (buffers that queued to blast) +
141     // mNumAcquired (buffers that queued to SF)  mPendingRelease.size() (buffers that are held by
142     // blast). This counter is read by android studio profiler.
143     std::string mQueuedBufferTrace;
144     sp<SurfaceControl> mSurfaceControl;
145
146     std::mutex mMutex;
147     std::condition_variable mCallbackCV;
148
149     // BufferQueue internally allows 1 more than
150     // the max to be acquired
151     int32_t mMaxAcquiredBuffers = 1;
152
153     int32_t mNumFrameAvailable GUARDED_BY(mMutex);
154     int32_t mNumAcquired GUARDED_BY(mMutex);
155
156     // Keep a reference to the submitted buffers so we can release when surfaceflinger drops the
157     // buffer or the buffer has been presented and a new buffer is ready to be presented.
158     std::unordered_map<ReleaseCallbackId, BufferItem, ReleaseBufferCallbackIdHash> mSubmitted
159             GUARDED_BY(mMutex);
160
161     // Keep a queue of the released buffers instead of immediately releasing
162     // the buffers back to the buffer queue. This would be controlled by SF
163     // setting the max acquired buffer count.
164     struct ReleasedBuffer {
165         ReleaseCallbackId callbackId;
166         sp<Fence> releaseFence;
167     };
168     std::deque<ReleasedBuffer> mPendingRelease GUARDED_BY(mMutex);
169
170     ui::Size mSize GUARDED_BY(mMutex);
171     ui::Size mRequestedSize GUARDED_BY(mMutex);
172     int32_t mFormat GUARDED_BY(mMutex);
173
174     struct BufferInfo {
175         bool hasBuffer = false;
176         uint32_t width;
177         uint32_t height;
178         uint32_t transform;
179         // This is used to check if we should update the blast layer size immediately or wait until
180         // we get the next buffer. This will support scenarios where the layer can change sizes
181         // and the buffer will scale to fit the new size.
182         uint32_t scalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
183         Rect crop;
184
185         void update(bool hasBuffer, uint32_t width, uint32_t height, uint32_t transform,
186                     uint32_t scalingMode, const Rect& crop) {
187             this->hasBuffer = hasBuffer;
188             this->width = width;
189             this->height = height;
190             this->transform = transform;
191             this->scalingMode = scalingMode;
192             if (!crop.isEmpty()) {
193                 this->crop = crop;
194             } else {
195                 this->crop = Rect(width, height);
196             }
197         }
198     };
199
200     // Last acquired buffer's info. This is used to calculate the correct scale when size change is
201     // requested. We need to use the old buffer's info to determine what scale we need to apply to
202     // ensure the correct size.
203     BufferInfo mLastBufferInfo GUARDED_BY(mMutex);
204     void setMatrix(SurfaceComposerClient::Transaction* t, const BufferInfo& bufferInfo)
205             REQUIRES(mMutex);
206
207     uint32_t mTransformHint GUARDED_BY(mMutex);
208
209     sp<IGraphicBufferConsumer> mConsumer;
210     sp<IGraphicBufferProducer> mProducer;
211     sp<BLASTBufferItemConsumer> mBufferItemConsumer;
212
213     SurfaceComposerClient::Transaction* mNextTransaction GUARDED_BY(mMutex);
214     std::vector<std::tuple<uint64_t /* framenumber */, SurfaceComposerClient::Transaction>>
215             mPendingTransactions GUARDED_BY(mMutex);
216
217     // Last requested auto refresh state set by the producer. The state indicates that the consumer
218     // should acquire the next frame as soon as it can and not wait for a frame to become available.
219     // This is only relevant for shared buffer mode.
220     bool mAutoRefresh GUARDED_BY(mMutex) = false;
221
222     std::queue<FrameTimelineInfo> mNextFrameTimelineInfoQueue GUARDED_BY(mMutex);
223
224     // Tracks the last acquired frame number
225     uint64_t mLastAcquiredFrameNumber GUARDED_BY(mMutex) = 0;
226
227     std::function<void(int64_t)> mTransactionCompleteCallback GUARDED_BY(mMutex) = nullptr;
228     uint64_t mTransactionCompleteFrameNumber GUARDED_BY(mMutex){0};
229
230     // Queues up transactions using this token in SurfaceFlinger. This prevents queued up
231     // transactions from other parts of the client from blocking this transaction.
232     const sp<IBinder> mApplyToken GUARDED_BY(mMutex) = new BBinder();
233
234     // Guards access to mDequeueTimestamps since we cannot hold to mMutex in onFrameDequeued or
235     // we will deadlock.
236     std::mutex mTimestampMutex;
237     // Tracks buffer dequeue times by the client. This info is sent to SurfaceFlinger which uses
238     // it for debugging purposes.
239     std::unordered_map<uint64_t /* bufferId */, nsecs_t> mDequeueTimestamps
240             GUARDED_BY(mTimestampMutex);
241
242     // Keep track of SurfaceControls that have submitted a transaction and BBQ is waiting on a
243     // callback for them.
244     std::queue<sp<SurfaceControl>> mSurfaceControlsWithPendingCallback GUARDED_BY(mMutex);
245
246     uint32_t mCurrentMaxAcquiredBufferCount;
247     bool mWaitForTransactionCallback = false;
248 };
249
250 } // namespace android
251
252 #endif  // ANDROID_GUI_SURFACE_H