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