blob: f8da6bf0ae882356df0ba24600e858c00dea2ddc [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 Wuf1405182017-11-27 11:29:21 -080057 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 Wubd854bf2017-11-27 13:41:26 -080061 // texture to which images are to be streamed.
Chia-I Wuc75c44d2017-11-27 14:32:57 -080062 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex, Layer* layer);
Chia-I Wuf1405182017-11-27 11:29:21 -080063
Chia-I Wuf1405182017-11-27 11:29:21 -080064 // updateTexImage acquires the most recently queued buffer, and sets the
65 // image contents of the target texture to it.
66 //
67 // This call may only be made while the OpenGL ES context to which the
68 // target texture belongs is bound to the calling thread.
69 //
70 // This calls doGLFenceWait to ensure proper synchronization.
71 status_t updateTexImage();
72
Chia-I Wuf1405182017-11-27 11:29:21 -080073 // setReleaseFence stores a fence that will signal when the current buffer
74 // is no longer being read. This fence will be returned to the producer
75 // when the current buffer is released by updateTexImage(). Multiple
76 // fences can be set for a given buffer; they will be merged into a single
77 // union fence.
78 virtual void setReleaseFence(const sp<Fence>& fence);
79
80 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
81 // associated with the texture image set by the most recent call to
82 // updateTexImage.
83 //
84 // This transform matrix maps 2D homogeneous texture coordinates of the form
85 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
86 // coordinate that should be used to sample that location from the texture.
87 // Sampling the texture outside of the range of this transform is undefined.
88 //
89 // This transform is necessary to compensate for transforms that the stream
90 // content producer may implicitly apply to the content. By forcing users of
91 // a BufferLayerConsumer to apply this transform we avoid performing an extra
92 // copy of the data that would be needed to hide the transform from the
93 // user.
94 //
95 // The matrix is stored in column-major order so that it may be passed
96 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
97 // functions.
98 void getTransformMatrix(float mtx[16]);
99
Chia-I Wuf1405182017-11-27 11:29:21 -0800100 // getTimestamp retrieves the timestamp associated with the texture image
101 // set by the most recent call to updateTexImage.
102 //
103 // The timestamp is in nanoseconds, and is monotonically increasing. Its
104 // other semantics (zero point, etc) are source-dependent and should be
105 // documented by the source.
106 int64_t getTimestamp();
107
108 // getDataSpace retrieves the DataSpace associated with the texture image
109 // set by the most recent call to updateTexImage.
110 android_dataspace getCurrentDataSpace();
111
112 // getFrameNumber retrieves the frame number associated with the texture
113 // image set by the most recent call to updateTexImage.
114 //
115 // The frame number is an incrementing counter set to 0 at the creation of
116 // the BufferQueue associated with this consumer.
117 uint64_t getFrameNumber();
118
119 // setDefaultBufferSize is used to set the size of buffers returned by
120 // requestBuffers when a with and height of zero is requested.
121 // A call to setDefaultBufferSize() may trigger requestBuffers() to
122 // be called from the client.
123 // The width and height parameters must be no greater than the minimum of
124 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
125 // An error due to invalid dimensions might not be reported until
126 // updateTexImage() is called.
127 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
128
129 // setFilteringEnabled sets whether the transform matrix should be computed
130 // for use with bilinear filtering.
131 void setFilteringEnabled(bool enabled);
132
133 // getCurrentBuffer returns the buffer associated with the current image.
134 // When outSlot is not nullptr, the current buffer slot index is also
135 // returned.
136 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
137
Chia-I Wuf1405182017-11-27 11:29:21 -0800138 // getCurrentCrop returns the cropping rectangle of the current buffer.
139 Rect getCurrentCrop() const;
140
141 // getCurrentTransform returns the transform of the current buffer.
142 uint32_t getCurrentTransform() const;
143
144 // getCurrentScalingMode returns the scaling mode of the current buffer.
145 uint32_t getCurrentScalingMode() const;
146
147 // getCurrentFence returns the fence indicating when the current buffer is
148 // ready to be read from.
149 sp<Fence> getCurrentFence() const;
150
151 // getCurrentFence returns the FenceTime indicating when the current
152 // buffer is ready to be read from.
153 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
154
155 // setConsumerUsageBits overrides the ConsumerBase method to OR
156 // DEFAULT_USAGE_FLAGS to usage.
157 status_t setConsumerUsageBits(uint64_t usage);
158
Chia-I Wuf1405182017-11-27 11:29:21 -0800159protected:
160 // abandonLocked overrides the ConsumerBase method to clear
161 // mCurrentTextureImage in addition to the ConsumerBase behavior.
162 virtual void abandonLocked();
163
164 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
165 // specific info in addition to the ConsumerBase behavior.
166 virtual void dumpLocked(String8& result, const char* prefix) const;
167
168 // acquireBufferLocked overrides the ConsumerBase method to update the
169 // mEglSlots array in addition to the ConsumerBase behavior.
170 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
171 uint64_t maxFrameNumber = 0) override;
172
Chia-I Wuf1405182017-11-27 11:29:21 -0800173 struct PendingRelease {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800174 PendingRelease() : isPending(false), currentTexture(-1), graphicBuffer() {}
Chia-I Wuf1405182017-11-27 11:29:21 -0800175
176 bool isPending;
177 int currentTexture;
178 sp<GraphicBuffer> graphicBuffer;
Chia-I Wuf1405182017-11-27 11:29:21 -0800179 };
180
181 // This releases the buffer in the slot referenced by mCurrentTexture,
182 // then updates state to refer to the BufferItem, which must be a
183 // newly-acquired buffer. If pendingRelease is not null, the parameters
184 // which would have been passed to releaseBufferLocked upon the successful
185 // completion of the method will instead be returned to the caller, so that
186 // it may call releaseBufferLocked itself later.
187 status_t updateAndReleaseLocked(const BufferItem& item,
188 PendingRelease* pendingRelease = nullptr);
189
Chia-I Wubd854bf2017-11-27 13:41:26 -0800190 // Binds mTexName and the current buffer to sTexTarget. Uses
Chia-I Wuf1405182017-11-27 11:29:21 -0800191 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
192 // bind succeeds, this calls doGLFenceWait.
193 status_t bindTextureImageLocked();
194
195 // Gets the current EGLDisplay and EGLContext values, and compares them
196 // to mEglDisplay and mEglContext. If the fields have been previously
197 // set, the values must match; if not, the fields are set to the current
198 // values.
Chia-I Wuc91077c2017-11-27 13:32:04 -0800199 status_t checkAndUpdateEglStateLocked();
Chia-I Wuf1405182017-11-27 11:29:21 -0800200
201private:
202 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
203 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800204 // - After freeBuffer, we must still keep the current image/buffer
205 // Reference counting EGLImages lets us handle all these cases easily while
206 // also only creating new EGLImages from buffers when required.
207 class EglImage : public LightRefBase<EglImage> {
208 public:
209 EglImage(sp<GraphicBuffer> graphicBuffer);
210
211 // createIfNeeded creates an EGLImage if required (we haven't created
212 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800213 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800214
215 // This calls glEGLImageTargetTexture2DOES to bind the image to the
216 // texture in the specified texture target.
217 void bindToTextureTarget(uint32_t texTarget);
218
219 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
220 const native_handle* graphicBufferHandle() {
221 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
222 }
223
224 private:
225 // Only allow instantiation using ref counting.
226 friend class LightRefBase<EglImage>;
227 virtual ~EglImage();
228
229 // createImage creates a new EGLImage from a GraphicBuffer.
230 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
231 const Rect& crop);
232
233 // Disallow copying
234 EglImage(const EglImage& rhs);
235 void operator=(const EglImage& rhs);
236
237 // mGraphicBuffer is the buffer that was used to create this image.
238 sp<GraphicBuffer> mGraphicBuffer;
239
240 // mEglImage is the EGLImage created from mGraphicBuffer.
241 EGLImageKHR mEglImage;
242
243 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
244 EGLDisplay mEglDisplay;
245
246 // mCropRect is the crop rectangle passed to EGL when mEglImage
247 // was created.
248 Rect mCropRect;
249 };
250
251 // freeBufferLocked frees up the given buffer slot. If the slot has been
252 // initialized this will release the reference to the GraphicBuffer in that
253 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
254 //
255 // This method must be called with mMutex locked.
256 virtual void freeBufferLocked(int slotIndex);
257
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800258 // IConsumerListener interface
259 void onDisconnect() override;
260 void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
261 FrameEventHistoryDelta* outDelta) override;
262
Chia-I Wuf1405182017-11-27 11:29:21 -0800263 // computeCurrentTransformMatrixLocked computes the transform matrix for the
264 // current texture. It uses mCurrentTransform and the current GraphicBuffer
265 // to compute this matrix and stores it in mCurrentTransformMatrix.
266 // mCurrentTextureImage must not be NULL.
267 void computeCurrentTransformMatrixLocked();
268
269 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
270 // stream to ensure that it is safe for future OpenGL ES commands to
271 // access the current texture buffer.
272 status_t doGLFenceWaitLocked() const;
273
274 // syncForReleaseLocked performs the synchronization needed to release the
275 // current slot from an OpenGL ES context. If needed it will set the
276 // current slot's fence to guard against a producer accessing the buffer
277 // before the outstanding accesses have completed.
278 status_t syncForReleaseLocked(EGLDisplay dpy);
279
Chia-I Wubd854bf2017-11-27 13:41:26 -0800280 // sTexTarget is the GL texture target with which the GL texture object is
281 // associated.
282 static constexpr uint32_t sTexTarget = 0x8D65; // GL_TEXTURE_EXTERNAL_OES
283
Chia-I Wuf1405182017-11-27 11:29:21 -0800284 // The default consumer usage flags that BufferLayerConsumer always sets on its
285 // BufferQueue instance; these will be OR:d with any additional flags passed
286 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
287 // consume buffers as hardware textures.
288 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
289
290 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
291 // possible that this buffer is not associated with any buffer slot, so we
292 // must track it separately in order to support the getCurrentBuffer method.
293 sp<EglImage> mCurrentTextureImage;
294
295 // mCurrentCrop is the crop rectangle that applies to the current texture.
296 // It gets set each time updateTexImage is called.
297 Rect mCurrentCrop;
298
299 // mCurrentTransform is the transform identifier for the current texture. It
300 // gets set each time updateTexImage is called.
301 uint32_t mCurrentTransform;
302
303 // mCurrentScalingMode is the scaling mode for the current texture. It gets
304 // set each time updateTexImage is called.
305 uint32_t mCurrentScalingMode;
306
307 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
308 sp<Fence> mCurrentFence;
309
310 // The FenceTime wrapper around mCurrentFence.
311 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
312
313 // mCurrentTransformMatrix is the transform matrix for the current texture.
314 // It gets computed by computeTransformMatrix each time updateTexImage is
315 // called.
316 float mCurrentTransformMatrix[16];
317
318 // mCurrentTimestamp is the timestamp for the current texture. It
319 // gets set each time updateTexImage is called.
320 int64_t mCurrentTimestamp;
321
322 // mCurrentDataSpace is the dataspace for the current texture. It
323 // gets set each time updateTexImage is called.
324 android_dataspace mCurrentDataSpace;
325
326 // mCurrentFrameNumber is the frame counter for the current texture.
327 // It gets set each time updateTexImage is called.
328 uint64_t mCurrentFrameNumber;
329
330 uint32_t mDefaultWidth, mDefaultHeight;
331
332 // mFilteringEnabled indicates whether the transform matrix is computed for
333 // use with bilinear filtering. It defaults to true and is changed by
334 // setFilteringEnabled().
335 bool mFilteringEnabled;
336
337 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800338 // be bound when updateTexImage is called. It is set at construction time.
339 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800340
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800341 // The layer for this BufferLayerConsumer
342 const wp<Layer> mLayer;
343
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