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