blob: 84a94e7ec967839873568560f9132217a8b8c667 [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:
56 enum { TEXTURE_EXTERNAL = 0x8D65 }; // GL_TEXTURE_EXTERNAL_OES
57 typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
58
Chia-I Wuc91077c2017-11-27 13:32:04 -080059 // BufferLayerConsumer constructs a new BufferLayerConsumer object.
60 // The tex parameter indicates the name of the OpenGL ES
Chia-I Wuf1405182017-11-27 11:29:21 -080061 // texture to which images are to be streamed. texTarget specifies the
62 // OpenGL ES texture target to which the texture will be bound in
63 // updateTexImage. useFenceSync specifies whether fences should be used to
64 // synchronize access to buffers if that behavior is enabled at
65 // compile-time.
Chia-I Wuf1405182017-11-27 11:29:21 -080066 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex, uint32_t texureTarget,
67 bool useFenceSync, bool isControlledByApp);
68
Chia-I Wuf1405182017-11-27 11:29:21 -080069 // updateTexImage acquires the most recently queued buffer, and sets the
70 // image contents of the target texture to it.
71 //
72 // This call may only be made while the OpenGL ES context to which the
73 // target texture belongs is bound to the calling thread.
74 //
75 // This calls doGLFenceWait to ensure proper synchronization.
76 status_t updateTexImage();
77
Chia-I Wuf1405182017-11-27 11:29:21 -080078 // setReleaseFence stores a fence that will signal when the current buffer
79 // is no longer being read. This fence will be returned to the producer
80 // when the current buffer is released by updateTexImage(). Multiple
81 // fences can be set for a given buffer; they will be merged into a single
82 // union fence.
83 virtual void setReleaseFence(const sp<Fence>& fence);
84
85 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
86 // associated with the texture image set by the most recent call to
87 // updateTexImage.
88 //
89 // This transform matrix maps 2D homogeneous texture coordinates of the form
90 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
91 // coordinate that should be used to sample that location from the texture.
92 // Sampling the texture outside of the range of this transform is undefined.
93 //
94 // This transform is necessary to compensate for transforms that the stream
95 // content producer may implicitly apply to the content. By forcing users of
96 // a BufferLayerConsumer to apply this transform we avoid performing an extra
97 // copy of the data that would be needed to hide the transform from the
98 // user.
99 //
100 // The matrix is stored in column-major order so that it may be passed
101 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
102 // functions.
103 void getTransformMatrix(float mtx[16]);
104
105 // Computes the transform matrix documented by getTransformMatrix
106 // from the BufferItem sub parts.
107 static void computeTransformMatrix(float outTransform[16], const sp<GraphicBuffer>& buf,
108 const Rect& cropRect, uint32_t transform, bool filtering);
109
110 // Scale the crop down horizontally or vertically such that it has the
111 // same aspect ratio as the buffer does.
112 static Rect scaleDownCrop(const Rect& crop, uint32_t bufferWidth, uint32_t bufferHeight);
113
114 // getTimestamp retrieves the timestamp associated with the texture image
115 // set by the most recent call to updateTexImage.
116 //
117 // The timestamp is in nanoseconds, and is monotonically increasing. Its
118 // other semantics (zero point, etc) are source-dependent and should be
119 // documented by the source.
120 int64_t getTimestamp();
121
122 // getDataSpace retrieves the DataSpace associated with the texture image
123 // set by the most recent call to updateTexImage.
124 android_dataspace getCurrentDataSpace();
125
126 // getFrameNumber retrieves the frame number associated with the texture
127 // image set by the most recent call to updateTexImage.
128 //
129 // The frame number is an incrementing counter set to 0 at the creation of
130 // the BufferQueue associated with this consumer.
131 uint64_t getFrameNumber();
132
133 // setDefaultBufferSize is used to set the size of buffers returned by
134 // requestBuffers when a with and height of zero is requested.
135 // A call to setDefaultBufferSize() may trigger requestBuffers() to
136 // be called from the client.
137 // The width and height parameters must be no greater than the minimum of
138 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
139 // An error due to invalid dimensions might not be reported until
140 // updateTexImage() is called.
141 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
142
143 // setFilteringEnabled sets whether the transform matrix should be computed
144 // for use with bilinear filtering.
145 void setFilteringEnabled(bool enabled);
146
147 // getCurrentBuffer returns the buffer associated with the current image.
148 // When outSlot is not nullptr, the current buffer slot index is also
149 // returned.
150 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
151
152 // getCurrentTextureTarget returns the texture target of the current
153 // texture as returned by updateTexImage().
154 uint32_t getCurrentTextureTarget() const;
155
156 // getCurrentCrop returns the cropping rectangle of the current buffer.
157 Rect getCurrentCrop() const;
158
159 // getCurrentTransform returns the transform of the current buffer.
160 uint32_t getCurrentTransform() const;
161
162 // getCurrentScalingMode returns the scaling mode of the current buffer.
163 uint32_t getCurrentScalingMode() const;
164
165 // getCurrentFence returns the fence indicating when the current buffer is
166 // ready to be read from.
167 sp<Fence> getCurrentFence() const;
168
169 // getCurrentFence returns the FenceTime indicating when the current
170 // buffer is ready to be read from.
171 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
172
173 // setConsumerUsageBits overrides the ConsumerBase method to OR
174 // DEFAULT_USAGE_FLAGS to usage.
175 status_t setConsumerUsageBits(uint64_t usage);
176
Chia-I Wuf1405182017-11-27 11:29:21 -0800177protected:
178 // abandonLocked overrides the ConsumerBase method to clear
179 // mCurrentTextureImage in addition to the ConsumerBase behavior.
180 virtual void abandonLocked();
181
182 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
183 // specific info in addition to the ConsumerBase behavior.
184 virtual void dumpLocked(String8& result, const char* prefix) const;
185
186 // acquireBufferLocked overrides the ConsumerBase method to update the
187 // mEglSlots array in addition to the ConsumerBase behavior.
188 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
189 uint64_t maxFrameNumber = 0) override;
190
191 // releaseBufferLocked overrides the ConsumerBase method to update the
192 // mEglSlots array in addition to the ConsumerBase.
193 virtual status_t releaseBufferLocked(int slot, const sp<GraphicBuffer> graphicBuffer,
194 EGLDisplay display, EGLSyncKHR eglFence) override;
195
196 status_t releaseBufferLocked(int slot, const sp<GraphicBuffer> graphicBuffer,
197 EGLSyncKHR eglFence) {
198 return releaseBufferLocked(slot, graphicBuffer, mEglDisplay, eglFence);
199 }
200
201 struct PendingRelease {
202 PendingRelease()
203 : isPending(false),
204 currentTexture(-1),
205 graphicBuffer(),
206 display(nullptr),
207 fence(nullptr) {}
208
209 bool isPending;
210 int currentTexture;
211 sp<GraphicBuffer> graphicBuffer;
212 EGLDisplay display;
213 EGLSyncKHR fence;
214 };
215
216 // This releases the buffer in the slot referenced by mCurrentTexture,
217 // then updates state to refer to the BufferItem, which must be a
218 // newly-acquired buffer. If pendingRelease is not null, the parameters
219 // which would have been passed to releaseBufferLocked upon the successful
220 // completion of the method will instead be returned to the caller, so that
221 // it may call releaseBufferLocked itself later.
222 status_t updateAndReleaseLocked(const BufferItem& item,
223 PendingRelease* pendingRelease = nullptr);
224
225 // Binds mTexName and the current buffer to mTexTarget. Uses
226 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
227 // bind succeeds, this calls doGLFenceWait.
228 status_t bindTextureImageLocked();
229
230 // Gets the current EGLDisplay and EGLContext values, and compares them
231 // to mEglDisplay and mEglContext. If the fields have been previously
232 // set, the values must match; if not, the fields are set to the current
233 // values.
Chia-I Wuc91077c2017-11-27 13:32:04 -0800234 status_t checkAndUpdateEglStateLocked();
Chia-I Wuf1405182017-11-27 11:29:21 -0800235
236private:
237 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
238 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800239 // - After freeBuffer, we must still keep the current image/buffer
240 // Reference counting EGLImages lets us handle all these cases easily while
241 // also only creating new EGLImages from buffers when required.
242 class EglImage : public LightRefBase<EglImage> {
243 public:
244 EglImage(sp<GraphicBuffer> graphicBuffer);
245
246 // createIfNeeded creates an EGLImage if required (we haven't created
247 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800248 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800249
250 // This calls glEGLImageTargetTexture2DOES to bind the image to the
251 // texture in the specified texture target.
252 void bindToTextureTarget(uint32_t texTarget);
253
254 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
255 const native_handle* graphicBufferHandle() {
256 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
257 }
258
259 private:
260 // Only allow instantiation using ref counting.
261 friend class LightRefBase<EglImage>;
262 virtual ~EglImage();
263
264 // createImage creates a new EGLImage from a GraphicBuffer.
265 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
266 const Rect& crop);
267
268 // Disallow copying
269 EglImage(const EglImage& rhs);
270 void operator=(const EglImage& rhs);
271
272 // mGraphicBuffer is the buffer that was used to create this image.
273 sp<GraphicBuffer> mGraphicBuffer;
274
275 // mEglImage is the EGLImage created from mGraphicBuffer.
276 EGLImageKHR mEglImage;
277
278 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
279 EGLDisplay mEglDisplay;
280
281 // mCropRect is the crop rectangle passed to EGL when mEglImage
282 // was created.
283 Rect mCropRect;
284 };
285
286 // freeBufferLocked frees up the given buffer slot. If the slot has been
287 // initialized this will release the reference to the GraphicBuffer in that
288 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
289 //
290 // This method must be called with mMutex locked.
291 virtual void freeBufferLocked(int slotIndex);
292
293 // computeCurrentTransformMatrixLocked computes the transform matrix for the
294 // current texture. It uses mCurrentTransform and the current GraphicBuffer
295 // to compute this matrix and stores it in mCurrentTransformMatrix.
296 // mCurrentTextureImage must not be NULL.
297 void computeCurrentTransformMatrixLocked();
298
299 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
300 // stream to ensure that it is safe for future OpenGL ES commands to
301 // access the current texture buffer.
302 status_t doGLFenceWaitLocked() const;
303
304 // syncForReleaseLocked performs the synchronization needed to release the
305 // current slot from an OpenGL ES context. If needed it will set the
306 // current slot's fence to guard against a producer accessing the buffer
307 // before the outstanding accesses have completed.
308 status_t syncForReleaseLocked(EGLDisplay dpy);
309
Chia-I Wuf1405182017-11-27 11:29:21 -0800310 // The default consumer usage flags that BufferLayerConsumer always sets on its
311 // BufferQueue instance; these will be OR:d with any additional flags passed
312 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
313 // consume buffers as hardware textures.
314 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
315
316 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
317 // possible that this buffer is not associated with any buffer slot, so we
318 // must track it separately in order to support the getCurrentBuffer method.
319 sp<EglImage> mCurrentTextureImage;
320
321 // mCurrentCrop is the crop rectangle that applies to the current texture.
322 // It gets set each time updateTexImage is called.
323 Rect mCurrentCrop;
324
325 // mCurrentTransform is the transform identifier for the current texture. It
326 // gets set each time updateTexImage is called.
327 uint32_t mCurrentTransform;
328
329 // mCurrentScalingMode is the scaling mode for the current texture. It gets
330 // set each time updateTexImage is called.
331 uint32_t mCurrentScalingMode;
332
333 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
334 sp<Fence> mCurrentFence;
335
336 // The FenceTime wrapper around mCurrentFence.
337 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
338
339 // mCurrentTransformMatrix is the transform matrix for the current texture.
340 // It gets computed by computeTransformMatrix each time updateTexImage is
341 // called.
342 float mCurrentTransformMatrix[16];
343
344 // mCurrentTimestamp is the timestamp for the current texture. It
345 // gets set each time updateTexImage is called.
346 int64_t mCurrentTimestamp;
347
348 // mCurrentDataSpace is the dataspace for the current texture. It
349 // gets set each time updateTexImage is called.
350 android_dataspace mCurrentDataSpace;
351
352 // mCurrentFrameNumber is the frame counter for the current texture.
353 // It gets set each time updateTexImage is called.
354 uint64_t mCurrentFrameNumber;
355
356 uint32_t mDefaultWidth, mDefaultHeight;
357
358 // mFilteringEnabled indicates whether the transform matrix is computed for
359 // use with bilinear filtering. It defaults to true and is changed by
360 // setFilteringEnabled().
361 bool mFilteringEnabled;
362
363 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800364 // be bound when updateTexImage is called. It is set at construction time.
365 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800366
367 // mUseFenceSync indicates whether creation of the EGL_KHR_fence_sync
368 // extension should be used to prevent buffers from being dequeued before
369 // it's safe for them to be written. It gets set at construction time and
370 // never changes.
371 const bool mUseFenceSync;
372
373 // mTexTarget is the GL texture target with which the GL texture object is
374 // associated. It is set in the constructor and never changed. It is
375 // almost always GL_TEXTURE_EXTERNAL_OES except for one use case in Android
376 // Browser. In that case it is set to GL_TEXTURE_2D to allow
377 // glCopyTexSubImage to read from the texture. This is a hack to work
378 // around a GL driver limitation on the number of FBO attachments, which the
379 // browser's tile cache exceeds.
380 const uint32_t mTexTarget;
381
382 // EGLSlot contains the information and object references that
383 // BufferLayerConsumer maintains about a BufferQueue buffer slot.
384 struct EglSlot {
385 EglSlot() : mEglFence(EGL_NO_SYNC_KHR) {}
386
387 // mEglImage is the EGLImage created from mGraphicBuffer.
388 sp<EglImage> mEglImage;
389
390 // mFence is the EGL sync object that must signal before the buffer
391 // associated with this buffer slot may be dequeued. It is initialized
392 // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
393 // on a compile-time option) set to a new sync object in updateTexImage.
394 EGLSyncKHR mEglFence;
395 };
396
397 // mEglDisplay is the EGLDisplay with which this BufferLayerConsumer is currently
398 // associated. It is intialized to EGL_NO_DISPLAY and gets set to the
Chia-I Wuc91077c2017-11-27 13:32:04 -0800399 // current display when updateTexImage is called for the first time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800400 EGLDisplay mEglDisplay;
401
402 // mEglContext is the OpenGL ES context with which this BufferLayerConsumer is
403 // currently associated. It is initialized to EGL_NO_CONTEXT and gets set
404 // to the current GL context when updateTexImage is called for the first
Chia-I Wuc91077c2017-11-27 13:32:04 -0800405 // time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800406 EGLContext mEglContext;
407
408 // mEGLSlots stores the buffers that have been allocated by the BufferQueue
409 // for each buffer slot. It is initialized to null pointers, and gets
410 // filled in with the result of BufferQueue::acquire when the
411 // client dequeues a buffer from a
412 // slot that has not yet been used. The buffer allocated to a slot will also
413 // be replaced if the requested buffer usage or geometry differs from that
414 // of the buffer allocated to a slot.
415 EglSlot mEglSlots[BufferQueueDefs::NUM_BUFFER_SLOTS];
416
417 // mCurrentTexture is the buffer slot index of the buffer that is currently
418 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
419 // indicating that no buffer slot is currently bound to the texture. Note,
420 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
421 // that no buffer is bound to the texture. A call to setBufferCount will
422 // reset mCurrentTexture to INVALID_BUFFER_SLOT.
423 int mCurrentTexture;
Chia-I Wuf1405182017-11-27 11:29:21 -0800424};
425
426// ----------------------------------------------------------------------------
427}; // namespace android
428
429#endif // ANDROID_BUFFERLAYERCONSUMER_H