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