blob: 0da73d1ffe8a14d647c39562f82c3c603f36e6bb [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 Wuda5c7302017-11-27 14:51:06 -080036class DispSync;
Chia-I Wuc75c44d2017-11-27 14:32:57 -080037class Layer;
Chia-I Wuf1405182017-11-27 11:29:21 -080038class String8;
39
40/*
41 * BufferLayerConsumer consumes buffers of graphics data from a BufferQueue,
42 * and makes them available to OpenGL as a texture.
43 *
44 * A typical usage pattern is to set up the BufferLayerConsumer with the
45 * desired options, and call updateTexImage() when a new frame is desired.
46 * If a new frame is available, the texture will be updated. If not,
47 * the previous contents are retained.
48 *
Chia-I Wuc91077c2017-11-27 13:32:04 -080049 * The texture is attached to the GL_TEXTURE_EXTERNAL_OES texture target, in
50 * the EGL context of the first thread that calls updateTexImage(). After that
51 * point, all calls to updateTexImage must be made with the same OpenGL ES
52 * context current.
Chia-I Wuf1405182017-11-27 11:29:21 -080053 *
54 * This class was previously called SurfaceTexture.
55 */
56class BufferLayerConsumer : public ConsumerBase {
57public:
Chia-I Wuda5c7302017-11-27 14:51:06 -080058 static const status_t BUFFER_REJECTED = UNKNOWN_ERROR + 8;
59
60 class BufferRejecter {
61 friend class BufferLayerConsumer;
62 virtual bool reject(const sp<GraphicBuffer>& buf, const BufferItem& item) = 0;
63
64 protected:
65 virtual ~BufferRejecter() {}
66 };
67
Chia-I Wufd257f82017-11-27 14:51:06 -080068 struct ContentsChangedListener : public FrameAvailableListener {
69 virtual void onSidebandStreamChanged() = 0;
70 };
Chia-I Wuf1405182017-11-27 11:29:21 -080071
Chia-I Wuc91077c2017-11-27 13:32:04 -080072 // BufferLayerConsumer constructs a new BufferLayerConsumer object.
73 // The tex parameter indicates the name of the OpenGL ES
Chia-I Wubd854bf2017-11-27 13:41:26 -080074 // texture to which images are to be streamed.
Chia-I Wuc75c44d2017-11-27 14:32:57 -080075 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex, Layer* layer);
Chia-I Wuf1405182017-11-27 11:29:21 -080076
Chia-I Wufd257f82017-11-27 14:51:06 -080077 // Sets the contents changed listener. This should be used instead of
78 // ConsumerBase::setFrameAvailableListener().
79 void setContentsChangedListener(const wp<ContentsChangedListener>& listener);
80
Chia-I Wuda5c7302017-11-27 14:51:06 -080081 nsecs_t computeExpectedPresent(const DispSync& dispSync);
82
Chia-I Wuf1405182017-11-27 11:29:21 -080083 // updateTexImage acquires the most recently queued buffer, and sets the
84 // image contents of the target texture to it.
85 //
86 // This call may only be made while the OpenGL ES context to which the
87 // target texture belongs is bound to the calling thread.
88 //
89 // This calls doGLFenceWait to ensure proper synchronization.
Chia-I Wuda5c7302017-11-27 14:51:06 -080090 //
91 // This version of updateTexImage() takes a functor that may be used to
92 // reject the newly acquired buffer. Unlike the GLConsumer version,
93 // this does not guarantee that the buffer has been bound to the GL
94 // texture.
95 status_t updateTexImage(BufferRejecter* rejecter, const DispSync& dispSync, bool* autoRefresh,
96 bool* queuedBuffer, uint64_t maxFrameNumber);
Chia-I Wuf1405182017-11-27 11:29:21 -080097
Chia-I Wuf1405182017-11-27 11:29:21 -080098 // setReleaseFence stores a fence that will signal when the current buffer
99 // is no longer being read. This fence will be returned to the producer
100 // when the current buffer is released by updateTexImage(). Multiple
101 // fences can be set for a given buffer; they will be merged into a single
102 // union fence.
Chia-I Wuda5c7302017-11-27 14:51:06 -0800103 void setReleaseFence(const sp<Fence>& fence);
104
105 bool releasePendingBuffer();
Chia-I Wuf1405182017-11-27 11:29:21 -0800106
107 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
108 // associated with the texture image set by the most recent call to
109 // updateTexImage.
110 //
111 // This transform matrix maps 2D homogeneous texture coordinates of the form
112 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
113 // coordinate that should be used to sample that location from the texture.
114 // Sampling the texture outside of the range of this transform is undefined.
115 //
116 // This transform is necessary to compensate for transforms that the stream
117 // content producer may implicitly apply to the content. By forcing users of
118 // a BufferLayerConsumer to apply this transform we avoid performing an extra
119 // copy of the data that would be needed to hide the transform from the
120 // user.
121 //
122 // The matrix is stored in column-major order so that it may be passed
123 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
124 // functions.
125 void getTransformMatrix(float mtx[16]);
126
Chia-I Wuf1405182017-11-27 11:29:21 -0800127 // getTimestamp retrieves the timestamp associated with the texture image
128 // set by the most recent call to updateTexImage.
129 //
130 // The timestamp is in nanoseconds, and is monotonically increasing. Its
131 // other semantics (zero point, etc) are source-dependent and should be
132 // documented by the source.
133 int64_t getTimestamp();
134
135 // getDataSpace retrieves the DataSpace associated with the texture image
136 // set by the most recent call to updateTexImage.
137 android_dataspace getCurrentDataSpace();
138
139 // getFrameNumber retrieves the frame number associated with the texture
140 // image set by the most recent call to updateTexImage.
141 //
142 // The frame number is an incrementing counter set to 0 at the creation of
143 // the BufferQueue associated with this consumer.
144 uint64_t getFrameNumber();
145
146 // setDefaultBufferSize is used to set the size of buffers returned by
147 // requestBuffers when a with and height of zero is requested.
148 // A call to setDefaultBufferSize() may trigger requestBuffers() to
149 // be called from the client.
150 // The width and height parameters must be no greater than the minimum of
151 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
152 // An error due to invalid dimensions might not be reported until
153 // updateTexImage() is called.
154 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
155
156 // setFilteringEnabled sets whether the transform matrix should be computed
157 // for use with bilinear filtering.
158 void setFilteringEnabled(bool enabled);
159
160 // getCurrentBuffer returns the buffer associated with the current image.
161 // When outSlot is not nullptr, the current buffer slot index is also
162 // returned.
163 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
164
Chia-I Wuf1405182017-11-27 11:29:21 -0800165 // getCurrentCrop returns the cropping rectangle of the current buffer.
166 Rect getCurrentCrop() const;
167
168 // getCurrentTransform returns the transform of the current buffer.
169 uint32_t getCurrentTransform() const;
170
171 // getCurrentScalingMode returns the scaling mode of the current buffer.
172 uint32_t getCurrentScalingMode() const;
173
174 // getCurrentFence returns the fence indicating when the current buffer is
175 // ready to be read from.
176 sp<Fence> getCurrentFence() const;
177
178 // getCurrentFence returns the FenceTime indicating when the current
179 // buffer is ready to be read from.
180 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
181
182 // setConsumerUsageBits overrides the ConsumerBase method to OR
183 // DEFAULT_USAGE_FLAGS to usage.
184 status_t setConsumerUsageBits(uint64_t usage);
185
Chia-I Wuf1405182017-11-27 11:29:21 -0800186protected:
187 // abandonLocked overrides the ConsumerBase method to clear
188 // mCurrentTextureImage in addition to the ConsumerBase behavior.
189 virtual void abandonLocked();
190
191 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
192 // specific info in addition to the ConsumerBase behavior.
193 virtual void dumpLocked(String8& result, const char* prefix) const;
194
195 // acquireBufferLocked overrides the ConsumerBase method to update the
196 // mEglSlots array in addition to the ConsumerBase behavior.
197 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
198 uint64_t maxFrameNumber = 0) override;
199
Chia-I Wuf1405182017-11-27 11:29:21 -0800200 struct PendingRelease {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800201 PendingRelease() : isPending(false), currentTexture(-1), graphicBuffer() {}
Chia-I Wuf1405182017-11-27 11:29:21 -0800202
203 bool isPending;
204 int currentTexture;
205 sp<GraphicBuffer> graphicBuffer;
Chia-I Wuf1405182017-11-27 11:29:21 -0800206 };
207
208 // This releases the buffer in the slot referenced by mCurrentTexture,
209 // then updates state to refer to the BufferItem, which must be a
210 // newly-acquired buffer. If pendingRelease is not null, the parameters
211 // which would have been passed to releaseBufferLocked upon the successful
212 // completion of the method will instead be returned to the caller, so that
213 // it may call releaseBufferLocked itself later.
214 status_t updateAndReleaseLocked(const BufferItem& item,
215 PendingRelease* pendingRelease = nullptr);
216
Chia-I Wubd854bf2017-11-27 13:41:26 -0800217 // Binds mTexName and the current buffer to sTexTarget. Uses
Chia-I Wuf1405182017-11-27 11:29:21 -0800218 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
219 // bind succeeds, this calls doGLFenceWait.
220 status_t bindTextureImageLocked();
221
222 // Gets the current EGLDisplay and EGLContext values, and compares them
223 // to mEglDisplay and mEglContext. If the fields have been previously
224 // set, the values must match; if not, the fields are set to the current
225 // values.
Chia-I Wuc91077c2017-11-27 13:32:04 -0800226 status_t checkAndUpdateEglStateLocked();
Chia-I Wuf1405182017-11-27 11:29:21 -0800227
228private:
229 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
230 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800231 // - After freeBuffer, we must still keep the current image/buffer
232 // Reference counting EGLImages lets us handle all these cases easily while
233 // also only creating new EGLImages from buffers when required.
234 class EglImage : public LightRefBase<EglImage> {
235 public:
236 EglImage(sp<GraphicBuffer> graphicBuffer);
237
238 // createIfNeeded creates an EGLImage if required (we haven't created
239 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800240 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800241
242 // This calls glEGLImageTargetTexture2DOES to bind the image to the
243 // texture in the specified texture target.
244 void bindToTextureTarget(uint32_t texTarget);
245
246 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
247 const native_handle* graphicBufferHandle() {
248 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
249 }
250
251 private:
252 // Only allow instantiation using ref counting.
253 friend class LightRefBase<EglImage>;
254 virtual ~EglImage();
255
256 // createImage creates a new EGLImage from a GraphicBuffer.
257 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
258 const Rect& crop);
259
260 // Disallow copying
261 EglImage(const EglImage& rhs);
262 void operator=(const EglImage& rhs);
263
264 // mGraphicBuffer is the buffer that was used to create this image.
265 sp<GraphicBuffer> mGraphicBuffer;
266
267 // mEglImage is the EGLImage created from mGraphicBuffer.
268 EGLImageKHR mEglImage;
269
270 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
271 EGLDisplay mEglDisplay;
272
273 // mCropRect is the crop rectangle passed to EGL when mEglImage
274 // was created.
275 Rect mCropRect;
276 };
277
278 // freeBufferLocked frees up the given buffer slot. If the slot has been
279 // initialized this will release the reference to the GraphicBuffer in that
280 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
281 //
282 // This method must be called with mMutex locked.
283 virtual void freeBufferLocked(int slotIndex);
284
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800285 // IConsumerListener interface
286 void onDisconnect() override;
Chia-I Wufd257f82017-11-27 14:51:06 -0800287 void onSidebandStreamChanged() override;
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800288 void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
289 FrameEventHistoryDelta* outDelta) override;
290
Chia-I Wuf1405182017-11-27 11:29:21 -0800291 // computeCurrentTransformMatrixLocked computes the transform matrix for the
292 // current texture. It uses mCurrentTransform and the current GraphicBuffer
293 // to compute this matrix and stores it in mCurrentTransformMatrix.
294 // mCurrentTextureImage must not be NULL.
295 void computeCurrentTransformMatrixLocked();
296
297 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
298 // stream to ensure that it is safe for future OpenGL ES commands to
299 // access the current texture buffer.
300 status_t doGLFenceWaitLocked() const;
301
302 // syncForReleaseLocked performs the synchronization needed to release the
303 // current slot from an OpenGL ES context. If needed it will set the
304 // current slot's fence to guard against a producer accessing the buffer
305 // before the outstanding accesses have completed.
306 status_t syncForReleaseLocked(EGLDisplay dpy);
307
Chia-I Wubd854bf2017-11-27 13:41:26 -0800308 // sTexTarget is the GL texture target with which the GL texture object is
309 // associated.
310 static constexpr uint32_t sTexTarget = 0x8D65; // GL_TEXTURE_EXTERNAL_OES
311
Chia-I Wuf1405182017-11-27 11:29:21 -0800312 // The default consumer usage flags that BufferLayerConsumer always sets on its
313 // BufferQueue instance; these will be OR:d with any additional flags passed
314 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
315 // consume buffers as hardware textures.
316 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
317
318 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
319 // possible that this buffer is not associated with any buffer slot, so we
320 // must track it separately in order to support the getCurrentBuffer method.
321 sp<EglImage> mCurrentTextureImage;
322
323 // mCurrentCrop is the crop rectangle that applies to the current texture.
324 // It gets set each time updateTexImage is called.
325 Rect mCurrentCrop;
326
327 // mCurrentTransform is the transform identifier for the current texture. It
328 // gets set each time updateTexImage is called.
329 uint32_t mCurrentTransform;
330
331 // mCurrentScalingMode is the scaling mode for the current texture. It gets
332 // set each time updateTexImage is called.
333 uint32_t mCurrentScalingMode;
334
335 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
336 sp<Fence> mCurrentFence;
337
338 // The FenceTime wrapper around mCurrentFence.
339 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
340
341 // mCurrentTransformMatrix is the transform matrix for the current texture.
342 // It gets computed by computeTransformMatrix each time updateTexImage is
343 // called.
344 float mCurrentTransformMatrix[16];
345
346 // mCurrentTimestamp is the timestamp for the current texture. It
347 // gets set each time updateTexImage is called.
348 int64_t mCurrentTimestamp;
349
350 // mCurrentDataSpace is the dataspace for the current texture. It
351 // gets set each time updateTexImage is called.
352 android_dataspace mCurrentDataSpace;
353
354 // mCurrentFrameNumber is the frame counter for the current texture.
355 // It gets set each time updateTexImage is called.
356 uint64_t mCurrentFrameNumber;
357
358 uint32_t mDefaultWidth, mDefaultHeight;
359
360 // mFilteringEnabled indicates whether the transform matrix is computed for
361 // use with bilinear filtering. It defaults to true and is changed by
362 // setFilteringEnabled().
363 bool mFilteringEnabled;
364
365 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800366 // be bound when updateTexImage is called. It is set at construction time.
367 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800368
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800369 // The layer for this BufferLayerConsumer
370 const wp<Layer> mLayer;
371
Chia-I Wufd257f82017-11-27 14:51:06 -0800372 wp<ContentsChangedListener> mContentsChangedListener;
373
Chia-I Wuf1405182017-11-27 11:29:21 -0800374 // EGLSlot contains the information and object references that
375 // BufferLayerConsumer maintains about a BufferQueue buffer slot.
376 struct EglSlot {
Chia-I Wuf1405182017-11-27 11:29:21 -0800377 // mEglImage is the EGLImage created from mGraphicBuffer.
378 sp<EglImage> mEglImage;
Chia-I Wuf1405182017-11-27 11:29:21 -0800379 };
380
381 // mEglDisplay is the EGLDisplay with which this BufferLayerConsumer is currently
382 // associated. It is intialized to EGL_NO_DISPLAY and gets set to the
Chia-I Wuc91077c2017-11-27 13:32:04 -0800383 // current display when updateTexImage is called for the first time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800384 EGLDisplay mEglDisplay;
385
386 // mEglContext is the OpenGL ES context with which this BufferLayerConsumer is
387 // currently associated. It is initialized to EGL_NO_CONTEXT and gets set
388 // to the current GL context when updateTexImage is called for the first
Chia-I Wuc91077c2017-11-27 13:32:04 -0800389 // time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800390 EGLContext mEglContext;
391
392 // mEGLSlots stores the buffers that have been allocated by the BufferQueue
393 // for each buffer slot. It is initialized to null pointers, and gets
394 // filled in with the result of BufferQueue::acquire when the
395 // client dequeues a buffer from a
396 // slot that has not yet been used. The buffer allocated to a slot will also
397 // be replaced if the requested buffer usage or geometry differs from that
398 // of the buffer allocated to a slot.
399 EglSlot mEglSlots[BufferQueueDefs::NUM_BUFFER_SLOTS];
400
401 // mCurrentTexture is the buffer slot index of the buffer that is currently
402 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
403 // indicating that no buffer slot is currently bound to the texture. Note,
404 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
405 // that no buffer is bound to the texture. A call to setBufferCount will
406 // reset mCurrentTexture to INVALID_BUFFER_SLOT.
407 int mCurrentTexture;
Chia-I Wuda5c7302017-11-27 14:51:06 -0800408
409 // A release that is pending on the receipt of a new release fence from
410 // presentDisplay
411 PendingRelease mPendingRelease;
Chia-I Wuf1405182017-11-27 11:29:21 -0800412};
413
414// ----------------------------------------------------------------------------
415}; // namespace android
416
417#endif // ANDROID_BUFFERLAYERCONSUMER_H