blob: 3e08aa456d51fc59b4c28594927b01c76333d99f [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>
28
29#include <utils/String8.h>
30#include <utils/Vector.h>
31#include <utils/threads.h>
32
33namespace android {
34// ----------------------------------------------------------------------------
35
36class String8;
37
38/*
39 * BufferLayerConsumer consumes buffers of graphics data from a BufferQueue,
40 * and makes them available to OpenGL as a texture.
41 *
42 * A typical usage pattern is to set up the BufferLayerConsumer with the
43 * desired options, and call updateTexImage() when a new frame is desired.
44 * If a new frame is available, the texture will be updated. If not,
45 * the previous contents are retained.
46 *
Chia-I Wuc91077c2017-11-27 13:32:04 -080047 * The texture is attached to the GL_TEXTURE_EXTERNAL_OES texture target, in
48 * the EGL context of the first thread that calls updateTexImage(). After that
49 * point, all calls to updateTexImage must be made with the same OpenGL ES
50 * context current.
Chia-I Wuf1405182017-11-27 11:29:21 -080051 *
52 * This class was previously called SurfaceTexture.
53 */
54class BufferLayerConsumer : public ConsumerBase {
55public:
Chia-I Wuf1405182017-11-27 11:29:21 -080056 typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
57
Chia-I Wuc91077c2017-11-27 13:32:04 -080058 // BufferLayerConsumer constructs a new BufferLayerConsumer object.
59 // The tex parameter indicates the name of the OpenGL ES
Chia-I Wubd854bf2017-11-27 13:41:26 -080060 // texture to which images are to be streamed.
61 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex);
Chia-I Wuf1405182017-11-27 11:29:21 -080062
Chia-I Wuf1405182017-11-27 11:29:21 -080063 // updateTexImage acquires the most recently queued buffer, and sets the
64 // image contents of the target texture to it.
65 //
66 // This call may only be made while the OpenGL ES context to which the
67 // target texture belongs is bound to the calling thread.
68 //
69 // This calls doGLFenceWait to ensure proper synchronization.
70 status_t updateTexImage();
71
Chia-I Wuf1405182017-11-27 11:29:21 -080072 // setReleaseFence stores a fence that will signal when the current buffer
73 // is no longer being read. This fence will be returned to the producer
74 // when the current buffer is released by updateTexImage(). Multiple
75 // fences can be set for a given buffer; they will be merged into a single
76 // union fence.
77 virtual void setReleaseFence(const sp<Fence>& fence);
78
79 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
80 // associated with the texture image set by the most recent call to
81 // updateTexImage.
82 //
83 // This transform matrix maps 2D homogeneous texture coordinates of the form
84 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
85 // coordinate that should be used to sample that location from the texture.
86 // Sampling the texture outside of the range of this transform is undefined.
87 //
88 // This transform is necessary to compensate for transforms that the stream
89 // content producer may implicitly apply to the content. By forcing users of
90 // a BufferLayerConsumer to apply this transform we avoid performing an extra
91 // copy of the data that would be needed to hide the transform from the
92 // user.
93 //
94 // The matrix is stored in column-major order so that it may be passed
95 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
96 // functions.
97 void getTransformMatrix(float mtx[16]);
98
99 // Computes the transform matrix documented by getTransformMatrix
100 // from the BufferItem sub parts.
101 static void computeTransformMatrix(float outTransform[16], const sp<GraphicBuffer>& buf,
102 const Rect& cropRect, uint32_t transform, bool filtering);
103
104 // Scale the crop down horizontally or vertically such that it has the
105 // same aspect ratio as the buffer does.
106 static Rect scaleDownCrop(const Rect& crop, uint32_t bufferWidth, uint32_t bufferHeight);
107
108 // getTimestamp retrieves the timestamp associated with the texture image
109 // set by the most recent call to updateTexImage.
110 //
111 // The timestamp is in nanoseconds, and is monotonically increasing. Its
112 // other semantics (zero point, etc) are source-dependent and should be
113 // documented by the source.
114 int64_t getTimestamp();
115
116 // getDataSpace retrieves the DataSpace associated with the texture image
117 // set by the most recent call to updateTexImage.
118 android_dataspace getCurrentDataSpace();
119
120 // getFrameNumber retrieves the frame number associated with the texture
121 // image set by the most recent call to updateTexImage.
122 //
123 // The frame number is an incrementing counter set to 0 at the creation of
124 // the BufferQueue associated with this consumer.
125 uint64_t getFrameNumber();
126
127 // setDefaultBufferSize is used to set the size of buffers returned by
128 // requestBuffers when a with and height of zero is requested.
129 // A call to setDefaultBufferSize() may trigger requestBuffers() to
130 // be called from the client.
131 // The width and height parameters must be no greater than the minimum of
132 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
133 // An error due to invalid dimensions might not be reported until
134 // updateTexImage() is called.
135 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
136
137 // setFilteringEnabled sets whether the transform matrix should be computed
138 // for use with bilinear filtering.
139 void setFilteringEnabled(bool enabled);
140
141 // getCurrentBuffer returns the buffer associated with the current image.
142 // When outSlot is not nullptr, the current buffer slot index is also
143 // returned.
144 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
145
Chia-I Wuf1405182017-11-27 11:29:21 -0800146 // getCurrentCrop returns the cropping rectangle of the current buffer.
147 Rect getCurrentCrop() const;
148
149 // getCurrentTransform returns the transform of the current buffer.
150 uint32_t getCurrentTransform() const;
151
152 // getCurrentScalingMode returns the scaling mode of the current buffer.
153 uint32_t getCurrentScalingMode() const;
154
155 // getCurrentFence returns the fence indicating when the current buffer is
156 // ready to be read from.
157 sp<Fence> getCurrentFence() const;
158
159 // getCurrentFence returns the FenceTime indicating when the current
160 // buffer is ready to be read from.
161 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
162
163 // setConsumerUsageBits overrides the ConsumerBase method to OR
164 // DEFAULT_USAGE_FLAGS to usage.
165 status_t setConsumerUsageBits(uint64_t usage);
166
Chia-I Wuf1405182017-11-27 11:29:21 -0800167protected:
168 // abandonLocked overrides the ConsumerBase method to clear
169 // mCurrentTextureImage in addition to the ConsumerBase behavior.
170 virtual void abandonLocked();
171
172 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
173 // specific info in addition to the ConsumerBase behavior.
174 virtual void dumpLocked(String8& result, const char* prefix) const;
175
176 // acquireBufferLocked overrides the ConsumerBase method to update the
177 // mEglSlots array in addition to the ConsumerBase behavior.
178 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
179 uint64_t maxFrameNumber = 0) override;
180
Chia-I Wuf1405182017-11-27 11:29:21 -0800181 struct PendingRelease {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800182 PendingRelease() : isPending(false), currentTexture(-1), graphicBuffer() {}
Chia-I Wuf1405182017-11-27 11:29:21 -0800183
184 bool isPending;
185 int currentTexture;
186 sp<GraphicBuffer> graphicBuffer;
Chia-I Wuf1405182017-11-27 11:29:21 -0800187 };
188
189 // This releases the buffer in the slot referenced by mCurrentTexture,
190 // then updates state to refer to the BufferItem, which must be a
191 // newly-acquired buffer. If pendingRelease is not null, the parameters
192 // which would have been passed to releaseBufferLocked upon the successful
193 // completion of the method will instead be returned to the caller, so that
194 // it may call releaseBufferLocked itself later.
195 status_t updateAndReleaseLocked(const BufferItem& item,
196 PendingRelease* pendingRelease = nullptr);
197
Chia-I Wubd854bf2017-11-27 13:41:26 -0800198 // Binds mTexName and the current buffer to sTexTarget. Uses
Chia-I Wuf1405182017-11-27 11:29:21 -0800199 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
200 // bind succeeds, this calls doGLFenceWait.
201 status_t bindTextureImageLocked();
202
203 // Gets the current EGLDisplay and EGLContext values, and compares them
204 // to mEglDisplay and mEglContext. If the fields have been previously
205 // set, the values must match; if not, the fields are set to the current
206 // values.
Chia-I Wuc91077c2017-11-27 13:32:04 -0800207 status_t checkAndUpdateEglStateLocked();
Chia-I Wuf1405182017-11-27 11:29:21 -0800208
209private:
210 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
211 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800212 // - After freeBuffer, we must still keep the current image/buffer
213 // Reference counting EGLImages lets us handle all these cases easily while
214 // also only creating new EGLImages from buffers when required.
215 class EglImage : public LightRefBase<EglImage> {
216 public:
217 EglImage(sp<GraphicBuffer> graphicBuffer);
218
219 // createIfNeeded creates an EGLImage if required (we haven't created
220 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800221 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800222
223 // This calls glEGLImageTargetTexture2DOES to bind the image to the
224 // texture in the specified texture target.
225 void bindToTextureTarget(uint32_t texTarget);
226
227 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
228 const native_handle* graphicBufferHandle() {
229 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
230 }
231
232 private:
233 // Only allow instantiation using ref counting.
234 friend class LightRefBase<EglImage>;
235 virtual ~EglImage();
236
237 // createImage creates a new EGLImage from a GraphicBuffer.
238 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
239 const Rect& crop);
240
241 // Disallow copying
242 EglImage(const EglImage& rhs);
243 void operator=(const EglImage& rhs);
244
245 // mGraphicBuffer is the buffer that was used to create this image.
246 sp<GraphicBuffer> mGraphicBuffer;
247
248 // mEglImage is the EGLImage created from mGraphicBuffer.
249 EGLImageKHR mEglImage;
250
251 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
252 EGLDisplay mEglDisplay;
253
254 // mCropRect is the crop rectangle passed to EGL when mEglImage
255 // was created.
256 Rect mCropRect;
257 };
258
259 // freeBufferLocked frees up the given buffer slot. If the slot has been
260 // initialized this will release the reference to the GraphicBuffer in that
261 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
262 //
263 // This method must be called with mMutex locked.
264 virtual void freeBufferLocked(int slotIndex);
265
266 // computeCurrentTransformMatrixLocked computes the transform matrix for the
267 // current texture. It uses mCurrentTransform and the current GraphicBuffer
268 // to compute this matrix and stores it in mCurrentTransformMatrix.
269 // mCurrentTextureImage must not be NULL.
270 void computeCurrentTransformMatrixLocked();
271
272 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
273 // stream to ensure that it is safe for future OpenGL ES commands to
274 // access the current texture buffer.
275 status_t doGLFenceWaitLocked() const;
276
277 // syncForReleaseLocked performs the synchronization needed to release the
278 // current slot from an OpenGL ES context. If needed it will set the
279 // current slot's fence to guard against a producer accessing the buffer
280 // before the outstanding accesses have completed.
281 status_t syncForReleaseLocked(EGLDisplay dpy);
282
Chia-I Wubd854bf2017-11-27 13:41:26 -0800283 // sTexTarget is the GL texture target with which the GL texture object is
284 // associated.
285 static constexpr uint32_t sTexTarget = 0x8D65; // GL_TEXTURE_EXTERNAL_OES
286
Chia-I Wuf1405182017-11-27 11:29:21 -0800287 // The default consumer usage flags that BufferLayerConsumer always sets on its
288 // BufferQueue instance; these will be OR:d with any additional flags passed
289 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
290 // consume buffers as hardware textures.
291 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
292
293 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
294 // possible that this buffer is not associated with any buffer slot, so we
295 // must track it separately in order to support the getCurrentBuffer method.
296 sp<EglImage> mCurrentTextureImage;
297
298 // mCurrentCrop is the crop rectangle that applies to the current texture.
299 // It gets set each time updateTexImage is called.
300 Rect mCurrentCrop;
301
302 // mCurrentTransform is the transform identifier for the current texture. It
303 // gets set each time updateTexImage is called.
304 uint32_t mCurrentTransform;
305
306 // mCurrentScalingMode is the scaling mode for the current texture. It gets
307 // set each time updateTexImage is called.
308 uint32_t mCurrentScalingMode;
309
310 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
311 sp<Fence> mCurrentFence;
312
313 // The FenceTime wrapper around mCurrentFence.
314 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
315
316 // mCurrentTransformMatrix is the transform matrix for the current texture.
317 // It gets computed by computeTransformMatrix each time updateTexImage is
318 // called.
319 float mCurrentTransformMatrix[16];
320
321 // mCurrentTimestamp is the timestamp for the current texture. It
322 // gets set each time updateTexImage is called.
323 int64_t mCurrentTimestamp;
324
325 // mCurrentDataSpace is the dataspace for the current texture. It
326 // gets set each time updateTexImage is called.
327 android_dataspace mCurrentDataSpace;
328
329 // mCurrentFrameNumber is the frame counter for the current texture.
330 // It gets set each time updateTexImage is called.
331 uint64_t mCurrentFrameNumber;
332
333 uint32_t mDefaultWidth, mDefaultHeight;
334
335 // mFilteringEnabled indicates whether the transform matrix is computed for
336 // use with bilinear filtering. It defaults to true and is changed by
337 // setFilteringEnabled().
338 bool mFilteringEnabled;
339
340 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800341 // be bound when updateTexImage is called. It is set at construction time.
342 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800343
Chia-I Wuf1405182017-11-27 11:29:21 -0800344 // EGLSlot contains the information and object references that
345 // BufferLayerConsumer maintains about a BufferQueue buffer slot.
346 struct EglSlot {
Chia-I Wuf1405182017-11-27 11:29:21 -0800347 // mEglImage is the EGLImage created from mGraphicBuffer.
348 sp<EglImage> mEglImage;
Chia-I Wuf1405182017-11-27 11:29:21 -0800349 };
350
351 // mEglDisplay is the EGLDisplay with which this BufferLayerConsumer is currently
352 // associated. It is intialized to EGL_NO_DISPLAY and gets set to the
Chia-I Wuc91077c2017-11-27 13:32:04 -0800353 // current display when updateTexImage is called for the first time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800354 EGLDisplay mEglDisplay;
355
356 // mEglContext is the OpenGL ES context with which this BufferLayerConsumer is
357 // currently associated. It is initialized to EGL_NO_CONTEXT and gets set
358 // to the current GL context when updateTexImage is called for the first
Chia-I Wuc91077c2017-11-27 13:32:04 -0800359 // time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800360 EGLContext mEglContext;
361
362 // mEGLSlots stores the buffers that have been allocated by the BufferQueue
363 // for each buffer slot. It is initialized to null pointers, and gets
364 // filled in with the result of BufferQueue::acquire when the
365 // client dequeues a buffer from a
366 // slot that has not yet been used. The buffer allocated to a slot will also
367 // be replaced if the requested buffer usage or geometry differs from that
368 // of the buffer allocated to a slot.
369 EglSlot mEglSlots[BufferQueueDefs::NUM_BUFFER_SLOTS];
370
371 // mCurrentTexture is the buffer slot index of the buffer that is currently
372 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
373 // indicating that no buffer slot is currently bound to the texture. Note,
374 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
375 // that no buffer is bound to the texture. A call to setBufferCount will
376 // reset mCurrentTexture to INVALID_BUFFER_SLOT.
377 int mCurrentTexture;
Chia-I Wuf1405182017-11-27 11:29:21 -0800378};
379
380// ----------------------------------------------------------------------------
381}; // namespace android
382
383#endif // ANDROID_BUFFERLAYERCONSUMER_H