blob: 05bb96a55158bcdb478e3cbfcc4e7d02017cf645 [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#undef LOG_TAG
18#define LOG_TAG "BufferLayerConsumer"
19#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20//#define LOG_NDEBUG 0
21
22#include "BufferLayerConsumer.h"
23
24#include <inttypes.h>
25
26#include <EGL/egl.h>
27#include <EGL/eglext.h>
28#include <GLES2/gl2.h>
29#include <GLES2/gl2ext.h>
30#include <cutils/compiler.h>
31
32#include <hardware/hardware.h>
33
34#include <math/mat4.h>
35
36#include <gui/BufferItem.h>
37#include <gui/GLConsumer.h>
38#include <gui/ISurfaceComposer.h>
39#include <gui/SurfaceComposerClient.h>
40
41#include <private/gui/ComposerService.h>
42#include <private/gui/SyncFeatures.h>
43
44#include <utils/Log.h>
45#include <utils/String8.h>
46#include <utils/Trace.h>
47
48extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
49#define CROP_EXT_STR "EGL_ANDROID_image_crop"
50#define PROT_CONTENT_EXT_STR "EGL_EXT_protected_content"
51#define EGL_PROTECTED_CONTENT_EXT 0x32C0
52
53namespace android {
54
55// Macros for including the BufferLayerConsumer name in log messages
56#define BLC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
57#define BLC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
58//#define BLC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
59#define BLC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
60#define BLC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
61
Chia-I Wuf1405182017-11-27 11:29:21 -080062static const mat4 mtxIdentity;
63
Chia-I Wuf1405182017-11-27 11:29:21 -080064static bool hasEglAndroidImageCropImpl() {
65 EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
66 const char* exts = eglQueryStringImplementationANDROID(dpy, EGL_EXTENSIONS);
67 size_t cropExtLen = strlen(CROP_EXT_STR);
68 size_t extsLen = strlen(exts);
69 bool equal = !strcmp(CROP_EXT_STR, exts);
70 bool atStart = !strncmp(CROP_EXT_STR " ", exts, cropExtLen + 1);
71 bool atEnd = (cropExtLen + 1) < extsLen &&
72 !strcmp(" " CROP_EXT_STR, exts + extsLen - (cropExtLen + 1));
73 bool inMiddle = strstr(exts, " " CROP_EXT_STR " ");
74 return equal || atStart || atEnd || inMiddle;
75}
76
77static bool hasEglAndroidImageCrop() {
78 // Only compute whether the extension is present once the first time this
79 // function is called.
80 static bool hasIt = hasEglAndroidImageCropImpl();
81 return hasIt;
82}
83
84static bool hasEglProtectedContentImpl() {
85 EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
86 const char* exts = eglQueryString(dpy, EGL_EXTENSIONS);
87 size_t cropExtLen = strlen(PROT_CONTENT_EXT_STR);
88 size_t extsLen = strlen(exts);
89 bool equal = !strcmp(PROT_CONTENT_EXT_STR, exts);
90 bool atStart = !strncmp(PROT_CONTENT_EXT_STR " ", exts, cropExtLen + 1);
91 bool atEnd = (cropExtLen + 1) < extsLen &&
92 !strcmp(" " PROT_CONTENT_EXT_STR, exts + extsLen - (cropExtLen + 1));
93 bool inMiddle = strstr(exts, " " PROT_CONTENT_EXT_STR " ");
94 return equal || atStart || atEnd || inMiddle;
95}
96
97static bool hasEglProtectedContent() {
98 // Only compute whether the extension is present once the first time this
99 // function is called.
100 static bool hasIt = hasEglProtectedContentImpl();
101 return hasIt;
102}
103
104static bool isEglImageCroppable(const Rect& crop) {
105 return hasEglAndroidImageCrop() && (crop.left == 0 && crop.top == 0);
106}
107
108BufferLayerConsumer::BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t tex,
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800109 uint32_t texTarget, bool isControlledByApp)
Chia-I Wuf1405182017-11-27 11:29:21 -0800110 : ConsumerBase(bq, isControlledByApp),
111 mCurrentCrop(Rect::EMPTY_RECT),
112 mCurrentTransform(0),
113 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
114 mCurrentFence(Fence::NO_FENCE),
115 mCurrentTimestamp(0),
116 mCurrentDataSpace(HAL_DATASPACE_UNKNOWN),
117 mCurrentFrameNumber(0),
118 mDefaultWidth(1),
119 mDefaultHeight(1),
120 mFilteringEnabled(true),
121 mTexName(tex),
Chia-I Wuf1405182017-11-27 11:29:21 -0800122 mTexTarget(texTarget),
123 mEglDisplay(EGL_NO_DISPLAY),
124 mEglContext(EGL_NO_CONTEXT),
Chia-I Wuc91077c2017-11-27 13:32:04 -0800125 mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT) {
Chia-I Wuf1405182017-11-27 11:29:21 -0800126 BLC_LOGV("BufferLayerConsumer");
127
128 memcpy(mCurrentTransformMatrix, mtxIdentity.asArray(), sizeof(mCurrentTransformMatrix));
129
130 mConsumer->setConsumerUsageBits(DEFAULT_USAGE_FLAGS);
131}
132
133status_t BufferLayerConsumer::setDefaultBufferSize(uint32_t w, uint32_t h) {
134 Mutex::Autolock lock(mMutex);
135 if (mAbandoned) {
136 BLC_LOGE("setDefaultBufferSize: BufferLayerConsumer is abandoned!");
137 return NO_INIT;
138 }
139 mDefaultWidth = w;
140 mDefaultHeight = h;
141 return mConsumer->setDefaultBufferSize(w, h);
142}
143
144status_t BufferLayerConsumer::updateTexImage() {
145 ATRACE_CALL();
146 BLC_LOGV("updateTexImage");
147 Mutex::Autolock lock(mMutex);
148
149 if (mAbandoned) {
150 BLC_LOGE("updateTexImage: BufferLayerConsumer is abandoned!");
151 return NO_INIT;
152 }
153
154 // Make sure the EGL state is the same as in previous calls.
155 status_t err = checkAndUpdateEglStateLocked();
156 if (err != NO_ERROR) {
157 return err;
158 }
159
160 BufferItem item;
161
162 // Acquire the next buffer.
163 // In asynchronous mode the list is guaranteed to be one buffer
164 // deep, while in synchronous mode we use the oldest buffer.
165 err = acquireBufferLocked(&item, 0);
166 if (err != NO_ERROR) {
167 if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
168 // We always bind the texture even if we don't update its contents.
169 BLC_LOGV("updateTexImage: no buffers were available");
170 glBindTexture(mTexTarget, mTexName);
171 err = NO_ERROR;
172 } else {
173 BLC_LOGE("updateTexImage: acquire failed: %s (%d)", strerror(-err), err);
174 }
175 return err;
176 }
177
178 // Release the previous buffer.
179 err = updateAndReleaseLocked(item);
180 if (err != NO_ERROR) {
181 // We always bind the texture.
182 glBindTexture(mTexTarget, mTexName);
183 return err;
184 }
185
186 // Bind the new buffer to the GL texture, and wait until it's ready.
187 return bindTextureImageLocked();
188}
189
Chia-I Wuf1405182017-11-27 11:29:21 -0800190status_t BufferLayerConsumer::acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
191 uint64_t maxFrameNumber) {
192 status_t err = ConsumerBase::acquireBufferLocked(item, presentWhen, maxFrameNumber);
193 if (err != NO_ERROR) {
194 return err;
195 }
196
197 // If item->mGraphicBuffer is not null, this buffer has not been acquired
198 // before, so any prior EglImage created is using a stale buffer. This
199 // replaces any old EglImage with a new one (using the new buffer).
200 if (item->mGraphicBuffer != NULL) {
201 int slot = item->mSlot;
202 mEglSlots[slot].mEglImage = new EglImage(item->mGraphicBuffer);
203 }
204
205 return NO_ERROR;
206}
207
Chia-I Wuf1405182017-11-27 11:29:21 -0800208status_t BufferLayerConsumer::updateAndReleaseLocked(const BufferItem& item,
209 PendingRelease* pendingRelease) {
210 status_t err = NO_ERROR;
211
212 int slot = item.mSlot;
213
Chia-I Wuf1405182017-11-27 11:29:21 -0800214 // Confirm state.
215 err = checkAndUpdateEglStateLocked();
216 if (err != NO_ERROR) {
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800217 releaseBufferLocked(slot, mSlots[slot].mGraphicBuffer);
Chia-I Wuf1405182017-11-27 11:29:21 -0800218 return err;
219 }
220
221 // Ensure we have a valid EglImageKHR for the slot, creating an EglImage
222 // if nessessary, for the gralloc buffer currently in the slot in
223 // ConsumerBase.
224 // We may have to do this even when item.mGraphicBuffer == NULL (which
225 // means the buffer was previously acquired).
226 err = mEglSlots[slot].mEglImage->createIfNeeded(mEglDisplay, item.mCrop);
227 if (err != NO_ERROR) {
228 BLC_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d", mEglDisplay,
229 slot);
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800230 releaseBufferLocked(slot, mSlots[slot].mGraphicBuffer);
Chia-I Wuf1405182017-11-27 11:29:21 -0800231 return UNKNOWN_ERROR;
232 }
233
234 // Do whatever sync ops we need to do before releasing the old slot.
235 if (slot != mCurrentTexture) {
236 err = syncForReleaseLocked(mEglDisplay);
237 if (err != NO_ERROR) {
238 // Release the buffer we just acquired. It's not safe to
239 // release the old buffer, so instead we just drop the new frame.
240 // As we are still under lock since acquireBuffer, it is safe to
241 // release by slot.
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800242 releaseBufferLocked(slot, mSlots[slot].mGraphicBuffer);
Chia-I Wuf1405182017-11-27 11:29:21 -0800243 return err;
244 }
245 }
246
247 BLC_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)", mCurrentTexture,
248 mCurrentTextureImage != NULL ? mCurrentTextureImage->graphicBufferHandle() : 0, slot,
249 mSlots[slot].mGraphicBuffer->handle);
250
251 // Hang onto the pointer so that it isn't freed in the call to
252 // releaseBufferLocked() if we're in shared buffer mode and both buffers are
253 // the same.
254 sp<EglImage> nextTextureImage = mEglSlots[slot].mEglImage;
255
256 // release old buffer
257 if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
258 if (pendingRelease == nullptr) {
259 status_t status =
Chia-I Wu6aff69b2017-11-27 14:08:48 -0800260 releaseBufferLocked(mCurrentTexture, mCurrentTextureImage->graphicBuffer());
Chia-I Wuf1405182017-11-27 11:29:21 -0800261 if (status < NO_ERROR) {
262 BLC_LOGE("updateAndRelease: failed to release buffer: %s (%d)", strerror(-status),
263 status);
264 err = status;
265 // keep going, with error raised [?]
266 }
267 } else {
268 pendingRelease->currentTexture = mCurrentTexture;
269 pendingRelease->graphicBuffer = mCurrentTextureImage->graphicBuffer();
Chia-I Wuf1405182017-11-27 11:29:21 -0800270 pendingRelease->isPending = true;
271 }
272 }
273
274 // Update the BufferLayerConsumer state.
275 mCurrentTexture = slot;
276 mCurrentTextureImage = nextTextureImage;
277 mCurrentCrop = item.mCrop;
278 mCurrentTransform = item.mTransform;
279 mCurrentScalingMode = item.mScalingMode;
280 mCurrentTimestamp = item.mTimestamp;
281 mCurrentDataSpace = item.mDataSpace;
282 mCurrentFence = item.mFence;
283 mCurrentFenceTime = item.mFenceTime;
284 mCurrentFrameNumber = item.mFrameNumber;
285
286 computeCurrentTransformMatrixLocked();
287
288 return err;
289}
290
291status_t BufferLayerConsumer::bindTextureImageLocked() {
292 if (mEglDisplay == EGL_NO_DISPLAY) {
293 ALOGE("bindTextureImage: invalid display");
294 return INVALID_OPERATION;
295 }
296
297 GLenum error;
298 while ((error = glGetError()) != GL_NO_ERROR) {
299 BLC_LOGW("bindTextureImage: clearing GL error: %#04x", error);
300 }
301
302 glBindTexture(mTexTarget, mTexName);
303 if (mCurrentTexture == BufferQueue::INVALID_BUFFER_SLOT && mCurrentTextureImage == NULL) {
304 BLC_LOGE("bindTextureImage: no currently-bound texture");
305 return NO_INIT;
306 }
307
308 status_t err = mCurrentTextureImage->createIfNeeded(mEglDisplay, mCurrentCrop);
309 if (err != NO_ERROR) {
310 BLC_LOGW("bindTextureImage: can't create image on display=%p slot=%d", mEglDisplay,
311 mCurrentTexture);
312 return UNKNOWN_ERROR;
313 }
314 mCurrentTextureImage->bindToTextureTarget(mTexTarget);
315
Chia-I Wuf1405182017-11-27 11:29:21 -0800316 // Wait for the new buffer to be ready.
317 return doGLFenceWaitLocked();
318}
319
Chia-I Wuc91077c2017-11-27 13:32:04 -0800320status_t BufferLayerConsumer::checkAndUpdateEglStateLocked() {
Chia-I Wuf1405182017-11-27 11:29:21 -0800321 EGLDisplay dpy = eglGetCurrentDisplay();
322 EGLContext ctx = eglGetCurrentContext();
323
Chia-I Wuc91077c2017-11-27 13:32:04 -0800324 // if this is the first time we're called, mEglDisplay/mEglContext have
325 // never been set, so don't error out (below).
326 if (mEglDisplay == EGL_NO_DISPLAY) {
327 mEglDisplay = dpy;
328 }
329 if (mEglContext == EGL_NO_CONTEXT) {
330 mEglContext = ctx;
Chia-I Wuf1405182017-11-27 11:29:21 -0800331 }
332
333 if (mEglDisplay != dpy || dpy == EGL_NO_DISPLAY) {
334 BLC_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
335 return INVALID_OPERATION;
336 }
337
338 if (mEglContext != ctx || ctx == EGL_NO_CONTEXT) {
339 BLC_LOGE("checkAndUpdateEglState: invalid current EGLContext");
340 return INVALID_OPERATION;
341 }
342
Chia-I Wuf1405182017-11-27 11:29:21 -0800343 return NO_ERROR;
344}
345
346void BufferLayerConsumer::setReleaseFence(const sp<Fence>& fence) {
347 if (fence->isValid() && mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
348 status_t err =
349 addReleaseFence(mCurrentTexture, mCurrentTextureImage->graphicBuffer(), fence);
350 if (err != OK) {
351 BLC_LOGE("setReleaseFence: failed to add the fence: %s (%d)", strerror(-err), err);
352 }
353 }
354}
355
Chia-I Wuf1405182017-11-27 11:29:21 -0800356status_t BufferLayerConsumer::syncForReleaseLocked(EGLDisplay dpy) {
357 BLC_LOGV("syncForReleaseLocked");
358
359 if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
360 if (SyncFeatures::getInstance().useNativeFenceSync()) {
361 EGLSyncKHR sync = eglCreateSyncKHR(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
362 if (sync == EGL_NO_SYNC_KHR) {
363 BLC_LOGE("syncForReleaseLocked: error creating EGL fence: %#x", eglGetError());
364 return UNKNOWN_ERROR;
365 }
366 glFlush();
367 int fenceFd = eglDupNativeFenceFDANDROID(dpy, sync);
368 eglDestroySyncKHR(dpy, sync);
369 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
370 BLC_LOGE("syncForReleaseLocked: error dup'ing native fence "
371 "fd: %#x",
372 eglGetError());
373 return UNKNOWN_ERROR;
374 }
375 sp<Fence> fence(new Fence(fenceFd));
376 status_t err = addReleaseFenceLocked(mCurrentTexture,
377 mCurrentTextureImage->graphicBuffer(), fence);
378 if (err != OK) {
379 BLC_LOGE("syncForReleaseLocked: error adding release fence: "
380 "%s (%d)",
381 strerror(-err), err);
382 return err;
383 }
Chia-I Wuf1405182017-11-27 11:29:21 -0800384 }
385 }
386
387 return OK;
388}
389
390uint32_t BufferLayerConsumer::getCurrentTextureTarget() const {
391 return mTexTarget;
392}
393
394void BufferLayerConsumer::getTransformMatrix(float mtx[16]) {
395 Mutex::Autolock lock(mMutex);
396 memcpy(mtx, mCurrentTransformMatrix, sizeof(mCurrentTransformMatrix));
397}
398
399void BufferLayerConsumer::setFilteringEnabled(bool enabled) {
400 Mutex::Autolock lock(mMutex);
401 if (mAbandoned) {
402 BLC_LOGE("setFilteringEnabled: BufferLayerConsumer is abandoned!");
403 return;
404 }
405 bool needsRecompute = mFilteringEnabled != enabled;
406 mFilteringEnabled = enabled;
407
408 if (needsRecompute && mCurrentTextureImage == NULL) {
409 BLC_LOGD("setFilteringEnabled called with mCurrentTextureImage == NULL");
410 }
411
412 if (needsRecompute && mCurrentTextureImage != NULL) {
413 computeCurrentTransformMatrixLocked();
414 }
415}
416
417void BufferLayerConsumer::computeCurrentTransformMatrixLocked() {
418 BLC_LOGV("computeCurrentTransformMatrixLocked");
419 sp<GraphicBuffer> buf =
420 (mCurrentTextureImage == nullptr) ? nullptr : mCurrentTextureImage->graphicBuffer();
421 if (buf == nullptr) {
422 BLC_LOGD("computeCurrentTransformMatrixLocked: "
423 "mCurrentTextureImage is NULL");
424 }
425 computeTransformMatrix(mCurrentTransformMatrix, buf,
426 isEglImageCroppable(mCurrentCrop) ? Rect::EMPTY_RECT : mCurrentCrop,
427 mCurrentTransform, mFilteringEnabled);
428}
429
430void BufferLayerConsumer::computeTransformMatrix(float outTransform[16],
431 const sp<GraphicBuffer>& buf, const Rect& cropRect,
432 uint32_t transform, bool filtering) {
433 // Transform matrices
434 static const mat4 mtxFlipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
435 static const mat4 mtxFlipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
436 static const mat4 mtxRot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
437
438 mat4 xform;
439 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
440 xform *= mtxFlipH;
441 }
442 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
443 xform *= mtxFlipV;
444 }
445 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
446 xform *= mtxRot90;
447 }
448
449 if (!cropRect.isEmpty()) {
450 float tx = 0.0f, ty = 0.0f, sx = 1.0f, sy = 1.0f;
451 float bufferWidth = buf->getWidth();
452 float bufferHeight = buf->getHeight();
453 float shrinkAmount = 0.0f;
454 if (filtering) {
455 // In order to prevent bilinear sampling beyond the edge of the
456 // crop rectangle we may need to shrink it by 2 texels in each
457 // dimension. Normally this would just need to take 1/2 a texel
458 // off each end, but because the chroma channels of YUV420 images
459 // are subsampled we may need to shrink the crop region by a whole
460 // texel on each side.
461 switch (buf->getPixelFormat()) {
462 case PIXEL_FORMAT_RGBA_8888:
463 case PIXEL_FORMAT_RGBX_8888:
464 case PIXEL_FORMAT_RGBA_FP16:
465 case PIXEL_FORMAT_RGBA_1010102:
466 case PIXEL_FORMAT_RGB_888:
467 case PIXEL_FORMAT_RGB_565:
468 case PIXEL_FORMAT_BGRA_8888:
469 // We know there's no subsampling of any channels, so we
470 // only need to shrink by a half a pixel.
471 shrinkAmount = 0.5;
472 break;
473
474 default:
475 // If we don't recognize the format, we must assume the
476 // worst case (that we care about), which is YUV420.
477 shrinkAmount = 1.0;
478 break;
479 }
480 }
481
482 // Only shrink the dimensions that are not the size of the buffer.
483 if (cropRect.width() < bufferWidth) {
484 tx = (float(cropRect.left) + shrinkAmount) / bufferWidth;
485 sx = (float(cropRect.width()) - (2.0f * shrinkAmount)) / bufferWidth;
486 }
487 if (cropRect.height() < bufferHeight) {
488 ty = (float(bufferHeight - cropRect.bottom) + shrinkAmount) / bufferHeight;
489 sy = (float(cropRect.height()) - (2.0f * shrinkAmount)) / bufferHeight;
490 }
491
492 mat4 crop(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1);
493 xform = crop * xform;
494 }
495
496 // SurfaceFlinger expects the top of its window textures to be at a Y
497 // coordinate of 0, so BufferLayerConsumer must behave the same way. We don't
498 // want to expose this to applications, however, so we must add an
499 // additional vertical flip to the transform after all the other transforms.
500 xform = mtxFlipV * xform;
501
502 memcpy(outTransform, xform.asArray(), sizeof(xform));
503}
504
505Rect BufferLayerConsumer::scaleDownCrop(const Rect& crop, uint32_t bufferWidth,
506 uint32_t bufferHeight) {
507 Rect outCrop = crop;
508
509 uint32_t newWidth = static_cast<uint32_t>(crop.width());
510 uint32_t newHeight = static_cast<uint32_t>(crop.height());
511
512 if (newWidth * bufferHeight > newHeight * bufferWidth) {
513 newWidth = newHeight * bufferWidth / bufferHeight;
514 ALOGV("too wide: newWidth = %d", newWidth);
515 } else if (newWidth * bufferHeight < newHeight * bufferWidth) {
516 newHeight = newWidth * bufferHeight / bufferWidth;
517 ALOGV("too tall: newHeight = %d", newHeight);
518 }
519
520 uint32_t currentWidth = static_cast<uint32_t>(crop.width());
521 uint32_t currentHeight = static_cast<uint32_t>(crop.height());
522
523 // The crop is too wide
524 if (newWidth < currentWidth) {
525 uint32_t dw = currentWidth - newWidth;
526 auto halfdw = dw / 2;
527 outCrop.left += halfdw;
528 // Not halfdw because it would subtract 1 too few when dw is odd
529 outCrop.right -= (dw - halfdw);
530 // The crop is too tall
531 } else if (newHeight < currentHeight) {
532 uint32_t dh = currentHeight - newHeight;
533 auto halfdh = dh / 2;
534 outCrop.top += halfdh;
535 // Not halfdh because it would subtract 1 too few when dh is odd
536 outCrop.bottom -= (dh - halfdh);
537 }
538
539 ALOGV("getCurrentCrop final crop [%d,%d,%d,%d]", outCrop.left, outCrop.top, outCrop.right,
540 outCrop.bottom);
541
542 return outCrop;
543}
544
545nsecs_t BufferLayerConsumer::getTimestamp() {
546 BLC_LOGV("getTimestamp");
547 Mutex::Autolock lock(mMutex);
548 return mCurrentTimestamp;
549}
550
551android_dataspace BufferLayerConsumer::getCurrentDataSpace() {
552 BLC_LOGV("getCurrentDataSpace");
553 Mutex::Autolock lock(mMutex);
554 return mCurrentDataSpace;
555}
556
557uint64_t BufferLayerConsumer::getFrameNumber() {
558 BLC_LOGV("getFrameNumber");
559 Mutex::Autolock lock(mMutex);
560 return mCurrentFrameNumber;
561}
562
563sp<GraphicBuffer> BufferLayerConsumer::getCurrentBuffer(int* outSlot) const {
564 Mutex::Autolock lock(mMutex);
565
566 if (outSlot != nullptr) {
567 *outSlot = mCurrentTexture;
568 }
569
570 return (mCurrentTextureImage == nullptr) ? NULL : mCurrentTextureImage->graphicBuffer();
571}
572
573Rect BufferLayerConsumer::getCurrentCrop() const {
574 Mutex::Autolock lock(mMutex);
575 return (mCurrentScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP)
576 ? scaleDownCrop(mCurrentCrop, mDefaultWidth, mDefaultHeight)
577 : mCurrentCrop;
578}
579
580uint32_t BufferLayerConsumer::getCurrentTransform() const {
581 Mutex::Autolock lock(mMutex);
582 return mCurrentTransform;
583}
584
585uint32_t BufferLayerConsumer::getCurrentScalingMode() const {
586 Mutex::Autolock lock(mMutex);
587 return mCurrentScalingMode;
588}
589
590sp<Fence> BufferLayerConsumer::getCurrentFence() const {
591 Mutex::Autolock lock(mMutex);
592 return mCurrentFence;
593}
594
595std::shared_ptr<FenceTime> BufferLayerConsumer::getCurrentFenceTime() const {
596 Mutex::Autolock lock(mMutex);
597 return mCurrentFenceTime;
598}
599
600status_t BufferLayerConsumer::doGLFenceWaitLocked() const {
601 EGLDisplay dpy = eglGetCurrentDisplay();
602 EGLContext ctx = eglGetCurrentContext();
603
604 if (mEglDisplay != dpy || mEglDisplay == EGL_NO_DISPLAY) {
605 BLC_LOGE("doGLFenceWait: invalid current EGLDisplay");
606 return INVALID_OPERATION;
607 }
608
609 if (mEglContext != ctx || mEglContext == EGL_NO_CONTEXT) {
610 BLC_LOGE("doGLFenceWait: invalid current EGLContext");
611 return INVALID_OPERATION;
612 }
613
614 if (mCurrentFence->isValid()) {
615 if (SyncFeatures::getInstance().useWaitSync()) {
616 // Create an EGLSyncKHR from the current fence.
617 int fenceFd = mCurrentFence->dup();
618 if (fenceFd == -1) {
619 BLC_LOGE("doGLFenceWait: error dup'ing fence fd: %d", errno);
620 return -errno;
621 }
622 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd, EGL_NONE};
623 EGLSyncKHR sync = eglCreateSyncKHR(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
624 if (sync == EGL_NO_SYNC_KHR) {
625 close(fenceFd);
626 BLC_LOGE("doGLFenceWait: error creating EGL fence: %#x", eglGetError());
627 return UNKNOWN_ERROR;
628 }
629
630 // XXX: The spec draft is inconsistent as to whether this should
631 // return an EGLint or void. Ignore the return value for now, as
632 // it's not strictly needed.
633 eglWaitSyncKHR(dpy, sync, 0);
634 EGLint eglErr = eglGetError();
635 eglDestroySyncKHR(dpy, sync);
636 if (eglErr != EGL_SUCCESS) {
637 BLC_LOGE("doGLFenceWait: error waiting for EGL fence: %#x", eglErr);
638 return UNKNOWN_ERROR;
639 }
640 } else {
641 status_t err = mCurrentFence->waitForever("BufferLayerConsumer::doGLFenceWaitLocked");
642 if (err != NO_ERROR) {
643 BLC_LOGE("doGLFenceWait: error waiting for fence: %d", err);
644 return err;
645 }
646 }
647 }
648
649 return NO_ERROR;
650}
651
652void BufferLayerConsumer::freeBufferLocked(int slotIndex) {
653 BLC_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
654 if (slotIndex == mCurrentTexture) {
655 mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
656 }
657 mEglSlots[slotIndex].mEglImage.clear();
658 ConsumerBase::freeBufferLocked(slotIndex);
659}
660
661void BufferLayerConsumer::abandonLocked() {
662 BLC_LOGV("abandonLocked");
663 mCurrentTextureImage.clear();
664 ConsumerBase::abandonLocked();
665}
666
667status_t BufferLayerConsumer::setConsumerUsageBits(uint64_t usage) {
668 return ConsumerBase::setConsumerUsageBits(usage | DEFAULT_USAGE_FLAGS);
669}
670
671void BufferLayerConsumer::dumpLocked(String8& result, const char* prefix) const {
672 result.appendFormat("%smTexName=%d mCurrentTexture=%d\n"
673 "%smCurrentCrop=[%d,%d,%d,%d] mCurrentTransform=%#x\n",
674 prefix, mTexName, mCurrentTexture, prefix, mCurrentCrop.left,
675 mCurrentCrop.top, mCurrentCrop.right, mCurrentCrop.bottom,
676 mCurrentTransform);
677
678 ConsumerBase::dumpLocked(result, prefix);
679}
680
681BufferLayerConsumer::EglImage::EglImage(sp<GraphicBuffer> graphicBuffer)
682 : mGraphicBuffer(graphicBuffer),
683 mEglImage(EGL_NO_IMAGE_KHR),
684 mEglDisplay(EGL_NO_DISPLAY),
685 mCropRect(Rect::EMPTY_RECT) {}
686
687BufferLayerConsumer::EglImage::~EglImage() {
688 if (mEglImage != EGL_NO_IMAGE_KHR) {
689 if (!eglDestroyImageKHR(mEglDisplay, mEglImage)) {
690 ALOGE("~EglImage: eglDestroyImageKHR failed");
691 }
692 eglTerminate(mEglDisplay);
693 }
694}
695
Chia-I Wuc91077c2017-11-27 13:32:04 -0800696status_t BufferLayerConsumer::EglImage::createIfNeeded(EGLDisplay eglDisplay,
697 const Rect& cropRect) {
Chia-I Wuf1405182017-11-27 11:29:21 -0800698 // If there's an image and it's no longer valid, destroy it.
699 bool haveImage = mEglImage != EGL_NO_IMAGE_KHR;
700 bool displayInvalid = mEglDisplay != eglDisplay;
701 bool cropInvalid = hasEglAndroidImageCrop() && mCropRect != cropRect;
Chia-I Wuc91077c2017-11-27 13:32:04 -0800702 if (haveImage && (displayInvalid || cropInvalid)) {
Chia-I Wuf1405182017-11-27 11:29:21 -0800703 if (!eglDestroyImageKHR(mEglDisplay, mEglImage)) {
704 ALOGE("createIfNeeded: eglDestroyImageKHR failed");
705 }
706 eglTerminate(mEglDisplay);
707 mEglImage = EGL_NO_IMAGE_KHR;
708 mEglDisplay = EGL_NO_DISPLAY;
709 }
710
711 // If there's no image, create one.
712 if (mEglImage == EGL_NO_IMAGE_KHR) {
713 mEglDisplay = eglDisplay;
714 mCropRect = cropRect;
715 mEglImage = createImage(mEglDisplay, mGraphicBuffer, mCropRect);
716 }
717
718 // Fail if we can't create a valid image.
719 if (mEglImage == EGL_NO_IMAGE_KHR) {
720 mEglDisplay = EGL_NO_DISPLAY;
721 mCropRect.makeInvalid();
722 const sp<GraphicBuffer>& buffer = mGraphicBuffer;
723 ALOGE("Failed to create image. size=%ux%u st=%u usage=%#" PRIx64 " fmt=%d",
724 buffer->getWidth(), buffer->getHeight(), buffer->getStride(), buffer->getUsage(),
725 buffer->getPixelFormat());
726 return UNKNOWN_ERROR;
727 }
728
729 return OK;
730}
731
732void BufferLayerConsumer::EglImage::bindToTextureTarget(uint32_t texTarget) {
733 glEGLImageTargetTexture2DOES(texTarget, static_cast<GLeglImageOES>(mEglImage));
734}
735
736EGLImageKHR BufferLayerConsumer::EglImage::createImage(EGLDisplay dpy,
737 const sp<GraphicBuffer>& graphicBuffer,
738 const Rect& crop) {
739 EGLClientBuffer cbuf = static_cast<EGLClientBuffer>(graphicBuffer->getNativeBuffer());
740 const bool createProtectedImage =
741 (graphicBuffer->getUsage() & GRALLOC_USAGE_PROTECTED) && hasEglProtectedContent();
742 EGLint attrs[] = {
743 EGL_IMAGE_PRESERVED_KHR,
744 EGL_TRUE,
745 EGL_IMAGE_CROP_LEFT_ANDROID,
746 crop.left,
747 EGL_IMAGE_CROP_TOP_ANDROID,
748 crop.top,
749 EGL_IMAGE_CROP_RIGHT_ANDROID,
750 crop.right,
751 EGL_IMAGE_CROP_BOTTOM_ANDROID,
752 crop.bottom,
753 createProtectedImage ? EGL_PROTECTED_CONTENT_EXT : EGL_NONE,
754 createProtectedImage ? EGL_TRUE : EGL_NONE,
755 EGL_NONE,
756 };
757 if (!crop.isValid()) {
758 // No crop rect to set, so leave the crop out of the attrib array. Make
759 // sure to propagate the protected content attrs if they are set.
760 attrs[2] = attrs[10];
761 attrs[3] = attrs[11];
762 attrs[4] = EGL_NONE;
763 } else if (!isEglImageCroppable(crop)) {
764 // The crop rect is not at the origin, so we can't set the crop on the
765 // EGLImage because that's not allowed by the EGL_ANDROID_image_crop
766 // extension. In the future we can add a layered extension that
767 // removes this restriction if there is hardware that can support it.
768 attrs[2] = attrs[10];
769 attrs[3] = attrs[11];
770 attrs[4] = EGL_NONE;
771 }
772 eglInitialize(dpy, 0, 0);
773 EGLImageKHR image =
774 eglCreateImageKHR(dpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, cbuf, attrs);
775 if (image == EGL_NO_IMAGE_KHR) {
776 EGLint error = eglGetError();
777 ALOGE("error creating EGLImage: %#x", error);
778 eglTerminate(dpy);
779 }
780 return image;
781}
782
783}; // namespace android