blob: cc35a66f240f0206f81296f107d9e1c8d3a25d2b [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>
Chia-I Wu67dcc692017-11-27 14:51:06 -080028#include <ui/Region.h>
Chia-I Wuf1405182017-11-27 11:29:21 -080029
30#include <utils/String8.h>
31#include <utils/Vector.h>
32#include <utils/threads.h>
33
34namespace android {
35// ----------------------------------------------------------------------------
36
Chia-I Wuda5c7302017-11-27 14:51:06 -080037class DispSync;
Chia-I Wuc75c44d2017-11-27 14:32:57 -080038class Layer;
Chia-I Wuf1405182017-11-27 11:29:21 -080039class String8;
40
41/*
42 * BufferLayerConsumer consumes buffers of graphics data from a BufferQueue,
43 * and makes them available to OpenGL as a texture.
44 *
45 * A typical usage pattern is to set up the BufferLayerConsumer with the
46 * desired options, and call updateTexImage() when a new frame is desired.
47 * If a new frame is available, the texture will be updated. If not,
48 * the previous contents are retained.
49 *
Chia-I Wuc91077c2017-11-27 13:32:04 -080050 * The texture is attached to the GL_TEXTURE_EXTERNAL_OES texture target, in
51 * the EGL context of the first thread that calls updateTexImage(). After that
52 * point, all calls to updateTexImage must be made with the same OpenGL ES
53 * context current.
Chia-I Wuf1405182017-11-27 11:29:21 -080054 *
55 * This class was previously called SurfaceTexture.
56 */
57class BufferLayerConsumer : public ConsumerBase {
58public:
Chia-I Wuda5c7302017-11-27 14:51:06 -080059 static const status_t BUFFER_REJECTED = UNKNOWN_ERROR + 8;
60
61 class BufferRejecter {
62 friend class BufferLayerConsumer;
63 virtual bool reject(const sp<GraphicBuffer>& buf, const BufferItem& item) = 0;
64
65 protected:
66 virtual ~BufferRejecter() {}
67 };
68
Chia-I Wufd257f82017-11-27 14:51:06 -080069 struct ContentsChangedListener : public FrameAvailableListener {
70 virtual void onSidebandStreamChanged() = 0;
71 };
Chia-I Wuf1405182017-11-27 11:29:21 -080072
Chia-I Wuc91077c2017-11-27 13:32:04 -080073 // BufferLayerConsumer constructs a new BufferLayerConsumer object.
74 // The tex parameter indicates the name of the OpenGL ES
Chia-I Wubd854bf2017-11-27 13:41:26 -080075 // texture to which images are to be streamed.
Chia-I Wuc75c44d2017-11-27 14:32:57 -080076 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex, Layer* layer);
Chia-I Wuf1405182017-11-27 11:29:21 -080077
Chia-I Wufd257f82017-11-27 14:51:06 -080078 // Sets the contents changed listener. This should be used instead of
79 // ConsumerBase::setFrameAvailableListener().
80 void setContentsChangedListener(const wp<ContentsChangedListener>& listener);
81
Chia-I Wuda5c7302017-11-27 14:51:06 -080082 nsecs_t computeExpectedPresent(const DispSync& dispSync);
83
Chia-I Wuf1405182017-11-27 11:29:21 -080084 // updateTexImage acquires the most recently queued buffer, and sets the
85 // image contents of the target texture to it.
86 //
87 // This call may only be made while the OpenGL ES context to which the
88 // target texture belongs is bound to the calling thread.
89 //
90 // This calls doGLFenceWait to ensure proper synchronization.
Chia-I Wuda5c7302017-11-27 14:51:06 -080091 //
92 // This version of updateTexImage() takes a functor that may be used to
93 // reject the newly acquired buffer. Unlike the GLConsumer version,
94 // this does not guarantee that the buffer has been bound to the GL
95 // texture.
96 status_t updateTexImage(BufferRejecter* rejecter, const DispSync& dispSync, bool* autoRefresh,
97 bool* queuedBuffer, uint64_t maxFrameNumber);
Chia-I Wuf1405182017-11-27 11:29:21 -080098
Chia-I Wu0cb75ac2017-11-27 15:56:04 -080099 // See BufferLayerConsumer::bindTextureImageLocked().
100 status_t bindTextureImage();
101
Chia-I Wuf1405182017-11-27 11:29:21 -0800102 // setReleaseFence stores a fence that will signal when the current buffer
103 // is no longer being read. This fence will be returned to the producer
104 // when the current buffer is released by updateTexImage(). Multiple
105 // fences can be set for a given buffer; they will be merged into a single
106 // union fence.
Chia-I Wuda5c7302017-11-27 14:51:06 -0800107 void setReleaseFence(const sp<Fence>& fence);
108
109 bool releasePendingBuffer();
Chia-I Wuf1405182017-11-27 11:29:21 -0800110
Chia-I Wu0cb75ac2017-11-27 15:56:04 -0800111 sp<Fence> getPrevFinalReleaseFence() const;
112
Chia-I Wuf1405182017-11-27 11:29:21 -0800113 // 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
Chia-I Wuf1405182017-11-27 11:29:21 -0800133 // getTimestamp retrieves the timestamp associated with the texture image
134 // set by the most recent call to updateTexImage.
135 //
136 // The timestamp is in nanoseconds, and is monotonically increasing. Its
137 // other semantics (zero point, etc) are source-dependent and should be
138 // documented by the source.
139 int64_t getTimestamp();
140
141 // getDataSpace retrieves the DataSpace associated with the texture image
142 // set by the most recent call to updateTexImage.
143 android_dataspace getCurrentDataSpace();
144
145 // getFrameNumber retrieves the frame number associated with the texture
146 // image set by the most recent call to updateTexImage.
147 //
148 // The frame number is an incrementing counter set to 0 at the creation of
149 // the BufferQueue associated with this consumer.
150 uint64_t getFrameNumber();
151
Chia-I Wu67dcc692017-11-27 14:51:06 -0800152 bool getTransformToDisplayInverse() const;
153
154 // must be called from SF main thread
155 const Region& getSurfaceDamage() const;
156
Chia-I Wuf1405182017-11-27 11:29:21 -0800157 // setDefaultBufferSize is used to set the size of buffers returned by
158 // requestBuffers when a with and height of zero is requested.
159 // A call to setDefaultBufferSize() may trigger requestBuffers() to
160 // be called from the client.
161 // The width and height parameters must be no greater than the minimum of
162 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
163 // An error due to invalid dimensions might not be reported until
164 // updateTexImage() is called.
165 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
166
167 // setFilteringEnabled sets whether the transform matrix should be computed
168 // for use with bilinear filtering.
169 void setFilteringEnabled(bool enabled);
170
171 // getCurrentBuffer returns the buffer associated with the current image.
172 // When outSlot is not nullptr, the current buffer slot index is also
173 // returned.
174 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
175
Chia-I Wuf1405182017-11-27 11:29:21 -0800176 // 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 // getCurrentFence returns the FenceTime indicating when the current
190 // buffer is ready to be read from.
191 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
192
193 // setConsumerUsageBits overrides the ConsumerBase method to OR
194 // DEFAULT_USAGE_FLAGS to usage.
195 status_t setConsumerUsageBits(uint64_t usage);
196
Chia-I Wuf1405182017-11-27 11:29:21 -0800197protected:
198 // abandonLocked overrides the ConsumerBase method to clear
199 // mCurrentTextureImage in addition to the ConsumerBase behavior.
200 virtual void abandonLocked();
201
202 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
203 // specific info in addition to the ConsumerBase behavior.
204 virtual void dumpLocked(String8& result, const char* prefix) const;
205
206 // acquireBufferLocked overrides the ConsumerBase method to update the
207 // mEglSlots array in addition to the ConsumerBase behavior.
208 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
209 uint64_t maxFrameNumber = 0) override;
210
Chia-I Wuf1405182017-11-27 11:29:21 -0800211 struct PendingRelease {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800212 PendingRelease() : isPending(false), currentTexture(-1), graphicBuffer() {}
Chia-I Wuf1405182017-11-27 11:29:21 -0800213
214 bool isPending;
215 int currentTexture;
216 sp<GraphicBuffer> graphicBuffer;
Chia-I Wuf1405182017-11-27 11:29:21 -0800217 };
218
219 // This releases the buffer in the slot referenced by mCurrentTexture,
220 // then updates state to refer to the BufferItem, which must be a
221 // newly-acquired buffer. If pendingRelease is not null, the parameters
222 // which would have been passed to releaseBufferLocked upon the successful
223 // completion of the method will instead be returned to the caller, so that
224 // it may call releaseBufferLocked itself later.
225 status_t updateAndReleaseLocked(const BufferItem& item,
226 PendingRelease* pendingRelease = nullptr);
227
Chia-I Wubd854bf2017-11-27 13:41:26 -0800228 // Binds mTexName and the current buffer to sTexTarget. Uses
Chia-I Wuf1405182017-11-27 11:29:21 -0800229 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
230 // bind succeeds, this calls doGLFenceWait.
231 status_t bindTextureImageLocked();
232
233 // Gets the current EGLDisplay and EGLContext values, and compares them
234 // to mEglDisplay and mEglContext. If the fields have been previously
235 // set, the values must match; if not, the fields are set to the current
236 // values.
Chia-I Wuc91077c2017-11-27 13:32:04 -0800237 status_t checkAndUpdateEglStateLocked();
Chia-I Wuf1405182017-11-27 11:29:21 -0800238
239private:
240 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
241 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800242 // - After freeBuffer, we must still keep the current image/buffer
243 // Reference counting EGLImages lets us handle all these cases easily while
244 // also only creating new EGLImages from buffers when required.
245 class EglImage : public LightRefBase<EglImage> {
246 public:
247 EglImage(sp<GraphicBuffer> graphicBuffer);
248
249 // createIfNeeded creates an EGLImage if required (we haven't created
250 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800251 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800252
253 // This calls glEGLImageTargetTexture2DOES to bind the image to the
254 // texture in the specified texture target.
255 void bindToTextureTarget(uint32_t texTarget);
256
257 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
258 const native_handle* graphicBufferHandle() {
259 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
260 }
261
262 private:
263 // Only allow instantiation using ref counting.
264 friend class LightRefBase<EglImage>;
265 virtual ~EglImage();
266
267 // createImage creates a new EGLImage from a GraphicBuffer.
268 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
269 const Rect& crop);
270
271 // Disallow copying
272 EglImage(const EglImage& rhs);
273 void operator=(const EglImage& rhs);
274
275 // mGraphicBuffer is the buffer that was used to create this image.
276 sp<GraphicBuffer> mGraphicBuffer;
277
278 // mEglImage is the EGLImage created from mGraphicBuffer.
279 EGLImageKHR mEglImage;
280
281 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
282 EGLDisplay mEglDisplay;
283
284 // mCropRect is the crop rectangle passed to EGL when mEglImage
285 // was created.
286 Rect mCropRect;
287 };
288
289 // freeBufferLocked frees up the given buffer slot. If the slot has been
290 // initialized this will release the reference to the GraphicBuffer in that
291 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
292 //
293 // This method must be called with mMutex locked.
294 virtual void freeBufferLocked(int slotIndex);
295
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800296 // IConsumerListener interface
297 void onDisconnect() override;
Chia-I Wufd257f82017-11-27 14:51:06 -0800298 void onSidebandStreamChanged() override;
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800299 void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
300 FrameEventHistoryDelta* outDelta) override;
301
Chia-I Wuf1405182017-11-27 11:29:21 -0800302 // computeCurrentTransformMatrixLocked computes the transform matrix for the
303 // current texture. It uses mCurrentTransform and the current GraphicBuffer
304 // to compute this matrix and stores it in mCurrentTransformMatrix.
305 // mCurrentTextureImage must not be NULL.
306 void computeCurrentTransformMatrixLocked();
307
308 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
309 // stream to ensure that it is safe for future OpenGL ES commands to
310 // access the current texture buffer.
311 status_t doGLFenceWaitLocked() const;
312
313 // syncForReleaseLocked performs the synchronization needed to release the
314 // current slot from an OpenGL ES context. If needed it will set the
315 // current slot's fence to guard against a producer accessing the buffer
316 // before the outstanding accesses have completed.
317 status_t syncForReleaseLocked(EGLDisplay dpy);
318
Chia-I Wubd854bf2017-11-27 13:41:26 -0800319 // sTexTarget is the GL texture target with which the GL texture object is
320 // associated.
321 static constexpr uint32_t sTexTarget = 0x8D65; // GL_TEXTURE_EXTERNAL_OES
322
Chia-I Wuf1405182017-11-27 11:29:21 -0800323 // The default consumer usage flags that BufferLayerConsumer always sets on its
324 // BufferQueue instance; these will be OR:d with any additional flags passed
325 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
326 // consume buffers as hardware textures.
327 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
328
329 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
330 // possible that this buffer is not associated with any buffer slot, so we
331 // must track it separately in order to support the getCurrentBuffer method.
332 sp<EglImage> mCurrentTextureImage;
333
334 // mCurrentCrop is the crop rectangle that applies to the current texture.
335 // It gets set each time updateTexImage is called.
336 Rect mCurrentCrop;
337
338 // mCurrentTransform is the transform identifier for the current texture. It
339 // gets set each time updateTexImage is called.
340 uint32_t mCurrentTransform;
341
342 // mCurrentScalingMode is the scaling mode for the current texture. It gets
343 // set each time updateTexImage is called.
344 uint32_t mCurrentScalingMode;
345
346 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
347 sp<Fence> mCurrentFence;
348
349 // The FenceTime wrapper around mCurrentFence.
350 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
351
352 // mCurrentTransformMatrix is the transform matrix for the current texture.
353 // It gets computed by computeTransformMatrix each time updateTexImage is
354 // called.
355 float mCurrentTransformMatrix[16];
356
357 // mCurrentTimestamp is the timestamp for the current texture. It
358 // gets set each time updateTexImage is called.
359 int64_t mCurrentTimestamp;
360
361 // mCurrentDataSpace is the dataspace for the current texture. It
362 // gets set each time updateTexImage is called.
363 android_dataspace mCurrentDataSpace;
364
365 // mCurrentFrameNumber is the frame counter for the current texture.
366 // It gets set each time updateTexImage is called.
367 uint64_t mCurrentFrameNumber;
368
Chia-I Wu67dcc692017-11-27 14:51:06 -0800369 // Indicates this buffer must be transformed by the inverse transform of the screen
370 // it is displayed onto. This is applied after BufferLayerConsumer::mCurrentTransform.
371 // This must be set/read from SurfaceFlinger's main thread.
372 bool mCurrentTransformToDisplayInverse;
373
374 // The portion of this surface that has changed since the previous frame
375 Region mCurrentSurfaceDamage;
376
Chia-I Wuf1405182017-11-27 11:29:21 -0800377 uint32_t mDefaultWidth, mDefaultHeight;
378
379 // mFilteringEnabled indicates whether the transform matrix is computed for
380 // use with bilinear filtering. It defaults to true and is changed by
381 // setFilteringEnabled().
382 bool mFilteringEnabled;
383
384 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800385 // be bound when updateTexImage is called. It is set at construction time.
386 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800387
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800388 // The layer for this BufferLayerConsumer
389 const wp<Layer> mLayer;
390
Chia-I Wufd257f82017-11-27 14:51:06 -0800391 wp<ContentsChangedListener> mContentsChangedListener;
392
Chia-I Wuf1405182017-11-27 11:29:21 -0800393 // EGLSlot contains the information and object references that
394 // BufferLayerConsumer maintains about a BufferQueue buffer slot.
395 struct EglSlot {
Chia-I Wuf1405182017-11-27 11:29:21 -0800396 // mEglImage is the EGLImage created from mGraphicBuffer.
397 sp<EglImage> mEglImage;
Chia-I Wuf1405182017-11-27 11:29:21 -0800398 };
399
400 // mEglDisplay is the EGLDisplay with which this BufferLayerConsumer is currently
401 // associated. It is intialized to EGL_NO_DISPLAY and gets set to the
Chia-I Wuc91077c2017-11-27 13:32:04 -0800402 // current display when updateTexImage is called for the first time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800403 EGLDisplay mEglDisplay;
404
405 // mEglContext is the OpenGL ES context with which this BufferLayerConsumer is
406 // currently associated. It is initialized to EGL_NO_CONTEXT and gets set
407 // to the current GL context when updateTexImage is called for the first
Chia-I Wuc91077c2017-11-27 13:32:04 -0800408 // time.
Chia-I Wuf1405182017-11-27 11:29:21 -0800409 EGLContext mEglContext;
410
411 // mEGLSlots stores the buffers that have been allocated by the BufferQueue
412 // for each buffer slot. It is initialized to null pointers, and gets
413 // filled in with the result of BufferQueue::acquire when the
414 // client dequeues a buffer from a
415 // slot that has not yet been used. The buffer allocated to a slot will also
416 // be replaced if the requested buffer usage or geometry differs from that
417 // of the buffer allocated to a slot.
418 EglSlot mEglSlots[BufferQueueDefs::NUM_BUFFER_SLOTS];
419
420 // mCurrentTexture is the buffer slot index of the buffer that is currently
421 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
422 // indicating that no buffer slot is currently bound to the texture. Note,
423 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
424 // that no buffer is bound to the texture. A call to setBufferCount will
425 // reset mCurrentTexture to INVALID_BUFFER_SLOT.
426 int mCurrentTexture;
Chia-I Wuda5c7302017-11-27 14:51:06 -0800427
428 // A release that is pending on the receipt of a new release fence from
429 // presentDisplay
430 PendingRelease mPendingRelease;
Chia-I Wuf1405182017-11-27 11:29:21 -0800431};
432
433// ----------------------------------------------------------------------------
434}; // namespace android
435
436#endif // ANDROID_BUFFERLAYERCONSUMER_H