blob: 4f8e5fadecb268343e7bb65bbbdbba449de44dbe [file] [log] [blame]
Chia-I Wuf1405182017-11-27 11:29:21 -08001/*
2 * Copyright (C) 2010 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_BUFFERLAYERCONSUMER_H
18#define ANDROID_BUFFERLAYERCONSUMER_H
19
20#include <EGL/egl.h>
21#include <EGL/eglext.h>
22
23#include <gui/BufferQueueDefs.h>
24#include <gui/ConsumerBase.h>
25
26#include <ui/FenceTime.h>
27#include <ui/GraphicBuffer.h>
Chia-I Wu67dcc692017-11-27 14:51:06 -080028#include <ui/Region.h>
Chia-I Wuf1405182017-11-27 11:29:21 -080029
30#include <utils/String8.h>
31#include <utils/Vector.h>
32#include <utils/threads.h>
33
34namespace android {
35// ----------------------------------------------------------------------------
36
Chia-I Wuda5c7302017-11-27 14:51:06 -080037class DispSync;
Chia-I Wuc75c44d2017-11-27 14:32:57 -080038class Layer;
Chia-I Wuf1405182017-11-27 11:29:21 -080039class String8;
40
41/*
42 * BufferLayerConsumer consumes buffers of graphics data from a BufferQueue,
43 * and makes them available to OpenGL as a texture.
44 *
45 * A typical usage pattern is to set up the BufferLayerConsumer with the
46 * desired options, and call updateTexImage() when a new frame is desired.
47 * If a new frame is available, the texture will be updated. If not,
48 * the previous contents are retained.
49 *
Chia-I Wuc91077c2017-11-27 13:32:04 -080050 * The texture is attached to the GL_TEXTURE_EXTERNAL_OES texture target, in
51 * the EGL context of the first thread that calls updateTexImage(). After that
52 * point, all calls to updateTexImage must be made with the same OpenGL ES
53 * context current.
Chia-I Wuf1405182017-11-27 11:29:21 -080054 *
55 * This class was previously called SurfaceTexture.
56 */
57class BufferLayerConsumer : public ConsumerBase {
58public:
Chia-I Wuda5c7302017-11-27 14:51:06 -080059 static const status_t BUFFER_REJECTED = UNKNOWN_ERROR + 8;
60
61 class BufferRejecter {
62 friend class BufferLayerConsumer;
63 virtual bool reject(const sp<GraphicBuffer>& buf, const BufferItem& item) = 0;
64
65 protected:
66 virtual ~BufferRejecter() {}
67 };
68
Chia-I Wufd257f82017-11-27 14:51:06 -080069 struct ContentsChangedListener : public FrameAvailableListener {
70 virtual void onSidebandStreamChanged() = 0;
71 };
Chia-I Wuf1405182017-11-27 11:29:21 -080072
Chia-I Wuc91077c2017-11-27 13:32:04 -080073 // BufferLayerConsumer constructs a new BufferLayerConsumer object.
74 // The tex parameter indicates the name of the OpenGL ES
Chia-I Wubd854bf2017-11-27 13:41:26 -080075 // texture to which images are to be streamed.
Chia-I Wuc75c44d2017-11-27 14:32:57 -080076 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex, Layer* layer);
Chia-I Wuf1405182017-11-27 11:29:21 -080077
Chia-I Wufd257f82017-11-27 14:51:06 -080078 // Sets the contents changed listener. This should be used instead of
79 // ConsumerBase::setFrameAvailableListener().
80 void setContentsChangedListener(const wp<ContentsChangedListener>& listener);
81
Chia-I Wuda5c7302017-11-27 14:51:06 -080082 nsecs_t computeExpectedPresent(const DispSync& dispSync);
83
Chia-I Wuf1405182017-11-27 11:29:21 -080084 // updateTexImage acquires the most recently queued buffer, and sets the
85 // image contents of the target texture to it.
86 //
87 // This call may only be made while the OpenGL ES context to which the
88 // target texture belongs is bound to the calling thread.
89 //
90 // This calls doGLFenceWait to ensure proper synchronization.
Chia-I Wuda5c7302017-11-27 14:51:06 -080091 //
92 // This version of updateTexImage() takes a functor that may be used to
93 // reject the newly acquired buffer. Unlike the GLConsumer version,
94 // this does not guarantee that the buffer has been bound to the GL
95 // texture.
96 status_t updateTexImage(BufferRejecter* rejecter, const DispSync& dispSync, bool* autoRefresh,
97 bool* queuedBuffer, uint64_t maxFrameNumber);
Chia-I Wuf1405182017-11-27 11:29:21 -080098
Chia-I Wuf1405182017-11-27 11:29:21 -080099 // setReleaseFence stores a fence that will signal when the current buffer
100 // is no longer being read. This fence will be returned to the producer
101 // when the current buffer is released by updateTexImage(). Multiple
102 // fences can be set for a given buffer; they will be merged into a single
103 // union fence.
Chia-I Wuda5c7302017-11-27 14:51:06 -0800104 void setReleaseFence(const sp<Fence>& fence);
105
106 bool releasePendingBuffer();
Chia-I Wuf1405182017-11-27 11:29:21 -0800107
108 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
109 // associated with the texture image set by the most recent call to
110 // updateTexImage.
111 //
112 // This transform matrix maps 2D homogeneous texture coordinates of the form
113 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
114 // coordinate that should be used to sample that location from the texture.
115 // Sampling the texture outside of the range of this transform is undefined.
116 //
117 // This transform is necessary to compensate for transforms that the stream
118 // content producer may implicitly apply to the content. By forcing users of
119 // a BufferLayerConsumer to apply this transform we avoid performing an extra
120 // copy of the data that would be needed to hide the transform from the
121 // user.
122 //
123 // The matrix is stored in column-major order so that it may be passed
124 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
125 // functions.
126 void getTransformMatrix(float mtx[16]);
127
Chia-I Wuf1405182017-11-27 11:29:21 -0800128 // getTimestamp retrieves the timestamp associated with the texture image
129 // set by the most recent call to updateTexImage.
130 //
131 // The timestamp is in nanoseconds, and is monotonically increasing. Its
132 // other semantics (zero point, etc) are source-dependent and should be
133 // documented by the source.
134 int64_t getTimestamp();
135
136 // getDataSpace retrieves the DataSpace associated with the texture image
137 // set by the most recent call to updateTexImage.
138 android_dataspace getCurrentDataSpace();
139
140 // getFrameNumber retrieves the frame number associated with the texture
141 // image set by the most recent call to updateTexImage.
142 //
143 // The frame number is an incrementing counter set to 0 at the creation of
144 // the BufferQueue associated with this consumer.
145 uint64_t getFrameNumber();
146
Chia-I Wu67dcc692017-11-27 14:51:06 -0800147 bool getTransformToDisplayInverse() const;
148
149 // must be called from SF main thread
150 const Region& getSurfaceDamage() const;
151
Chia-I Wuf1405182017-11-27 11:29:21 -0800152 // setDefaultBufferSize is used to set the size of buffers returned by
153 // requestBuffers when a with and height of zero is requested.
154 // A call to setDefaultBufferSize() may trigger requestBuffers() to
155 // be called from the client.
156 // The width and height parameters must be no greater than the minimum of
157 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
158 // An error due to invalid dimensions might not be reported until
159 // updateTexImage() is called.
160 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
161
162 // setFilteringEnabled sets whether the transform matrix should be computed
163 // for use with bilinear filtering.
164 void setFilteringEnabled(bool enabled);
165
166 // getCurrentBuffer returns the buffer associated with the current image.
167 // When outSlot is not nullptr, the current buffer slot index is also
168 // returned.
169 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
170
Chia-I Wuf1405182017-11-27 11:29:21 -0800171 // getCurrentCrop returns the cropping rectangle of the current buffer.
172 Rect getCurrentCrop() const;
173
174 // getCurrentTransform returns the transform of the current buffer.
175 uint32_t getCurrentTransform() const;
176
177 // getCurrentScalingMode returns the scaling mode of the current buffer.
178 uint32_t getCurrentScalingMode() const;
179
180 // getCurrentFence returns the fence indicating when the current buffer is
181 // ready to be read from.
182 sp<Fence> getCurrentFence() const;
183
184 // getCurrentFence returns the FenceTime indicating when the current
185 // buffer is ready to be read from.
186 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
187
188 // setConsumerUsageBits overrides the ConsumerBase method to OR
189 // DEFAULT_USAGE_FLAGS to usage.
190 status_t setConsumerUsageBits(uint64_t usage);
191
Chia-I Wuf1405182017-11-27 11:29:21 -0800192protected:
193 // abandonLocked overrides the ConsumerBase method to clear
194 // mCurrentTextureImage in addition to the ConsumerBase behavior.
195 virtual void abandonLocked();
196
197 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
198 // specific info in addition to the ConsumerBase behavior.
199 virtual void dumpLocked(String8& result, const char* prefix) const;
200
201 // acquireBufferLocked overrides the ConsumerBase method to update the
202 // mEglSlots array in addition to the ConsumerBase behavior.
203 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
204 uint64_t maxFrameNumber = 0) override;
205
Chia-I Wuf1405182017-11-27 11:29:21 -0800206 struct PendingRelease {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800207 PendingRelease() : isPending(false), currentTexture(-1), graphicBuffer() {}
Chia-I Wuf1405182017-11-27 11:29:21 -0800208
209 bool isPending;
210 int currentTexture;
211 sp<GraphicBuffer> graphicBuffer;
Chia-I Wuf1405182017-11-27 11:29:21 -0800212 };
213
214 // This releases the buffer in the slot referenced by mCurrentTexture,
215 // then updates state to refer to the BufferItem, which must be a
216 // newly-acquired buffer. If pendingRelease is not null, the parameters
217 // which would have been passed to releaseBufferLocked upon the successful
218 // completion of the method will instead be returned to the caller, so that
219 // it may call releaseBufferLocked itself later.
220 status_t updateAndReleaseLocked(const BufferItem& item,
221 PendingRelease* pendingRelease = nullptr);
222
Chia-I Wubd854bf2017-11-27 13:41:26 -0800223 // Binds mTexName and the current buffer to sTexTarget. Uses
Chia-I Wuf1405182017-11-27 11:29:21 -0800224 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
225 // bind succeeds, this calls doGLFenceWait.
226 status_t bindTextureImageLocked();
227
228 // Gets the current EGLDisplay and EGLContext values, and compares them
229 // to mEglDisplay and mEglContext. If the fields have been previously
230 // set, the values must match; if not, the fields are set to the current
231 // values.
Chia-I Wuc91077c2017-11-27 13:32:04 -0800232 status_t checkAndUpdateEglStateLocked();
Chia-I Wuf1405182017-11-27 11:29:21 -0800233
234private:
235 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
236 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800237 // - After freeBuffer, we must still keep the current image/buffer
238 // Reference counting EGLImages lets us handle all these cases easily while
239 // also only creating new EGLImages from buffers when required.
240 class EglImage : public LightRefBase<EglImage> {
241 public:
242 EglImage(sp<GraphicBuffer> graphicBuffer);
243
244 // createIfNeeded creates an EGLImage if required (we haven't created
245 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800246 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800247
248 // This calls glEGLImageTargetTexture2DOES to bind the image to the
249 // texture in the specified texture target.
250 void bindToTextureTarget(uint32_t texTarget);
251
252 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
253 const native_handle* graphicBufferHandle() {
254 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
255 }
256
257 private:
258 // Only allow instantiation using ref counting.
259 friend class LightRefBase<EglImage>;
260 virtual ~EglImage();
261
262 // createImage creates a new EGLImage from a GraphicBuffer.
263 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
264 const Rect& crop);
265
266 // Disallow copying
267 EglImage(const EglImage& rhs);
268 void operator=(const EglImage& rhs);
269
270 // mGraphicBuffer is the buffer that was used to create this image.
271 sp<GraphicBuffer> mGraphicBuffer;
272
273 // mEglImage is the EGLImage created from mGraphicBuffer.
274 EGLImageKHR mEglImage;
275
276 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
277 EGLDisplay mEglDisplay;
278
279 // mCropRect is the crop rectangle passed to EGL when mEglImage
280 // was created.
281 Rect mCropRect;
282 };
283
284 // freeBufferLocked frees up the given buffer slot. If the slot has been
285 // initialized this will release the reference to the GraphicBuffer in that
286 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
287 //
288 // This method must be called with mMutex locked.
289 virtual void freeBufferLocked(int slotIndex);
290
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800291 // IConsumerListener interface
292 void onDisconnect() override;
Chia-I Wufd257f82017-11-27 14:51:06 -0800293 void onSidebandStreamChanged() override;
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800294 void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
295 FrameEventHistoryDelta* outDelta) override;
296
Chia-I Wuf1405182017-11-27 11:29:21 -0800297 // computeCurrentTransformMatrixLocked computes the transform matrix for the
298 // current texture. It uses mCurrentTransform and the current GraphicBuffer
299 // to compute this matrix and stores it in mCurrentTransformMatrix.
300 // mCurrentTextureImage must not be NULL.
301 void computeCurrentTransformMatrixLocked();
302
303 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
304 // stream to ensure that it is safe for future OpenGL ES commands to
305 // access the current texture buffer.
306 status_t doGLFenceWaitLocked() const;
307
308 // syncForReleaseLocked performs the synchronization needed to release the
309 // current slot from an OpenGL ES context. If needed it will set the
310 // current slot's fence to guard against a producer accessing the buffer
311 // before the outstanding accesses have completed.
312 status_t syncForReleaseLocked(EGLDisplay dpy);
313
Chia-I Wubd854bf2017-11-27 13:41:26 -0800314 // sTexTarget is the GL texture target with which the GL texture object is
315 // associated.
316 static constexpr uint32_t sTexTarget = 0x8D65; // GL_TEXTURE_EXTERNAL_OES
317
Chia-I Wuf1405182017-11-27 11:29:21 -0800318 // The default consumer usage flags that BufferLayerConsumer always sets on its
319 // BufferQueue instance; these will be OR:d with any additional flags passed
320 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
321 // consume buffers as hardware textures.
322 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
323
324 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
325 // possible that this buffer is not associated with any buffer slot, so we
326 // must track it separately in order to support the getCurrentBuffer method.
327 sp<EglImage> mCurrentTextureImage;
328
329 // mCurrentCrop is the crop rectangle that applies to the current texture.
330 // It gets set each time updateTexImage is called.
331 Rect mCurrentCrop;
332
333 // mCurrentTransform is the transform identifier for the current texture. It
334 // gets set each time updateTexImage is called.
335 uint32_t mCurrentTransform;
336
337 // mCurrentScalingMode is the scaling mode for the current texture. It gets
338 // set each time updateTexImage is called.
339 uint32_t mCurrentScalingMode;
340
341 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
342 sp<Fence> mCurrentFence;
343
344 // The FenceTime wrapper around mCurrentFence.
345 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
346
347 // mCurrentTransformMatrix is the transform matrix for the current texture.
348 // It gets computed by computeTransformMatrix each time updateTexImage is
349 // called.
350 float mCurrentTransformMatrix[16];
351
352 // mCurrentTimestamp is the timestamp for the current texture. It
353 // gets set each time updateTexImage is called.
354 int64_t mCurrentTimestamp;
355
356 // mCurrentDataSpace is the dataspace for the current texture. It
357 // gets set each time updateTexImage is called.
358 android_dataspace mCurrentDataSpace;
359
360 // mCurrentFrameNumber is the frame counter for the current texture.
361 // It gets set each time updateTexImage is called.
362 uint64_t mCurrentFrameNumber;
363
Chia-I Wu67dcc692017-11-27 14:51:06 -0800364 // Indicates this buffer must be transformed by the inverse transform of the screen
365 // it is displayed onto. This is applied after BufferLayerConsumer::mCurrentTransform.
366 // This must be set/read from SurfaceFlinger's main thread.
367 bool mCurrentTransformToDisplayInverse;
368
369 // The portion of this surface that has changed since the previous frame
370 Region mCurrentSurfaceDamage;
371
Chia-I Wuf1405182017-11-27 11:29:21 -0800372 uint32_t mDefaultWidth, mDefaultHeight;
373
374 // mFilteringEnabled indicates whether the transform matrix is computed for
375 // use with bilinear filtering. It defaults to true and is changed by
376 // setFilteringEnabled().
377 bool mFilteringEnabled;
378
379 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800380 // be bound when updateTexImage is called. It is set at construction time.
381 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800382
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800383 // The layer for this BufferLayerConsumer
384 const wp<Layer> mLayer;
385
Chia-I Wufd257f82017-11-27 14:51:06 -0800386 wp<ContentsChangedListener> mContentsChangedListener;
387
Chia-I Wuf1405182017-11-27 11:29:21 -0800388 // EGLSlot contains the information and object references that
389 // BufferLayerConsumer maintains about a BufferQueue buffer slot.
390 struct EglSlot {
Chia-I Wuf1405182017-11-27 11:29:21 -0800391 // mEglImage is the EGLImage created from mGraphicBuffer.
392 sp<EglImage> mEglImage;
Chia-I Wuf1405182017-11-27 11:29:21 -0800393 };
394
395 // mEglDisplay is the EGLDisplay with which this BufferLayerConsumer is currently
396 // associated. It is intialized to EGL_NO_DISPLAY and gets set to the
Chia-I Wuc91077c2017-11-27 13:32:04 -0800397 // current display when updateTexImage is called for the first time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800398 EGLDisplay mEglDisplay;
399
400 // mEglContext is the OpenGL ES context with which this BufferLayerConsumer is
401 // currently associated. It is initialized to EGL_NO_CONTEXT and gets set
402 // to the current GL context when updateTexImage is called for the first
Chia-I Wuc91077c2017-11-27 13:32:04 -0800403 // time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800404 EGLContext mEglContext;
405
406 // mEGLSlots stores the buffers that have been allocated by the BufferQueue
407 // for each buffer slot. It is initialized to null pointers, and gets
408 // filled in with the result of BufferQueue::acquire when the
409 // client dequeues a buffer from a
410 // slot that has not yet been used. The buffer allocated to a slot will also
411 // be replaced if the requested buffer usage or geometry differs from that
412 // of the buffer allocated to a slot.
413 EglSlot mEglSlots[BufferQueueDefs::NUM_BUFFER_SLOTS];
414
415 // mCurrentTexture is the buffer slot index of the buffer that is currently
416 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
417 // indicating that no buffer slot is currently bound to the texture. Note,
418 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
419 // that no buffer is bound to the texture. A call to setBufferCount will
420 // reset mCurrentTexture to INVALID_BUFFER_SLOT.
421 int mCurrentTexture;
Chia-I Wuda5c7302017-11-27 14:51:06 -0800422
423 // A release that is pending on the receipt of a new release fence from
424 // presentDisplay
425 PendingRelease mPendingRelease;
Chia-I Wuf1405182017-11-27 11:29:21 -0800426};
427
428// ----------------------------------------------------------------------------
429}; // namespace android
430
431#endif // ANDROID_BUFFERLAYERCONSUMER_H