blob: a08f15b248bf2bf8902fc8e996c465fc964ba8a5 [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 Wu9f2db772017-11-30 21:06:50 -080039class RenderEngine;
Chia-I Wuf1405182017-11-27 11:29:21 -080040class String8;
41
42/*
43 * BufferLayerConsumer consumes buffers of graphics data from a BufferQueue,
44 * and makes them available to OpenGL as a texture.
45 *
46 * A typical usage pattern is to set up the BufferLayerConsumer with the
47 * desired options, and call updateTexImage() when a new frame is desired.
48 * If a new frame is available, the texture will be updated. If not,
49 * the previous contents are retained.
50 *
Chia-I Wuc91077c2017-11-27 13:32:04 -080051 * The texture is attached to the GL_TEXTURE_EXTERNAL_OES texture target, in
52 * the EGL context of the first thread that calls updateTexImage(). After that
53 * point, all calls to updateTexImage must be made with the same OpenGL ES
54 * context current.
Chia-I Wuf1405182017-11-27 11:29:21 -080055 *
56 * This class was previously called SurfaceTexture.
57 */
58class BufferLayerConsumer : public ConsumerBase {
59public:
Chia-I Wuda5c7302017-11-27 14:51:06 -080060 static const status_t BUFFER_REJECTED = UNKNOWN_ERROR + 8;
61
62 class BufferRejecter {
63 friend class BufferLayerConsumer;
64 virtual bool reject(const sp<GraphicBuffer>& buf, const BufferItem& item) = 0;
65
66 protected:
67 virtual ~BufferRejecter() {}
68 };
69
Chia-I Wufd257f82017-11-27 14:51:06 -080070 struct ContentsChangedListener : public FrameAvailableListener {
71 virtual void onSidebandStreamChanged() = 0;
72 };
Chia-I Wuf1405182017-11-27 11:29:21 -080073
Chia-I Wuc91077c2017-11-27 13:32:04 -080074 // BufferLayerConsumer constructs a new BufferLayerConsumer object.
75 // The tex parameter indicates the name of the OpenGL ES
Chia-I Wubd854bf2017-11-27 13:41:26 -080076 // texture to which images are to be streamed.
Chia-I Wu9f2db772017-11-30 21:06:50 -080077 BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, RenderEngine& engine, uint32_t tex,
78 Layer* layer);
Chia-I Wuf1405182017-11-27 11:29:21 -080079
Chia-I Wufd257f82017-11-27 14:51:06 -080080 // Sets the contents changed listener. This should be used instead of
81 // ConsumerBase::setFrameAvailableListener().
82 void setContentsChangedListener(const wp<ContentsChangedListener>& listener);
83
Chia-I Wuda5c7302017-11-27 14:51:06 -080084 nsecs_t computeExpectedPresent(const DispSync& dispSync);
85
Chia-I Wuf1405182017-11-27 11:29:21 -080086 // updateTexImage acquires the most recently queued buffer, and sets the
87 // image contents of the target texture to it.
88 //
89 // This call may only be made while the OpenGL ES context to which the
90 // target texture belongs is bound to the calling thread.
91 //
92 // This calls doGLFenceWait to ensure proper synchronization.
Chia-I Wuda5c7302017-11-27 14:51:06 -080093 //
94 // This version of updateTexImage() takes a functor that may be used to
95 // reject the newly acquired buffer. Unlike the GLConsumer version,
96 // this does not guarantee that the buffer has been bound to the GL
97 // texture.
98 status_t updateTexImage(BufferRejecter* rejecter, const DispSync& dispSync, bool* autoRefresh,
99 bool* queuedBuffer, uint64_t maxFrameNumber);
Chia-I Wuf1405182017-11-27 11:29:21 -0800100
Chia-I Wu0cb75ac2017-11-27 15:56:04 -0800101 // See BufferLayerConsumer::bindTextureImageLocked().
102 status_t bindTextureImage();
103
Chia-I Wuf1405182017-11-27 11:29:21 -0800104 // setReleaseFence stores a fence that will signal when the current buffer
105 // is no longer being read. This fence will be returned to the producer
106 // when the current buffer is released by updateTexImage(). Multiple
107 // fences can be set for a given buffer; they will be merged into a single
108 // union fence.
Chia-I Wuda5c7302017-11-27 14:51:06 -0800109 void setReleaseFence(const sp<Fence>& fence);
110
111 bool releasePendingBuffer();
Chia-I Wuf1405182017-11-27 11:29:21 -0800112
Chia-I Wu0cb75ac2017-11-27 15:56:04 -0800113 sp<Fence> getPrevFinalReleaseFence() const;
114
Chia-I Wuf1405182017-11-27 11:29:21 -0800115 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
116 // associated with the texture image set by the most recent call to
117 // updateTexImage.
118 //
119 // This transform matrix maps 2D homogeneous texture coordinates of the form
120 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
121 // coordinate that should be used to sample that location from the texture.
122 // Sampling the texture outside of the range of this transform is undefined.
123 //
124 // This transform is necessary to compensate for transforms that the stream
125 // content producer may implicitly apply to the content. By forcing users of
126 // a BufferLayerConsumer to apply this transform we avoid performing an extra
127 // copy of the data that would be needed to hide the transform from the
128 // user.
129 //
130 // The matrix is stored in column-major order so that it may be passed
131 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
132 // functions.
133 void getTransformMatrix(float mtx[16]);
134
Chia-I Wuf1405182017-11-27 11:29:21 -0800135 // getTimestamp retrieves the timestamp associated with the texture image
136 // set by the most recent call to updateTexImage.
137 //
138 // The timestamp is in nanoseconds, and is monotonically increasing. Its
139 // other semantics (zero point, etc) are source-dependent and should be
140 // documented by the source.
141 int64_t getTimestamp();
142
143 // getDataSpace retrieves the DataSpace associated with the texture image
144 // set by the most recent call to updateTexImage.
145 android_dataspace getCurrentDataSpace();
146
147 // getFrameNumber retrieves the frame number associated with the texture
148 // image set by the most recent call to updateTexImage.
149 //
150 // The frame number is an incrementing counter set to 0 at the creation of
151 // the BufferQueue associated with this consumer.
152 uint64_t getFrameNumber();
153
Chia-I Wu67dcc692017-11-27 14:51:06 -0800154 bool getTransformToDisplayInverse() const;
155
156 // must be called from SF main thread
157 const Region& getSurfaceDamage() const;
158
Chia-I Wuf1405182017-11-27 11:29:21 -0800159 // setDefaultBufferSize is used to set the size of buffers returned by
160 // requestBuffers when a with and height of zero is requested.
161 // A call to setDefaultBufferSize() may trigger requestBuffers() to
162 // be called from the client.
163 // The width and height parameters must be no greater than the minimum of
164 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
165 // An error due to invalid dimensions might not be reported until
166 // updateTexImage() is called.
167 status_t setDefaultBufferSize(uint32_t width, uint32_t height);
168
169 // setFilteringEnabled sets whether the transform matrix should be computed
170 // for use with bilinear filtering.
171 void setFilteringEnabled(bool enabled);
172
173 // getCurrentBuffer returns the buffer associated with the current image.
174 // When outSlot is not nullptr, the current buffer slot index is also
175 // returned.
176 sp<GraphicBuffer> getCurrentBuffer(int* outSlot = nullptr) const;
177
Chia-I Wuf1405182017-11-27 11:29:21 -0800178 // getCurrentCrop returns the cropping rectangle of the current buffer.
179 Rect getCurrentCrop() const;
180
181 // getCurrentTransform returns the transform of the current buffer.
182 uint32_t getCurrentTransform() const;
183
184 // getCurrentScalingMode returns the scaling mode of the current buffer.
185 uint32_t getCurrentScalingMode() const;
186
187 // getCurrentFence returns the fence indicating when the current buffer is
188 // ready to be read from.
189 sp<Fence> getCurrentFence() const;
190
191 // getCurrentFence returns the FenceTime indicating when the current
192 // buffer is ready to be read from.
193 std::shared_ptr<FenceTime> getCurrentFenceTime() const;
194
195 // setConsumerUsageBits overrides the ConsumerBase method to OR
196 // DEFAULT_USAGE_FLAGS to usage.
197 status_t setConsumerUsageBits(uint64_t usage);
198
Chia-I Wuf1405182017-11-27 11:29:21 -0800199protected:
200 // abandonLocked overrides the ConsumerBase method to clear
201 // mCurrentTextureImage in addition to the ConsumerBase behavior.
202 virtual void abandonLocked();
203
204 // dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
205 // specific info in addition to the ConsumerBase behavior.
206 virtual void dumpLocked(String8& result, const char* prefix) const;
207
208 // acquireBufferLocked overrides the ConsumerBase method to update the
209 // mEglSlots array in addition to the ConsumerBase behavior.
210 virtual status_t acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
211 uint64_t maxFrameNumber = 0) override;
212
Chia-I Wuf1405182017-11-27 11:29:21 -0800213 struct PendingRelease {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800214 PendingRelease() : isPending(false), currentTexture(-1), graphicBuffer() {}
Chia-I Wuf1405182017-11-27 11:29:21 -0800215
216 bool isPending;
217 int currentTexture;
218 sp<GraphicBuffer> graphicBuffer;
Chia-I Wuf1405182017-11-27 11:29:21 -0800219 };
220
221 // This releases the buffer in the slot referenced by mCurrentTexture,
222 // then updates state to refer to the BufferItem, which must be a
223 // newly-acquired buffer. If pendingRelease is not null, the parameters
224 // which would have been passed to releaseBufferLocked upon the successful
225 // completion of the method will instead be returned to the caller, so that
226 // it may call releaseBufferLocked itself later.
227 status_t updateAndReleaseLocked(const BufferItem& item,
228 PendingRelease* pendingRelease = nullptr);
229
Chia-I Wubd854bf2017-11-27 13:41:26 -0800230 // Binds mTexName and the current buffer to sTexTarget. Uses
Chia-I Wuf1405182017-11-27 11:29:21 -0800231 // mCurrentTexture if it's set, mCurrentTextureImage if not. If the
232 // bind succeeds, this calls doGLFenceWait.
233 status_t bindTextureImageLocked();
234
Chia-I Wuf1405182017-11-27 11:29:21 -0800235private:
236 // EglImage is a utility class for tracking and creating EGLImageKHRs. There
237 // is primarily just one image per slot, but there is also special cases:
Chia-I Wuf1405182017-11-27 11:29:21 -0800238 // - After freeBuffer, we must still keep the current image/buffer
239 // Reference counting EGLImages lets us handle all these cases easily while
240 // also only creating new EGLImages from buffers when required.
241 class EglImage : public LightRefBase<EglImage> {
242 public:
243 EglImage(sp<GraphicBuffer> graphicBuffer);
244
245 // createIfNeeded creates an EGLImage if required (we haven't created
246 // one yet, or the EGLDisplay or crop-rect has changed).
Chia-I Wuc91077c2017-11-27 13:32:04 -0800247 status_t createIfNeeded(EGLDisplay display, const Rect& cropRect);
Chia-I Wuf1405182017-11-27 11:29:21 -0800248
249 // This calls glEGLImageTargetTexture2DOES to bind the image to the
250 // texture in the specified texture target.
251 void bindToTextureTarget(uint32_t texTarget);
252
253 const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
254 const native_handle* graphicBufferHandle() {
255 return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
256 }
257
258 private:
259 // Only allow instantiation using ref counting.
260 friend class LightRefBase<EglImage>;
261 virtual ~EglImage();
262
263 // createImage creates a new EGLImage from a GraphicBuffer.
264 EGLImageKHR createImage(EGLDisplay dpy, const sp<GraphicBuffer>& graphicBuffer,
265 const Rect& crop);
266
267 // Disallow copying
268 EglImage(const EglImage& rhs);
269 void operator=(const EglImage& rhs);
270
271 // mGraphicBuffer is the buffer that was used to create this image.
272 sp<GraphicBuffer> mGraphicBuffer;
273
274 // mEglImage is the EGLImage created from mGraphicBuffer.
275 EGLImageKHR mEglImage;
276
277 // mEGLDisplay is the EGLDisplay that was used to create mEglImage.
278 EGLDisplay mEglDisplay;
279
280 // mCropRect is the crop rectangle passed to EGL when mEglImage
281 // was created.
282 Rect mCropRect;
283 };
284
285 // freeBufferLocked frees up the given buffer slot. If the slot has been
286 // initialized this will release the reference to the GraphicBuffer in that
287 // slot and destroy the EGLImage in that slot. Otherwise it has no effect.
288 //
289 // This method must be called with mMutex locked.
290 virtual void freeBufferLocked(int slotIndex);
291
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800292 // IConsumerListener interface
293 void onDisconnect() override;
Chia-I Wufd257f82017-11-27 14:51:06 -0800294 void onSidebandStreamChanged() override;
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800295 void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
296 FrameEventHistoryDelta* outDelta) override;
297
Chia-I Wuf1405182017-11-27 11:29:21 -0800298 // computeCurrentTransformMatrixLocked computes the transform matrix for the
299 // current texture. It uses mCurrentTransform and the current GraphicBuffer
300 // to compute this matrix and stores it in mCurrentTransformMatrix.
301 // mCurrentTextureImage must not be NULL.
302 void computeCurrentTransformMatrixLocked();
303
304 // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
305 // stream to ensure that it is safe for future OpenGL ES commands to
306 // access the current texture buffer.
307 status_t doGLFenceWaitLocked() const;
308
309 // syncForReleaseLocked performs the synchronization needed to release the
310 // current slot from an OpenGL ES context. If needed it will set the
311 // current slot's fence to guard against a producer accessing the buffer
312 // before the outstanding accesses have completed.
313 status_t syncForReleaseLocked(EGLDisplay dpy);
314
Chia-I Wubd854bf2017-11-27 13:41:26 -0800315 // sTexTarget is the GL texture target with which the GL texture object is
316 // associated.
317 static constexpr uint32_t sTexTarget = 0x8D65; // GL_TEXTURE_EXTERNAL_OES
318
Chia-I Wuf1405182017-11-27 11:29:21 -0800319 // The default consumer usage flags that BufferLayerConsumer always sets on its
320 // BufferQueue instance; these will be OR:d with any additional flags passed
321 // from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
322 // consume buffers as hardware textures.
323 static const uint64_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
324
325 // mCurrentTextureImage is the EglImage/buffer of the current texture. It's
326 // possible that this buffer is not associated with any buffer slot, so we
327 // must track it separately in order to support the getCurrentBuffer method.
328 sp<EglImage> mCurrentTextureImage;
329
330 // mCurrentCrop is the crop rectangle that applies to the current texture.
331 // It gets set each time updateTexImage is called.
332 Rect mCurrentCrop;
333
334 // mCurrentTransform is the transform identifier for the current texture. It
335 // gets set each time updateTexImage is called.
336 uint32_t mCurrentTransform;
337
338 // mCurrentScalingMode is the scaling mode for the current texture. It gets
339 // set each time updateTexImage is called.
340 uint32_t mCurrentScalingMode;
341
342 // mCurrentFence is the fence received from BufferQueue in updateTexImage.
343 sp<Fence> mCurrentFence;
344
345 // The FenceTime wrapper around mCurrentFence.
346 std::shared_ptr<FenceTime> mCurrentFenceTime{FenceTime::NO_FENCE};
347
348 // mCurrentTransformMatrix is the transform matrix for the current texture.
349 // It gets computed by computeTransformMatrix each time updateTexImage is
350 // called.
351 float mCurrentTransformMatrix[16];
352
353 // mCurrentTimestamp is the timestamp for the current texture. It
354 // gets set each time updateTexImage is called.
355 int64_t mCurrentTimestamp;
356
357 // mCurrentDataSpace is the dataspace for the current texture. It
358 // gets set each time updateTexImage is called.
359 android_dataspace mCurrentDataSpace;
360
361 // mCurrentFrameNumber is the frame counter for the current texture.
362 // It gets set each time updateTexImage is called.
363 uint64_t mCurrentFrameNumber;
364
Chia-I Wu67dcc692017-11-27 14:51:06 -0800365 // Indicates this buffer must be transformed by the inverse transform of the screen
366 // it is displayed onto. This is applied after BufferLayerConsumer::mCurrentTransform.
367 // This must be set/read from SurfaceFlinger's main thread.
368 bool mCurrentTransformToDisplayInverse;
369
370 // The portion of this surface that has changed since the previous frame
371 Region mCurrentSurfaceDamage;
372
Chia-I Wuf1405182017-11-27 11:29:21 -0800373 uint32_t mDefaultWidth, mDefaultHeight;
374
375 // mFilteringEnabled indicates whether the transform matrix is computed for
376 // use with bilinear filtering. It defaults to true and is changed by
377 // setFilteringEnabled().
378 bool mFilteringEnabled;
379
Chia-I Wu9f2db772017-11-30 21:06:50 -0800380 RenderEngine& mRE;
381
382 // mEglDisplay is initialized to RenderEngine's EGLDisplay.
383 const EGLDisplay mEglDisplay;
384
Chia-I Wuf1405182017-11-27 11:29:21 -0800385 // mTexName is the name of the OpenGL texture to which streamed images will
Chia-I Wuc91077c2017-11-27 13:32:04 -0800386 // be bound when updateTexImage is called. It is set at construction time.
387 const uint32_t mTexName;
Chia-I Wuf1405182017-11-27 11:29:21 -0800388
Chia-I Wuc75c44d2017-11-27 14:32:57 -0800389 // The layer for this BufferLayerConsumer
390 const wp<Layer> mLayer;
391
Chia-I Wufd257f82017-11-27 14:51:06 -0800392 wp<ContentsChangedListener> mContentsChangedListener;
393
Chia-I Wuf1405182017-11-27 11:29:21 -0800394 // EGLSlot contains the information and object references that
395 // BufferLayerConsumer maintains about a BufferQueue buffer slot.
396 struct EglSlot {
Chia-I Wuf1405182017-11-27 11:29:21 -0800397 // mEglImage is the EGLImage created from mGraphicBuffer.
398 sp<EglImage> mEglImage;
Chia-I Wuf1405182017-11-27 11:29:21 -0800399 };
400
Chia-I Wuf1405182017-11-27 11:29:21 -0800401 // mEGLSlots stores the buffers that have been allocated by the BufferQueue
402 // for each buffer slot. It is initialized to null pointers, and gets
403 // filled in with the result of BufferQueue::acquire when the
404 // client dequeues a buffer from a
405 // slot that has not yet been used. The buffer allocated to a slot will also
406 // be replaced if the requested buffer usage or geometry differs from that
407 // of the buffer allocated to a slot.
408 EglSlot mEglSlots[BufferQueueDefs::NUM_BUFFER_SLOTS];
409
410 // mCurrentTexture is the buffer slot index of the buffer that is currently
411 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
412 // indicating that no buffer slot is currently bound to the texture. Note,
413 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
414 // that no buffer is bound to the texture. A call to setBufferCount will
415 // reset mCurrentTexture to INVALID_BUFFER_SLOT.
416 int mCurrentTexture;
Chia-I Wuda5c7302017-11-27 14:51:06 -0800417
418 // A release that is pending on the receipt of a new release fence from
419 // presentDisplay
420 PendingRelease mPendingRelease;
Chia-I Wuf1405182017-11-27 11:29:21 -0800421};
422
423// ----------------------------------------------------------------------------
424}; // namespace android
425
426#endif // ANDROID_BUFFERLAYERCONSUMER_H