1 /*
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 #define LOG_TAG "Surface"
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19 //#define LOG_NDEBUG 0
20
21 #include <gui/Surface.h>
22
23 #include <condition_variable>
24 #include <deque>
25 #include <mutex>
26 #include <thread>
27
28 #include <inttypes.h>
29
30 #include <android/native_window.h>
31
32 #include <utils/Log.h>
33 #include <utils/Trace.h>
34 #include <utils/NativeHandle.h>
35
36 #include <ui/DisplayStatInfo.h>
37 #include <ui/Fence.h>
38 #include <ui/GraphicBuffer.h>
39 #include <ui/HdrCapabilities.h>
40 #include <ui/Region.h>
41
42 #include <gui/BufferItem.h>
43 #include <gui/IProducerListener.h>
44
45 #include <gui/ISurfaceComposer.h>
46 #include <gui/LayerState.h>
47 #include <private/gui/ComposerService.h>
48
49 namespace android {
50
51 using ui::ColorMode;
52 using ui::Dataspace;
53
54 namespace {
55
isInterceptorRegistrationOp(int op)56 bool isInterceptorRegistrationOp(int op) {
57 return op == NATIVE_WINDOW_SET_CANCEL_INTERCEPTOR ||
58 op == NATIVE_WINDOW_SET_DEQUEUE_INTERCEPTOR ||
59 op == NATIVE_WINDOW_SET_PERFORM_INTERCEPTOR ||
60 op == NATIVE_WINDOW_SET_QUEUE_INTERCEPTOR ||
61 op == NATIVE_WINDOW_SET_QUERY_INTERCEPTOR;
62 }
63
64 } // namespace
65
Surface(const sp<IGraphicBufferProducer> & bufferProducer,bool controlledByApp)66 Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp)
67 : mGraphicBufferProducer(bufferProducer),
68 mCrop(Rect::EMPTY_RECT),
69 mBufferAge(0),
70 mGenerationNumber(0),
71 mSharedBufferMode(false),
72 mAutoRefresh(false),
73 mSharedBufferSlot(BufferItem::INVALID_BUFFER_SLOT),
74 mSharedBufferHasBeenQueued(false),
75 mQueriedSupportedTimestamps(false),
76 mFrameTimestampsSupportsPresent(false),
77 mEnableFrameTimestamps(false),
78 mFrameEventHistory(std::make_unique<ProducerFrameEventHistory>()) {
79 // Initialize the ANativeWindow function pointers.
80 ANativeWindow::setSwapInterval = hook_setSwapInterval;
81 ANativeWindow::dequeueBuffer = hook_dequeueBuffer;
82 ANativeWindow::cancelBuffer = hook_cancelBuffer;
83 ANativeWindow::queueBuffer = hook_queueBuffer;
84 ANativeWindow::query = hook_query;
85 ANativeWindow::perform = hook_perform;
86
87 ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
88 ANativeWindow::cancelBuffer_DEPRECATED = hook_cancelBuffer_DEPRECATED;
89 ANativeWindow::lockBuffer_DEPRECATED = hook_lockBuffer_DEPRECATED;
90 ANativeWindow::queueBuffer_DEPRECATED = hook_queueBuffer_DEPRECATED;
91
92 const_cast<int&>(ANativeWindow::minSwapInterval) = 0;
93 const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;
94
95 mReqWidth = 0;
96 mReqHeight = 0;
97 mReqFormat = 0;
98 mReqUsage = 0;
99 mTimestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
100 mDataSpace = Dataspace::UNKNOWN;
101 mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
102 mTransform = 0;
103 mStickyTransform = 0;
104 mDefaultWidth = 0;
105 mDefaultHeight = 0;
106 mUserWidth = 0;
107 mUserHeight = 0;
108 mTransformHint = 0;
109 mConsumerRunningBehind = false;
110 mConnectedToCpu = false;
111 mProducerControlledByApp = controlledByApp;
112 mSwapIntervalZero = false;
113 mMaxBufferCount = NUM_BUFFER_SLOTS;
114 }
115
~Surface()116 Surface::~Surface() {
117 if (mConnectedToCpu) {
118 Surface::disconnect(NATIVE_WINDOW_API_CPU);
119 }
120 }
121
composerService() const122 sp<ISurfaceComposer> Surface::composerService() const {
123 return ComposerService::getComposerService();
124 }
125
now() const126 nsecs_t Surface::now() const {
127 return systemTime();
128 }
129
getIGraphicBufferProducer() const130 sp<IGraphicBufferProducer> Surface::getIGraphicBufferProducer() const {
131 return mGraphicBufferProducer;
132 }
133
setSidebandStream(const sp<NativeHandle> & stream)134 void Surface::setSidebandStream(const sp<NativeHandle>& stream) {
135 mGraphicBufferProducer->setSidebandStream(stream);
136 }
137
allocateBuffers()138 void Surface::allocateBuffers() {
139 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
140 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
141 mGraphicBufferProducer->allocateBuffers(reqWidth, reqHeight,
142 mReqFormat, mReqUsage);
143 }
144
setGenerationNumber(uint32_t generation)145 status_t Surface::setGenerationNumber(uint32_t generation) {
146 status_t result = mGraphicBufferProducer->setGenerationNumber(generation);
147 if (result == NO_ERROR) {
148 mGenerationNumber = generation;
149 }
150 return result;
151 }
152
getNextFrameNumber() const153 uint64_t Surface::getNextFrameNumber() const {
154 Mutex::Autolock lock(mMutex);
155 return mNextFrameNumber;
156 }
157
getConsumerName() const158 String8 Surface::getConsumerName() const {
159 return mGraphicBufferProducer->getConsumerName();
160 }
161
setDequeueTimeout(nsecs_t timeout)162 status_t Surface::setDequeueTimeout(nsecs_t timeout) {
163 return mGraphicBufferProducer->setDequeueTimeout(timeout);
164 }
165
getLastQueuedBuffer(sp<GraphicBuffer> * outBuffer,sp<Fence> * outFence,float outTransformMatrix[16])166 status_t Surface::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
167 sp<Fence>* outFence, float outTransformMatrix[16]) {
168 return mGraphicBufferProducer->getLastQueuedBuffer(outBuffer, outFence,
169 outTransformMatrix);
170 }
171
getDisplayRefreshCycleDuration(nsecs_t * outRefreshDuration)172 status_t Surface::getDisplayRefreshCycleDuration(nsecs_t* outRefreshDuration) {
173 ATRACE_CALL();
174
175 DisplayStatInfo stats;
176 status_t result = composerService()->getDisplayStats(nullptr, &stats);
177 if (result != NO_ERROR) {
178 return result;
179 }
180
181 *outRefreshDuration = stats.vsyncPeriod;
182
183 return NO_ERROR;
184 }
185
enableFrameTimestamps(bool enable)186 void Surface::enableFrameTimestamps(bool enable) {
187 Mutex::Autolock lock(mMutex);
188 // If going from disabled to enabled, get the initial values for
189 // compositor and display timing.
190 if (!mEnableFrameTimestamps && enable) {
191 FrameEventHistoryDelta delta;
192 mGraphicBufferProducer->getFrameTimestamps(&delta);
193 mFrameEventHistory->applyDelta(delta);
194 }
195 mEnableFrameTimestamps = enable;
196 }
197
getCompositorTiming(nsecs_t * compositeDeadline,nsecs_t * compositeInterval,nsecs_t * compositeToPresentLatency)198 status_t Surface::getCompositorTiming(
199 nsecs_t* compositeDeadline, nsecs_t* compositeInterval,
200 nsecs_t* compositeToPresentLatency) {
201 Mutex::Autolock lock(mMutex);
202 if (!mEnableFrameTimestamps) {
203 return INVALID_OPERATION;
204 }
205
206 if (compositeDeadline != nullptr) {
207 *compositeDeadline =
208 mFrameEventHistory->getNextCompositeDeadline(now());
209 }
210 if (compositeInterval != nullptr) {
211 *compositeInterval = mFrameEventHistory->getCompositeInterval();
212 }
213 if (compositeToPresentLatency != nullptr) {
214 *compositeToPresentLatency =
215 mFrameEventHistory->getCompositeToPresentLatency();
216 }
217 return NO_ERROR;
218 }
219
checkConsumerForUpdates(const FrameEvents * e,const uint64_t lastFrameNumber,const nsecs_t * outLatchTime,const nsecs_t * outFirstRefreshStartTime,const nsecs_t * outLastRefreshStartTime,const nsecs_t * outGpuCompositionDoneTime,const nsecs_t * outDisplayPresentTime,const nsecs_t * outDequeueReadyTime,const nsecs_t * outReleaseTime)220 static bool checkConsumerForUpdates(
221 const FrameEvents* e, const uint64_t lastFrameNumber,
222 const nsecs_t* outLatchTime,
223 const nsecs_t* outFirstRefreshStartTime,
224 const nsecs_t* outLastRefreshStartTime,
225 const nsecs_t* outGpuCompositionDoneTime,
226 const nsecs_t* outDisplayPresentTime,
227 const nsecs_t* outDequeueReadyTime,
228 const nsecs_t* outReleaseTime) {
229 bool checkForLatch = (outLatchTime != nullptr) && !e->hasLatchInfo();
230 bool checkForFirstRefreshStart = (outFirstRefreshStartTime != nullptr) &&
231 !e->hasFirstRefreshStartInfo();
232 bool checkForGpuCompositionDone = (outGpuCompositionDoneTime != nullptr) &&
233 !e->hasGpuCompositionDoneInfo();
234 bool checkForDisplayPresent = (outDisplayPresentTime != nullptr) &&
235 !e->hasDisplayPresentInfo();
236
237 // LastRefreshStart, DequeueReady, and Release are never available for the
238 // last frame.
239 bool checkForLastRefreshStart = (outLastRefreshStartTime != nullptr) &&
240 !e->hasLastRefreshStartInfo() &&
241 (e->frameNumber != lastFrameNumber);
242 bool checkForDequeueReady = (outDequeueReadyTime != nullptr) &&
243 !e->hasDequeueReadyInfo() && (e->frameNumber != lastFrameNumber);
244 bool checkForRelease = (outReleaseTime != nullptr) &&
245 !e->hasReleaseInfo() && (e->frameNumber != lastFrameNumber);
246
247 // RequestedPresent and Acquire info are always available producer-side.
248 return checkForLatch || checkForFirstRefreshStart ||
249 checkForLastRefreshStart || checkForGpuCompositionDone ||
250 checkForDisplayPresent || checkForDequeueReady || checkForRelease;
251 }
252
getFrameTimestamp(nsecs_t * dst,const nsecs_t & src)253 static void getFrameTimestamp(nsecs_t *dst, const nsecs_t& src) {
254 if (dst != nullptr) {
255 // We always get valid timestamps for these eventually.
256 *dst = (src == FrameEvents::TIMESTAMP_PENDING) ?
257 NATIVE_WINDOW_TIMESTAMP_PENDING : src;
258 }
259 }
260
getFrameTimestampFence(nsecs_t * dst,const std::shared_ptr<FenceTime> & src,bool fenceShouldBeKnown)261 static void getFrameTimestampFence(nsecs_t *dst,
262 const std::shared_ptr<FenceTime>& src, bool fenceShouldBeKnown) {
263 if (dst != nullptr) {
264 if (!fenceShouldBeKnown) {
265 *dst = NATIVE_WINDOW_TIMESTAMP_PENDING;
266 return;
267 }
268
269 nsecs_t signalTime = src->getSignalTime();
270 *dst = (signalTime == Fence::SIGNAL_TIME_PENDING) ?
271 NATIVE_WINDOW_TIMESTAMP_PENDING :
272 (signalTime == Fence::SIGNAL_TIME_INVALID) ?
273 NATIVE_WINDOW_TIMESTAMP_INVALID :
274 signalTime;
275 }
276 }
277
getFrameTimestamps(uint64_t frameNumber,nsecs_t * outRequestedPresentTime,nsecs_t * outAcquireTime,nsecs_t * outLatchTime,nsecs_t * outFirstRefreshStartTime,nsecs_t * outLastRefreshStartTime,nsecs_t * outGpuCompositionDoneTime,nsecs_t * outDisplayPresentTime,nsecs_t * outDequeueReadyTime,nsecs_t * outReleaseTime)278 status_t Surface::getFrameTimestamps(uint64_t frameNumber,
279 nsecs_t* outRequestedPresentTime, nsecs_t* outAcquireTime,
280 nsecs_t* outLatchTime, nsecs_t* outFirstRefreshStartTime,
281 nsecs_t* outLastRefreshStartTime, nsecs_t* outGpuCompositionDoneTime,
282 nsecs_t* outDisplayPresentTime, nsecs_t* outDequeueReadyTime,
283 nsecs_t* outReleaseTime) {
284 ATRACE_CALL();
285
286 Mutex::Autolock lock(mMutex);
287
288 if (!mEnableFrameTimestamps) {
289 return INVALID_OPERATION;
290 }
291
292 // Verify the requested timestamps are supported.
293 querySupportedTimestampsLocked();
294 if (outDisplayPresentTime != nullptr && !mFrameTimestampsSupportsPresent) {
295 return BAD_VALUE;
296 }
297
298 FrameEvents* events = mFrameEventHistory->getFrame(frameNumber);
299 if (events == nullptr) {
300 // If the entry isn't available in the producer, it's definitely not
301 // available in the consumer.
302 return NAME_NOT_FOUND;
303 }
304
305 // Update our cache of events if the requested events are not available.
306 if (checkConsumerForUpdates(events, mLastFrameNumber,
307 outLatchTime, outFirstRefreshStartTime, outLastRefreshStartTime,
308 outGpuCompositionDoneTime, outDisplayPresentTime,
309 outDequeueReadyTime, outReleaseTime)) {
310 FrameEventHistoryDelta delta;
311 mGraphicBufferProducer->getFrameTimestamps(&delta);
312 mFrameEventHistory->applyDelta(delta);
313 events = mFrameEventHistory->getFrame(frameNumber);
314 }
315
316 if (events == nullptr) {
317 // The entry was available before the update, but was overwritten
318 // after the update. Make sure not to send the wrong frame's data.
319 return NAME_NOT_FOUND;
320 }
321
322 getFrameTimestamp(outRequestedPresentTime, events->requestedPresentTime);
323 getFrameTimestamp(outLatchTime, events->latchTime);
324 getFrameTimestamp(outFirstRefreshStartTime, events->firstRefreshStartTime);
325 getFrameTimestamp(outLastRefreshStartTime, events->lastRefreshStartTime);
326 getFrameTimestamp(outDequeueReadyTime, events->dequeueReadyTime);
327
328 getFrameTimestampFence(outAcquireTime, events->acquireFence,
329 events->hasAcquireInfo());
330 getFrameTimestampFence(outGpuCompositionDoneTime,
331 events->gpuCompositionDoneFence,
332 events->hasGpuCompositionDoneInfo());
333 getFrameTimestampFence(outDisplayPresentTime, events->displayPresentFence,
334 events->hasDisplayPresentInfo());
335 getFrameTimestampFence(outReleaseTime, events->releaseFence,
336 events->hasReleaseInfo());
337
338 return NO_ERROR;
339 }
340
getWideColorSupport(bool * supported)341 status_t Surface::getWideColorSupport(bool* supported) {
342 ATRACE_CALL();
343
344 const sp<IBinder> display = composerService()->getInternalDisplayToken();
345 if (display == nullptr) {
346 return NAME_NOT_FOUND;
347 }
348
349 *supported = false;
350 status_t error = composerService()->isWideColorDisplay(display, supported);
351 return error;
352 }
353
getHdrSupport(bool * supported)354 status_t Surface::getHdrSupport(bool* supported) {
355 ATRACE_CALL();
356
357 const sp<IBinder> display = composerService()->getInternalDisplayToken();
358 if (display == nullptr) {
359 return NAME_NOT_FOUND;
360 }
361
362 HdrCapabilities hdrCapabilities;
363 status_t err =
364 composerService()->getHdrCapabilities(display, &hdrCapabilities);
365
366 if (err)
367 return err;
368
369 *supported = !hdrCapabilities.getSupportedHdrTypes().empty();
370
371 return NO_ERROR;
372 }
373
hook_setSwapInterval(ANativeWindow * window,int interval)374 int Surface::hook_setSwapInterval(ANativeWindow* window, int interval) {
375 Surface* c = getSelf(window);
376 return c->setSwapInterval(interval);
377 }
378
hook_dequeueBuffer(ANativeWindow * window,ANativeWindowBuffer ** buffer,int * fenceFd)379 int Surface::hook_dequeueBuffer(ANativeWindow* window,
380 ANativeWindowBuffer** buffer, int* fenceFd) {
381 Surface* c = getSelf(window);
382 {
383 std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
384 if (c->mDequeueInterceptor != nullptr) {
385 auto interceptor = c->mDequeueInterceptor;
386 auto data = c->mDequeueInterceptorData;
387 return interceptor(window, Surface::dequeueBufferInternal, data, buffer, fenceFd);
388 }
389 }
390 return c->dequeueBuffer(buffer, fenceFd);
391 }
392
dequeueBufferInternal(ANativeWindow * window,ANativeWindowBuffer ** buffer,int * fenceFd)393 int Surface::dequeueBufferInternal(ANativeWindow* window, ANativeWindowBuffer** buffer,
394 int* fenceFd) {
395 Surface* c = getSelf(window);
396 return c->dequeueBuffer(buffer, fenceFd);
397 }
398
hook_cancelBuffer(ANativeWindow * window,ANativeWindowBuffer * buffer,int fenceFd)399 int Surface::hook_cancelBuffer(ANativeWindow* window,
400 ANativeWindowBuffer* buffer, int fenceFd) {
401 Surface* c = getSelf(window);
402 {
403 std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
404 if (c->mCancelInterceptor != nullptr) {
405 auto interceptor = c->mCancelInterceptor;
406 auto data = c->mCancelInterceptorData;
407 return interceptor(window, Surface::cancelBufferInternal, data, buffer, fenceFd);
408 }
409 }
410 return c->cancelBuffer(buffer, fenceFd);
411 }
412
cancelBufferInternal(ANativeWindow * window,ANativeWindowBuffer * buffer,int fenceFd)413 int Surface::cancelBufferInternal(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
414 Surface* c = getSelf(window);
415 return c->cancelBuffer(buffer, fenceFd);
416 }
417
hook_queueBuffer(ANativeWindow * window,ANativeWindowBuffer * buffer,int fenceFd)418 int Surface::hook_queueBuffer(ANativeWindow* window,
419 ANativeWindowBuffer* buffer, int fenceFd) {
420 Surface* c = getSelf(window);
421 {
422 std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
423 if (c->mQueueInterceptor != nullptr) {
424 auto interceptor = c->mQueueInterceptor;
425 auto data = c->mQueueInterceptorData;
426 return interceptor(window, Surface::queueBufferInternal, data, buffer, fenceFd);
427 }
428 }
429 return c->queueBuffer(buffer, fenceFd);
430 }
431
queueBufferInternal(ANativeWindow * window,ANativeWindowBuffer * buffer,int fenceFd)432 int Surface::queueBufferInternal(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
433 Surface* c = getSelf(window);
434 return c->queueBuffer(buffer, fenceFd);
435 }
436
hook_dequeueBuffer_DEPRECATED(ANativeWindow * window,ANativeWindowBuffer ** buffer)437 int Surface::hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
438 ANativeWindowBuffer** buffer) {
439 Surface* c = getSelf(window);
440 ANativeWindowBuffer* buf;
441 int fenceFd = -1;
442 int result = c->dequeueBuffer(&buf, &fenceFd);
443 if (result != OK) {
444 return result;
445 }
446 sp<Fence> fence(new Fence(fenceFd));
447 int waitResult = fence->waitForever("dequeueBuffer_DEPRECATED");
448 if (waitResult != OK) {
449 ALOGE("dequeueBuffer_DEPRECATED: Fence::wait returned an error: %d",
450 waitResult);
451 c->cancelBuffer(buf, -1);
452 return waitResult;
453 }
454 *buffer = buf;
455 return result;
456 }
457
hook_cancelBuffer_DEPRECATED(ANativeWindow * window,ANativeWindowBuffer * buffer)458 int Surface::hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
459 ANativeWindowBuffer* buffer) {
460 Surface* c = getSelf(window);
461 return c->cancelBuffer(buffer, -1);
462 }
463
hook_lockBuffer_DEPRECATED(ANativeWindow * window,ANativeWindowBuffer * buffer)464 int Surface::hook_lockBuffer_DEPRECATED(ANativeWindow* window,
465 ANativeWindowBuffer* buffer) {
466 Surface* c = getSelf(window);
467 return c->lockBuffer_DEPRECATED(buffer);
468 }
469
hook_queueBuffer_DEPRECATED(ANativeWindow * window,ANativeWindowBuffer * buffer)470 int Surface::hook_queueBuffer_DEPRECATED(ANativeWindow* window,
471 ANativeWindowBuffer* buffer) {
472 Surface* c = getSelf(window);
473 return c->queueBuffer(buffer, -1);
474 }
475
hook_perform(ANativeWindow * window,int operation,...)476 int Surface::hook_perform(ANativeWindow* window, int operation, ...) {
477 va_list args;
478 va_start(args, operation);
479 Surface* c = getSelf(window);
480 int result;
481 // Don't acquire shared ownership of the interceptor mutex if we're going to
482 // do interceptor registration, as otherwise we'll deadlock on acquiring
483 // exclusive ownership.
484 if (!isInterceptorRegistrationOp(operation)) {
485 std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
486 if (c->mPerformInterceptor != nullptr) {
487 result = c->mPerformInterceptor(window, Surface::performInternal,
488 c->mPerformInterceptorData, operation, args);
489 va_end(args);
490 return result;
491 }
492 }
493 result = c->perform(operation, args);
494 va_end(args);
495 return result;
496 }
497
performInternal(ANativeWindow * window,int operation,va_list args)498 int Surface::performInternal(ANativeWindow* window, int operation, va_list args) {
499 Surface* c = getSelf(window);
500 return c->perform(operation, args);
501 }
502
hook_query(const ANativeWindow * window,int what,int * value)503 int Surface::hook_query(const ANativeWindow* window, int what, int* value) {
504 const Surface* c = getSelf(window);
505 {
506 std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
507 if (c->mQueryInterceptor != nullptr) {
508 auto interceptor = c->mQueryInterceptor;
509 auto data = c->mQueryInterceptorData;
510 return interceptor(window, Surface::queryInternal, data, what, value);
511 }
512 }
513 return c->query(what, value);
514 }
515
queryInternal(const ANativeWindow * window,int what,int * value)516 int Surface::queryInternal(const ANativeWindow* window, int what, int* value) {
517 const Surface* c = getSelf(window);
518 return c->query(what, value);
519 }
520
setSwapInterval(int interval)521 int Surface::setSwapInterval(int interval) {
522 ATRACE_CALL();
523 // EGL specification states:
524 // interval is silently clamped to minimum and maximum implementation
525 // dependent values before being stored.
526
527 if (interval < minSwapInterval)
528 interval = minSwapInterval;
529
530 if (interval > maxSwapInterval)
531 interval = maxSwapInterval;
532
533 const bool wasSwapIntervalZero = mSwapIntervalZero;
534 mSwapIntervalZero = (interval == 0);
535
536 if (mSwapIntervalZero != wasSwapIntervalZero) {
537 mGraphicBufferProducer->setAsyncMode(mSwapIntervalZero);
538 }
539
540 return NO_ERROR;
541 }
542
543 class FenceMonitor {
544 public:
FenceMonitor(const char * name)545 explicit FenceMonitor(const char* name) : mName(name), mFencesQueued(0), mFencesSignaled(0) {
546 std::thread thread(&FenceMonitor::loop, this);
547 pthread_setname_np(thread.native_handle(), mName);
548 thread.detach();
549 }
550
queueFence(const sp<Fence> & fence)551 void queueFence(const sp<Fence>& fence) {
552 char message[64];
553
554 std::lock_guard<std::mutex> lock(mMutex);
555 if (fence->getSignalTime() != Fence::SIGNAL_TIME_PENDING) {
556 snprintf(message, sizeof(message), "%s fence %u has signaled", mName, mFencesQueued);
557 ATRACE_NAME(message);
558 // Need an increment on both to make the trace number correct.
559 mFencesQueued++;
560 mFencesSignaled++;
561 return;
562 }
563 snprintf(message, sizeof(message), "Trace %s fence %u", mName, mFencesQueued);
564 ATRACE_NAME(message);
565
566 mQueue.push_back(fence);
567 mCondition.notify_one();
568 mFencesQueued++;
569 ATRACE_INT(mName, int32_t(mQueue.size()));
570 }
571
572 private:
573 #pragma clang diagnostic push
574 #pragma clang diagnostic ignored "-Wmissing-noreturn"
loop()575 void loop() {
576 while (true) {
577 threadLoop();
578 }
579 }
580 #pragma clang diagnostic pop
581
threadLoop()582 void threadLoop() {
583 sp<Fence> fence;
584 uint32_t fenceNum;
585 {
586 std::unique_lock<std::mutex> lock(mMutex);
587 while (mQueue.empty()) {
588 mCondition.wait(lock);
589 }
590 fence = mQueue[0];
591 fenceNum = mFencesSignaled;
592 }
593 {
594 char message[64];
595 snprintf(message, sizeof(message), "waiting for %s %u", mName, fenceNum);
596 ATRACE_NAME(message);
597
598 status_t result = fence->waitForever(message);
599 if (result != OK) {
600 ALOGE("Error waiting for fence: %d", result);
601 }
602 }
603 {
604 std::lock_guard<std::mutex> lock(mMutex);
605 mQueue.pop_front();
606 mFencesSignaled++;
607 ATRACE_INT(mName, int32_t(mQueue.size()));
608 }
609 }
610
611 const char* mName;
612 uint32_t mFencesQueued;
613 uint32_t mFencesSignaled;
614 std::deque<sp<Fence>> mQueue;
615 std::condition_variable mCondition;
616 std::mutex mMutex;
617 };
618
dequeueBuffer(android_native_buffer_t ** buffer,int * fenceFd)619 int Surface::dequeueBuffer(android_native_buffer_t** buffer, int* fenceFd) {
620 ATRACE_CALL();
621 ALOGV("Surface::dequeueBuffer");
622
623 uint32_t reqWidth;
624 uint32_t reqHeight;
625 PixelFormat reqFormat;
626 uint64_t reqUsage;
627 bool enableFrameTimestamps;
628
629 {
630 Mutex::Autolock lock(mMutex);
631 if (mReportRemovedBuffers) {
632 mRemovedBuffers.clear();
633 }
634
635 reqWidth = mReqWidth ? mReqWidth : mUserWidth;
636 reqHeight = mReqHeight ? mReqHeight : mUserHeight;
637
638 reqFormat = mReqFormat;
639 reqUsage = mReqUsage;
640
641 enableFrameTimestamps = mEnableFrameTimestamps;
642
643 if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot !=
644 BufferItem::INVALID_BUFFER_SLOT) {
645 sp<GraphicBuffer>& gbuf(mSlots[mSharedBufferSlot].buffer);
646 if (gbuf != nullptr) {
647 *buffer = gbuf.get();
648 *fenceFd = -1;
649 return OK;
650 }
651 }
652 } // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffer
653
654 int buf = -1;
655 sp<Fence> fence;
656 nsecs_t startTime = systemTime();
657
658 FrameEventHistoryDelta frameTimestamps;
659 status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, reqWidth, reqHeight,
660 reqFormat, reqUsage, &mBufferAge,
661 enableFrameTimestamps ? &frameTimestamps
662 : nullptr);
663 mLastDequeueDuration = systemTime() - startTime;
664
665 if (result < 0) {
666 ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer"
667 "(%d, %d, %d, %#" PRIx64 ") failed: %d",
668 reqWidth, reqHeight, reqFormat, reqUsage, result);
669 return result;
670 }
671
672 if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
673 ALOGE("dequeueBuffer: IGraphicBufferProducer returned invalid slot number %d", buf);
674 android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
675 return FAILED_TRANSACTION;
676 }
677
678 Mutex::Autolock lock(mMutex);
679
680 // Write this while holding the mutex
681 mLastDequeueStartTime = startTime;
682
683 sp<GraphicBuffer>& gbuf(mSlots[buf].buffer);
684
685 // this should never happen
686 ALOGE_IF(fence == nullptr, "Surface::dequeueBuffer: received null Fence! buf=%d", buf);
687
688 if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
689 static FenceMonitor hwcReleaseThread("HWC release");
690 hwcReleaseThread.queueFence(fence);
691 }
692
693 if (result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
694 freeAllBuffers();
695 }
696
697 if (enableFrameTimestamps) {
698 mFrameEventHistory->applyDelta(frameTimestamps);
699 }
700
701 if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == nullptr) {
702 if (mReportRemovedBuffers && (gbuf != nullptr)) {
703 mRemovedBuffers.push_back(gbuf);
704 }
705 result = mGraphicBufferProducer->requestBuffer(buf, &gbuf);
706 if (result != NO_ERROR) {
707 ALOGE("dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: %d", result);
708 mGraphicBufferProducer->cancelBuffer(buf, fence);
709 return result;
710 }
711 }
712
713 if (fence->isValid()) {
714 *fenceFd = fence->dup();
715 if (*fenceFd == -1) {
716 ALOGE("dequeueBuffer: error duping fence: %d", errno);
717 // dup() should never fail; something is badly wrong. Soldier on
718 // and hope for the best; the worst that should happen is some
719 // visible corruption that lasts until the next frame.
720 }
721 } else {
722 *fenceFd = -1;
723 }
724
725 *buffer = gbuf.get();
726
727 if (mSharedBufferMode && mAutoRefresh) {
728 mSharedBufferSlot = buf;
729 mSharedBufferHasBeenQueued = false;
730 } else if (mSharedBufferSlot == buf) {
731 mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
732 mSharedBufferHasBeenQueued = false;
733 }
734
735 mDequeuedSlots.insert(buf);
736
737 return OK;
738 }
739
cancelBuffer(android_native_buffer_t * buffer,int fenceFd)740 int Surface::cancelBuffer(android_native_buffer_t* buffer,
741 int fenceFd) {
742 ATRACE_CALL();
743 ALOGV("Surface::cancelBuffer");
744 Mutex::Autolock lock(mMutex);
745 int i = getSlotFromBufferLocked(buffer);
746 if (i < 0) {
747 if (fenceFd >= 0) {
748 close(fenceFd);
749 }
750 return i;
751 }
752 if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
753 if (fenceFd >= 0) {
754 close(fenceFd);
755 }
756 return OK;
757 }
758 sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
759 mGraphicBufferProducer->cancelBuffer(i, fence);
760
761 if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
762 mSharedBufferHasBeenQueued = true;
763 }
764
765 mDequeuedSlots.erase(i);
766
767 return OK;
768 }
769
getSlotFromBufferLocked(android_native_buffer_t * buffer) const770 int Surface::getSlotFromBufferLocked(
771 android_native_buffer_t* buffer) const {
772 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
773 if (mSlots[i].buffer != nullptr &&
774 mSlots[i].buffer->handle == buffer->handle) {
775 return i;
776 }
777 }
778 ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
779 return BAD_VALUE;
780 }
781
lockBuffer_DEPRECATED(android_native_buffer_t * buffer)782 int Surface::lockBuffer_DEPRECATED(android_native_buffer_t* buffer __attribute__((unused))) {
783 ALOGV("Surface::lockBuffer");
784 Mutex::Autolock lock(mMutex);
785 return OK;
786 }
787
queueBuffer(android_native_buffer_t * buffer,int fenceFd)788 int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
789 ATRACE_CALL();
790 ALOGV("Surface::queueBuffer");
791 Mutex::Autolock lock(mMutex);
792 int64_t timestamp;
793 bool isAutoTimestamp = false;
794
795 if (mTimestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
796 timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
797 isAutoTimestamp = true;
798 ALOGV("Surface::queueBuffer making up timestamp: %.2f ms",
799 timestamp / 1000000.0);
800 } else {
801 timestamp = mTimestamp;
802 }
803 int i = getSlotFromBufferLocked(buffer);
804 if (i < 0) {
805 if (fenceFd >= 0) {
806 close(fenceFd);
807 }
808 return i;
809 }
810 if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
811 if (fenceFd >= 0) {
812 close(fenceFd);
813 }
814 return OK;
815 }
816
817
818 // Make sure the crop rectangle is entirely inside the buffer.
819 Rect crop(Rect::EMPTY_RECT);
820 mCrop.intersect(Rect(buffer->width, buffer->height), &crop);
821
822 sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
823 IGraphicBufferProducer::QueueBufferOutput output;
824 IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
825 static_cast<android_dataspace>(mDataSpace), crop, mScalingMode,
826 mTransform ^ mStickyTransform, fence, mStickyTransform,
827 mEnableFrameTimestamps);
828
829 // we should send HDR metadata as needed if this becomes a bottleneck
830 input.setHdrMetadata(mHdrMetadata);
831
832 if (mConnectedToCpu || mDirtyRegion.bounds() == Rect::INVALID_RECT) {
833 input.setSurfaceDamage(Region::INVALID_REGION);
834 } else {
835 // Here we do two things:
836 // 1) The surface damage was specified using the OpenGL ES convention of
837 // the origin being in the bottom-left corner. Here we flip to the
838 // convention that the rest of the system uses (top-left corner) by
839 // subtracting all top/bottom coordinates from the buffer height.
840 // 2) If the buffer is coming in rotated (for example, because the EGL
841 // implementation is reacting to the transform hint coming back from
842 // SurfaceFlinger), the surface damage needs to be rotated the
843 // opposite direction, since it was generated assuming an unrotated
844 // buffer (the app doesn't know that the EGL implementation is
845 // reacting to the transform hint behind its back). The
846 // transformations in the switch statement below apply those
847 // complementary rotations (e.g., if 90 degrees, rotate 270 degrees).
848
849 int width = buffer->width;
850 int height = buffer->height;
851 bool rotated90 = (mTransform ^ mStickyTransform) &
852 NATIVE_WINDOW_TRANSFORM_ROT_90;
853 if (rotated90) {
854 std::swap(width, height);
855 }
856
857 Region flippedRegion;
858 for (auto rect : mDirtyRegion) {
859 int left = rect.left;
860 int right = rect.right;
861 int top = height - rect.bottom; // Flip from OpenGL convention
862 int bottom = height - rect.top; // Flip from OpenGL convention
863 switch (mTransform ^ mStickyTransform) {
864 case NATIVE_WINDOW_TRANSFORM_ROT_90: {
865 // Rotate 270 degrees
866 Rect flippedRect{top, width - right, bottom, width - left};
867 flippedRegion.orSelf(flippedRect);
868 break;
869 }
870 case NATIVE_WINDOW_TRANSFORM_ROT_180: {
871 // Rotate 180 degrees
872 Rect flippedRect{width - right, height - bottom,
873 width - left, height - top};
874 flippedRegion.orSelf(flippedRect);
875 break;
876 }
877 case NATIVE_WINDOW_TRANSFORM_ROT_270: {
878 // Rotate 90 degrees
879 Rect flippedRect{height - bottom, left,
880 height - top, right};
881 flippedRegion.orSelf(flippedRect);
882 break;
883 }
884 default: {
885 Rect flippedRect{left, top, right, bottom};
886 flippedRegion.orSelf(flippedRect);
887 break;
888 }
889 }
890 }
891
892 input.setSurfaceDamage(flippedRegion);
893 }
894
895 nsecs_t now = systemTime();
896 status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
897 mLastQueueDuration = systemTime() - now;
898 if (err != OK) {
899 ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
900 }
901
902 mDequeuedSlots.erase(i);
903
904 if (mEnableFrameTimestamps) {
905 mFrameEventHistory->applyDelta(output.frameTimestamps);
906 // Update timestamps with the local acquire fence.
907 // The consumer doesn't send it back to prevent us from having two
908 // file descriptors of the same fence.
909 mFrameEventHistory->updateAcquireFence(mNextFrameNumber,
910 std::make_shared<FenceTime>(fence));
911
912 // Cache timestamps of signaled fences so we can close their file
913 // descriptors.
914 mFrameEventHistory->updateSignalTimes();
915 }
916
917 mLastFrameNumber = mNextFrameNumber;
918
919 mDefaultWidth = output.width;
920 mDefaultHeight = output.height;
921 mNextFrameNumber = output.nextFrameNumber;
922
923 // Ignore transform hint if sticky transform is set or transform to display inverse flag is
924 // set.
925 if (mStickyTransform == 0 && !transformToDisplayInverse()) {
926 mTransformHint = output.transformHint;
927 }
928
929 mConsumerRunningBehind = (output.numPendingBuffers >= 2);
930
931 if (!mConnectedToCpu) {
932 // Clear surface damage back to full-buffer
933 mDirtyRegion = Region::INVALID_REGION;
934 }
935
936 if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
937 mSharedBufferHasBeenQueued = true;
938 }
939
940 mQueueBufferCondition.broadcast();
941
942 if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
943 static FenceMonitor gpuCompletionThread("GPU completion");
944 gpuCompletionThread.queueFence(fence);
945 }
946
947 return err;
948 }
949
querySupportedTimestampsLocked() const950 void Surface::querySupportedTimestampsLocked() const {
951 // mMutex must be locked when calling this method.
952
953 if (mQueriedSupportedTimestamps) {
954 return;
955 }
956 mQueriedSupportedTimestamps = true;
957
958 std::vector<FrameEvent> supportedFrameTimestamps;
959 status_t err = composerService()->getSupportedFrameTimestamps(
960 &supportedFrameTimestamps);
961
962 if (err != NO_ERROR) {
963 return;
964 }
965
966 for (auto sft : supportedFrameTimestamps) {
967 if (sft == FrameEvent::DISPLAY_PRESENT) {
968 mFrameTimestampsSupportsPresent = true;
969 }
970 }
971 }
972
query(int what,int * value) const973 int Surface::query(int what, int* value) const {
974 ATRACE_CALL();
975 ALOGV("Surface::query");
976 { // scope for the lock
977 Mutex::Autolock lock(mMutex);
978 switch (what) {
979 case NATIVE_WINDOW_FORMAT:
980 if (mReqFormat) {
981 *value = static_cast<int>(mReqFormat);
982 return NO_ERROR;
983 }
984 break;
985 case NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER: {
986 if (composerService()->authenticateSurfaceTexture(
987 mGraphicBufferProducer)) {
988 *value = 1;
989 } else {
990 *value = 0;
991 }
992 return NO_ERROR;
993 }
994 case NATIVE_WINDOW_CONCRETE_TYPE:
995 *value = NATIVE_WINDOW_SURFACE;
996 return NO_ERROR;
997 case NATIVE_WINDOW_DEFAULT_WIDTH:
998 *value = static_cast<int>(
999 mUserWidth ? mUserWidth : mDefaultWidth);
1000 return NO_ERROR;
1001 case NATIVE_WINDOW_DEFAULT_HEIGHT:
1002 *value = static_cast<int>(
1003 mUserHeight ? mUserHeight : mDefaultHeight);
1004 return NO_ERROR;
1005 case NATIVE_WINDOW_TRANSFORM_HINT:
1006 *value = static_cast<int>(mTransformHint);
1007 return NO_ERROR;
1008 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
1009 status_t err = NO_ERROR;
1010 if (!mConsumerRunningBehind) {
1011 *value = 0;
1012 } else {
1013 err = mGraphicBufferProducer->query(what, value);
1014 if (err == NO_ERROR) {
1015 mConsumerRunningBehind = *value;
1016 }
1017 }
1018 return err;
1019 }
1020 case NATIVE_WINDOW_BUFFER_AGE: {
1021 if (mBufferAge > INT32_MAX) {
1022 *value = 0;
1023 } else {
1024 *value = static_cast<int32_t>(mBufferAge);
1025 }
1026 return NO_ERROR;
1027 }
1028 case NATIVE_WINDOW_LAST_DEQUEUE_DURATION: {
1029 int64_t durationUs = mLastDequeueDuration / 1000;
1030 *value = durationUs > std::numeric_limits<int>::max() ?
1031 std::numeric_limits<int>::max() :
1032 static_cast<int>(durationUs);
1033 return NO_ERROR;
1034 }
1035 case NATIVE_WINDOW_LAST_QUEUE_DURATION: {
1036 int64_t durationUs = mLastQueueDuration / 1000;
1037 *value = durationUs > std::numeric_limits<int>::max() ?
1038 std::numeric_limits<int>::max() :
1039 static_cast<int>(durationUs);
1040 return NO_ERROR;
1041 }
1042 case NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT: {
1043 querySupportedTimestampsLocked();
1044 *value = mFrameTimestampsSupportsPresent ? 1 : 0;
1045 return NO_ERROR;
1046 }
1047 case NATIVE_WINDOW_IS_VALID: {
1048 *value = mGraphicBufferProducer != nullptr ? 1 : 0;
1049 return NO_ERROR;
1050 }
1051 case NATIVE_WINDOW_DATASPACE: {
1052 *value = static_cast<int>(mDataSpace);
1053 return NO_ERROR;
1054 }
1055 case NATIVE_WINDOW_MAX_BUFFER_COUNT: {
1056 *value = mMaxBufferCount;
1057 return NO_ERROR;
1058 }
1059 }
1060 }
1061 return mGraphicBufferProducer->query(what, value);
1062 }
1063
perform(int operation,va_list args)1064 int Surface::perform(int operation, va_list args)
1065 {
1066 int res = NO_ERROR;
1067 switch (operation) {
1068 case NATIVE_WINDOW_CONNECT:
1069 // deprecated. must return NO_ERROR.
1070 break;
1071 case NATIVE_WINDOW_DISCONNECT:
1072 // deprecated. must return NO_ERROR.
1073 break;
1074 case NATIVE_WINDOW_SET_USAGE:
1075 res = dispatchSetUsage(args);
1076 break;
1077 case NATIVE_WINDOW_SET_CROP:
1078 res = dispatchSetCrop(args);
1079 break;
1080 case NATIVE_WINDOW_SET_BUFFER_COUNT:
1081 res = dispatchSetBufferCount(args);
1082 break;
1083 case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
1084 res = dispatchSetBuffersGeometry(args);
1085 break;
1086 case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
1087 res = dispatchSetBuffersTransform(args);
1088 break;
1089 case NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM:
1090 res = dispatchSetBuffersStickyTransform(args);
1091 break;
1092 case NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP:
1093 res = dispatchSetBuffersTimestamp(args);
1094 break;
1095 case NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS:
1096 res = dispatchSetBuffersDimensions(args);
1097 break;
1098 case NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS:
1099 res = dispatchSetBuffersUserDimensions(args);
1100 break;
1101 case NATIVE_WINDOW_SET_BUFFERS_FORMAT:
1102 res = dispatchSetBuffersFormat(args);
1103 break;
1104 case NATIVE_WINDOW_LOCK:
1105 res = dispatchLock(args);
1106 break;
1107 case NATIVE_WINDOW_UNLOCK_AND_POST:
1108 res = dispatchUnlockAndPost(args);
1109 break;
1110 case NATIVE_WINDOW_SET_SCALING_MODE:
1111 res = dispatchSetScalingMode(args);
1112 break;
1113 case NATIVE_WINDOW_API_CONNECT:
1114 res = dispatchConnect(args);
1115 break;
1116 case NATIVE_WINDOW_API_DISCONNECT:
1117 res = dispatchDisconnect(args);
1118 break;
1119 case NATIVE_WINDOW_SET_SIDEBAND_STREAM:
1120 res = dispatchSetSidebandStream(args);
1121 break;
1122 case NATIVE_WINDOW_SET_BUFFERS_DATASPACE:
1123 res = dispatchSetBuffersDataSpace(args);
1124 break;
1125 case NATIVE_WINDOW_SET_BUFFERS_SMPTE2086_METADATA:
1126 res = dispatchSetBuffersSmpte2086Metadata(args);
1127 break;
1128 case NATIVE_WINDOW_SET_BUFFERS_CTA861_3_METADATA:
1129 res = dispatchSetBuffersCta8613Metadata(args);
1130 break;
1131 case NATIVE_WINDOW_SET_BUFFERS_HDR10_PLUS_METADATA:
1132 res = dispatchSetBuffersHdr10PlusMetadata(args);
1133 break;
1134 case NATIVE_WINDOW_SET_SURFACE_DAMAGE:
1135 res = dispatchSetSurfaceDamage(args);
1136 break;
1137 case NATIVE_WINDOW_SET_SHARED_BUFFER_MODE:
1138 res = dispatchSetSharedBufferMode(args);
1139 break;
1140 case NATIVE_WINDOW_SET_AUTO_REFRESH:
1141 res = dispatchSetAutoRefresh(args);
1142 break;
1143 case NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION:
1144 res = dispatchGetDisplayRefreshCycleDuration(args);
1145 break;
1146 case NATIVE_WINDOW_GET_NEXT_FRAME_ID:
1147 res = dispatchGetNextFrameId(args);
1148 break;
1149 case NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS:
1150 res = dispatchEnableFrameTimestamps(args);
1151 break;
1152 case NATIVE_WINDOW_GET_COMPOSITOR_TIMING:
1153 res = dispatchGetCompositorTiming(args);
1154 break;
1155 case NATIVE_WINDOW_GET_FRAME_TIMESTAMPS:
1156 res = dispatchGetFrameTimestamps(args);
1157 break;
1158 case NATIVE_WINDOW_GET_WIDE_COLOR_SUPPORT:
1159 res = dispatchGetWideColorSupport(args);
1160 break;
1161 case NATIVE_WINDOW_GET_HDR_SUPPORT:
1162 res = dispatchGetHdrSupport(args);
1163 break;
1164 case NATIVE_WINDOW_SET_USAGE64:
1165 res = dispatchSetUsage64(args);
1166 break;
1167 case NATIVE_WINDOW_GET_CONSUMER_USAGE64:
1168 res = dispatchGetConsumerUsage64(args);
1169 break;
1170 case NATIVE_WINDOW_SET_AUTO_PREROTATION:
1171 res = dispatchSetAutoPrerotation(args);
1172 break;
1173 case NATIVE_WINDOW_GET_LAST_DEQUEUE_START:
1174 res = dispatchGetLastDequeueStartTime(args);
1175 break;
1176 case NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT:
1177 res = dispatchSetDequeueTimeout(args);
1178 break;
1179 case NATIVE_WINDOW_GET_LAST_DEQUEUE_DURATION:
1180 res = dispatchGetLastDequeueDuration(args);
1181 break;
1182 case NATIVE_WINDOW_GET_LAST_QUEUE_DURATION:
1183 res = dispatchGetLastQueueDuration(args);
1184 break;
1185 case NATIVE_WINDOW_SET_FRAME_RATE:
1186 res = dispatchSetFrameRate(args);
1187 break;
1188 case NATIVE_WINDOW_SET_CANCEL_INTERCEPTOR:
1189 res = dispatchAddCancelInterceptor(args);
1190 break;
1191 case NATIVE_WINDOW_SET_DEQUEUE_INTERCEPTOR:
1192 res = dispatchAddDequeueInterceptor(args);
1193 break;
1194 case NATIVE_WINDOW_SET_PERFORM_INTERCEPTOR:
1195 res = dispatchAddPerformInterceptor(args);
1196 break;
1197 case NATIVE_WINDOW_SET_QUEUE_INTERCEPTOR:
1198 res = dispatchAddQueueInterceptor(args);
1199 break;
1200 case NATIVE_WINDOW_SET_QUERY_INTERCEPTOR:
1201 res = dispatchAddQueryInterceptor(args);
1202 break;
1203 case NATIVE_WINDOW_ALLOCATE_BUFFERS:
1204 allocateBuffers();
1205 res = NO_ERROR;
1206 break;
1207 case NATIVE_WINDOW_GET_LAST_QUEUED_BUFFER:
1208 res = dispatchGetLastQueuedBuffer(args);
1209 break;
1210 default:
1211 res = NAME_NOT_FOUND;
1212 break;
1213 }
1214 return res;
1215 }
1216
dispatchConnect(va_list args)1217 int Surface::dispatchConnect(va_list args) {
1218 int api = va_arg(args, int);
1219 return connect(api);
1220 }
1221
dispatchDisconnect(va_list args)1222 int Surface::dispatchDisconnect(va_list args) {
1223 int api = va_arg(args, int);
1224 return disconnect(api);
1225 }
1226
dispatchSetUsage(va_list args)1227 int Surface::dispatchSetUsage(va_list args) {
1228 uint64_t usage = va_arg(args, uint32_t);
1229 return setUsage(usage);
1230 }
1231
dispatchSetUsage64(va_list args)1232 int Surface::dispatchSetUsage64(va_list args) {
1233 uint64_t usage = va_arg(args, uint64_t);
1234 return setUsage(usage);
1235 }
1236
dispatchSetCrop(va_list args)1237 int Surface::dispatchSetCrop(va_list args) {
1238 android_native_rect_t const* rect = va_arg(args, android_native_rect_t*);
1239 return setCrop(reinterpret_cast<Rect const*>(rect));
1240 }
1241
dispatchSetBufferCount(va_list args)1242 int Surface::dispatchSetBufferCount(va_list args) {
1243 size_t bufferCount = va_arg(args, size_t);
1244 return setBufferCount(static_cast<int32_t>(bufferCount));
1245 }
1246
dispatchSetBuffersGeometry(va_list args)1247 int Surface::dispatchSetBuffersGeometry(va_list args) {
1248 uint32_t width = va_arg(args, uint32_t);
1249 uint32_t height = va_arg(args, uint32_t);
1250 PixelFormat format = va_arg(args, PixelFormat);
1251 int err = setBuffersDimensions(width, height);
1252 if (err != 0) {
1253 return err;
1254 }
1255 return setBuffersFormat(format);
1256 }
1257
dispatchSetBuffersDimensions(va_list args)1258 int Surface::dispatchSetBuffersDimensions(va_list args) {
1259 uint32_t width = va_arg(args, uint32_t);
1260 uint32_t height = va_arg(args, uint32_t);
1261 return setBuffersDimensions(width, height);
1262 }
1263
dispatchSetBuffersUserDimensions(va_list args)1264 int Surface::dispatchSetBuffersUserDimensions(va_list args) {
1265 uint32_t width = va_arg(args, uint32_t);
1266 uint32_t height = va_arg(args, uint32_t);
1267 return setBuffersUserDimensions(width, height);
1268 }
1269
dispatchSetBuffersFormat(va_list args)1270 int Surface::dispatchSetBuffersFormat(va_list args) {
1271 PixelFormat format = va_arg(args, PixelFormat);
1272 return setBuffersFormat(format);
1273 }
1274
dispatchSetScalingMode(va_list args)1275 int Surface::dispatchSetScalingMode(va_list args) {
1276 int mode = va_arg(args, int);
1277 return setScalingMode(mode);
1278 }
1279
dispatchSetBuffersTransform(va_list args)1280 int Surface::dispatchSetBuffersTransform(va_list args) {
1281 uint32_t transform = va_arg(args, uint32_t);
1282 return setBuffersTransform(transform);
1283 }
1284
dispatchSetBuffersStickyTransform(va_list args)1285 int Surface::dispatchSetBuffersStickyTransform(va_list args) {
1286 uint32_t transform = va_arg(args, uint32_t);
1287 return setBuffersStickyTransform(transform);
1288 }
1289
dispatchSetBuffersTimestamp(va_list args)1290 int Surface::dispatchSetBuffersTimestamp(va_list args) {
1291 int64_t timestamp = va_arg(args, int64_t);
1292 return setBuffersTimestamp(timestamp);
1293 }
1294
dispatchLock(va_list args)1295 int Surface::dispatchLock(va_list args) {
1296 ANativeWindow_Buffer* outBuffer = va_arg(args, ANativeWindow_Buffer*);
1297 ARect* inOutDirtyBounds = va_arg(args, ARect*);
1298 return lock(outBuffer, inOutDirtyBounds);
1299 }
1300
dispatchUnlockAndPost(va_list args)1301 int Surface::dispatchUnlockAndPost(va_list args __attribute__((unused))) {
1302 return unlockAndPost();
1303 }
1304
dispatchSetSidebandStream(va_list args)1305 int Surface::dispatchSetSidebandStream(va_list args) {
1306 native_handle_t* sH = va_arg(args, native_handle_t*);
1307 sp<NativeHandle> sidebandHandle = NativeHandle::create(sH, false);
1308 setSidebandStream(sidebandHandle);
1309 return OK;
1310 }
1311
dispatchSetBuffersDataSpace(va_list args)1312 int Surface::dispatchSetBuffersDataSpace(va_list args) {
1313 Dataspace dataspace = static_cast<Dataspace>(va_arg(args, int));
1314 return setBuffersDataSpace(dataspace);
1315 }
1316
dispatchSetBuffersSmpte2086Metadata(va_list args)1317 int Surface::dispatchSetBuffersSmpte2086Metadata(va_list args) {
1318 const android_smpte2086_metadata* metadata =
1319 va_arg(args, const android_smpte2086_metadata*);
1320 return setBuffersSmpte2086Metadata(metadata);
1321 }
1322
dispatchSetBuffersCta8613Metadata(va_list args)1323 int Surface::dispatchSetBuffersCta8613Metadata(va_list args) {
1324 const android_cta861_3_metadata* metadata =
1325 va_arg(args, const android_cta861_3_metadata*);
1326 return setBuffersCta8613Metadata(metadata);
1327 }
1328
dispatchSetBuffersHdr10PlusMetadata(va_list args)1329 int Surface::dispatchSetBuffersHdr10PlusMetadata(va_list args) {
1330 const size_t size = va_arg(args, size_t);
1331 const uint8_t* metadata = va_arg(args, const uint8_t*);
1332 return setBuffersHdr10PlusMetadata(size, metadata);
1333 }
1334
dispatchSetSurfaceDamage(va_list args)1335 int Surface::dispatchSetSurfaceDamage(va_list args) {
1336 android_native_rect_t* rects = va_arg(args, android_native_rect_t*);
1337 size_t numRects = va_arg(args, size_t);
1338 setSurfaceDamage(rects, numRects);
1339 return NO_ERROR;
1340 }
1341
dispatchSetSharedBufferMode(va_list args)1342 int Surface::dispatchSetSharedBufferMode(va_list args) {
1343 bool sharedBufferMode = va_arg(args, int);
1344 return setSharedBufferMode(sharedBufferMode);
1345 }
1346
dispatchSetAutoRefresh(va_list args)1347 int Surface::dispatchSetAutoRefresh(va_list args) {
1348 bool autoRefresh = va_arg(args, int);
1349 return setAutoRefresh(autoRefresh);
1350 }
1351
dispatchGetDisplayRefreshCycleDuration(va_list args)1352 int Surface::dispatchGetDisplayRefreshCycleDuration(va_list args) {
1353 nsecs_t* outRefreshDuration = va_arg(args, int64_t*);
1354 return getDisplayRefreshCycleDuration(outRefreshDuration);
1355 }
1356
dispatchGetNextFrameId(va_list args)1357 int Surface::dispatchGetNextFrameId(va_list args) {
1358 uint64_t* nextFrameId = va_arg(args, uint64_t*);
1359 *nextFrameId = getNextFrameNumber();
1360 return NO_ERROR;
1361 }
1362
dispatchEnableFrameTimestamps(va_list args)1363 int Surface::dispatchEnableFrameTimestamps(va_list args) {
1364 bool enable = va_arg(args, int);
1365 enableFrameTimestamps(enable);
1366 return NO_ERROR;
1367 }
1368
dispatchGetCompositorTiming(va_list args)1369 int Surface::dispatchGetCompositorTiming(va_list args) {
1370 nsecs_t* compositeDeadline = va_arg(args, int64_t*);
1371 nsecs_t* compositeInterval = va_arg(args, int64_t*);
1372 nsecs_t* compositeToPresentLatency = va_arg(args, int64_t*);
1373 return getCompositorTiming(compositeDeadline, compositeInterval,
1374 compositeToPresentLatency);
1375 }
1376
dispatchGetFrameTimestamps(va_list args)1377 int Surface::dispatchGetFrameTimestamps(va_list args) {
1378 uint64_t frameId = va_arg(args, uint64_t);
1379 nsecs_t* outRequestedPresentTime = va_arg(args, int64_t*);
1380 nsecs_t* outAcquireTime = va_arg(args, int64_t*);
1381 nsecs_t* outLatchTime = va_arg(args, int64_t*);
1382 nsecs_t* outFirstRefreshStartTime = va_arg(args, int64_t*);
1383 nsecs_t* outLastRefreshStartTime = va_arg(args, int64_t*);
1384 nsecs_t* outGpuCompositionDoneTime = va_arg(args, int64_t*);
1385 nsecs_t* outDisplayPresentTime = va_arg(args, int64_t*);
1386 nsecs_t* outDequeueReadyTime = va_arg(args, int64_t*);
1387 nsecs_t* outReleaseTime = va_arg(args, int64_t*);
1388 return getFrameTimestamps(frameId,
1389 outRequestedPresentTime, outAcquireTime, outLatchTime,
1390 outFirstRefreshStartTime, outLastRefreshStartTime,
1391 outGpuCompositionDoneTime, outDisplayPresentTime,
1392 outDequeueReadyTime, outReleaseTime);
1393 }
1394
dispatchGetWideColorSupport(va_list args)1395 int Surface::dispatchGetWideColorSupport(va_list args) {
1396 bool* outSupport = va_arg(args, bool*);
1397 return getWideColorSupport(outSupport);
1398 }
1399
dispatchGetHdrSupport(va_list args)1400 int Surface::dispatchGetHdrSupport(va_list args) {
1401 bool* outSupport = va_arg(args, bool*);
1402 return getHdrSupport(outSupport);
1403 }
1404
dispatchGetConsumerUsage64(va_list args)1405 int Surface::dispatchGetConsumerUsage64(va_list args) {
1406 uint64_t* usage = va_arg(args, uint64_t*);
1407 return getConsumerUsage(usage);
1408 }
1409
dispatchSetAutoPrerotation(va_list args)1410 int Surface::dispatchSetAutoPrerotation(va_list args) {
1411 bool autoPrerotation = va_arg(args, int);
1412 return setAutoPrerotation(autoPrerotation);
1413 }
1414
dispatchGetLastDequeueStartTime(va_list args)1415 int Surface::dispatchGetLastDequeueStartTime(va_list args) {
1416 int64_t* lastDequeueStartTime = va_arg(args, int64_t*);
1417 *lastDequeueStartTime = mLastDequeueStartTime;
1418 return NO_ERROR;
1419 }
1420
dispatchSetDequeueTimeout(va_list args)1421 int Surface::dispatchSetDequeueTimeout(va_list args) {
1422 nsecs_t timeout = va_arg(args, int64_t);
1423 return setDequeueTimeout(timeout);
1424 }
1425
dispatchGetLastDequeueDuration(va_list args)1426 int Surface::dispatchGetLastDequeueDuration(va_list args) {
1427 int64_t* lastDequeueDuration = va_arg(args, int64_t*);
1428 *lastDequeueDuration = mLastDequeueDuration;
1429 return NO_ERROR;
1430 }
1431
dispatchGetLastQueueDuration(va_list args)1432 int Surface::dispatchGetLastQueueDuration(va_list args) {
1433 int64_t* lastQueueDuration = va_arg(args, int64_t*);
1434 *lastQueueDuration = mLastQueueDuration;
1435 return NO_ERROR;
1436 }
1437
dispatchSetFrameRate(va_list args)1438 int Surface::dispatchSetFrameRate(va_list args) {
1439 float frameRate = static_cast<float>(va_arg(args, double));
1440 int8_t compatibility = static_cast<int8_t>(va_arg(args, int));
1441 return setFrameRate(frameRate, compatibility);
1442 }
1443
dispatchAddCancelInterceptor(va_list args)1444 int Surface::dispatchAddCancelInterceptor(va_list args) {
1445 ANativeWindow_cancelBufferInterceptor interceptor =
1446 va_arg(args, ANativeWindow_cancelBufferInterceptor);
1447 void* data = va_arg(args, void*);
1448 std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1449 mCancelInterceptor = interceptor;
1450 mCancelInterceptorData = data;
1451 return NO_ERROR;
1452 }
1453
dispatchAddDequeueInterceptor(va_list args)1454 int Surface::dispatchAddDequeueInterceptor(va_list args) {
1455 ANativeWindow_dequeueBufferInterceptor interceptor =
1456 va_arg(args, ANativeWindow_dequeueBufferInterceptor);
1457 void* data = va_arg(args, void*);
1458 std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1459 mDequeueInterceptor = interceptor;
1460 mDequeueInterceptorData = data;
1461 return NO_ERROR;
1462 }
1463
dispatchAddPerformInterceptor(va_list args)1464 int Surface::dispatchAddPerformInterceptor(va_list args) {
1465 ANativeWindow_performInterceptor interceptor = va_arg(args, ANativeWindow_performInterceptor);
1466 void* data = va_arg(args, void*);
1467 std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1468 mPerformInterceptor = interceptor;
1469 mPerformInterceptorData = data;
1470 return NO_ERROR;
1471 }
1472
dispatchAddQueueInterceptor(va_list args)1473 int Surface::dispatchAddQueueInterceptor(va_list args) {
1474 ANativeWindow_queueBufferInterceptor interceptor =
1475 va_arg(args, ANativeWindow_queueBufferInterceptor);
1476 void* data = va_arg(args, void*);
1477 std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1478 mQueueInterceptor = interceptor;
1479 mQueueInterceptorData = data;
1480 return NO_ERROR;
1481 }
1482
dispatchAddQueryInterceptor(va_list args)1483 int Surface::dispatchAddQueryInterceptor(va_list args) {
1484 ANativeWindow_queryInterceptor interceptor = va_arg(args, ANativeWindow_queryInterceptor);
1485 void* data = va_arg(args, void*);
1486 std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1487 mQueryInterceptor = interceptor;
1488 mQueryInterceptorData = data;
1489 return NO_ERROR;
1490 }
1491
dispatchGetLastQueuedBuffer(va_list args)1492 int Surface::dispatchGetLastQueuedBuffer(va_list args) {
1493 AHardwareBuffer** buffer = va_arg(args, AHardwareBuffer**);
1494 int* fence = va_arg(args, int*);
1495 float* matrix = va_arg(args, float*);
1496 sp<GraphicBuffer> graphicBuffer;
1497 sp<Fence> spFence;
1498
1499 int result = mGraphicBufferProducer->getLastQueuedBuffer(&graphicBuffer, &spFence, matrix);
1500
1501 if (graphicBuffer != nullptr) {
1502 *buffer = reinterpret_cast<AHardwareBuffer*>(graphicBuffer.get());
1503 AHardwareBuffer_acquire(*buffer);
1504 } else {
1505 *buffer = nullptr;
1506 }
1507
1508 if (spFence != nullptr) {
1509 *fence = spFence->dup();
1510 } else {
1511 *fence = -1;
1512 }
1513 return result;
1514 }
1515
transformToDisplayInverse()1516 bool Surface::transformToDisplayInverse() {
1517 return (mTransform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) ==
1518 NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
1519 }
1520
connect(int api)1521 int Surface::connect(int api) {
1522 static sp<IProducerListener> listener = new DummyProducerListener();
1523 return connect(api, listener);
1524 }
1525
connect(int api,const sp<IProducerListener> & listener)1526 int Surface::connect(int api, const sp<IProducerListener>& listener) {
1527 return connect(api, listener, false);
1528 }
1529
connect(int api,bool reportBufferRemoval,const sp<SurfaceListener> & sListener)1530 int Surface::connect(
1531 int api, bool reportBufferRemoval, const sp<SurfaceListener>& sListener) {
1532 if (sListener != nullptr) {
1533 mListenerProxy = new ProducerListenerProxy(this, sListener);
1534 }
1535 return connect(api, mListenerProxy, reportBufferRemoval);
1536 }
1537
connect(int api,const sp<IProducerListener> & listener,bool reportBufferRemoval)1538 int Surface::connect(
1539 int api, const sp<IProducerListener>& listener, bool reportBufferRemoval) {
1540 ATRACE_CALL();
1541 ALOGV("Surface::connect");
1542 Mutex::Autolock lock(mMutex);
1543 IGraphicBufferProducer::QueueBufferOutput output;
1544 mReportRemovedBuffers = reportBufferRemoval;
1545 int err = mGraphicBufferProducer->connect(listener, api, mProducerControlledByApp, &output);
1546 if (err == NO_ERROR) {
1547 mDefaultWidth = output.width;
1548 mDefaultHeight = output.height;
1549 mNextFrameNumber = output.nextFrameNumber;
1550 mMaxBufferCount = output.maxBufferCount;
1551
1552 // Ignore transform hint if sticky transform is set or transform to display inverse flag is
1553 // set. Transform hint should be ignored if the client is expected to always submit buffers
1554 // in the same orientation.
1555 if (mStickyTransform == 0 && !transformToDisplayInverse()) {
1556 mTransformHint = output.transformHint;
1557 }
1558
1559 mConsumerRunningBehind = (output.numPendingBuffers >= 2);
1560 }
1561 if (!err && api == NATIVE_WINDOW_API_CPU) {
1562 mConnectedToCpu = true;
1563 // Clear the dirty region in case we're switching from a non-CPU API
1564 mDirtyRegion.clear();
1565 } else if (!err) {
1566 // Initialize the dirty region for tracking surface damage
1567 mDirtyRegion = Region::INVALID_REGION;
1568 }
1569
1570 return err;
1571 }
1572
1573
disconnect(int api,IGraphicBufferProducer::DisconnectMode mode)1574 int Surface::disconnect(int api, IGraphicBufferProducer::DisconnectMode mode) {
1575 ATRACE_CALL();
1576 ALOGV("Surface::disconnect");
1577 Mutex::Autolock lock(mMutex);
1578 mRemovedBuffers.clear();
1579 mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1580 mSharedBufferHasBeenQueued = false;
1581 freeAllBuffers();
1582 int err = mGraphicBufferProducer->disconnect(api, mode);
1583 if (!err) {
1584 mReqFormat = 0;
1585 mReqWidth = 0;
1586 mReqHeight = 0;
1587 mReqUsage = 0;
1588 mCrop.clear();
1589 mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
1590 mTransform = 0;
1591 mStickyTransform = 0;
1592 mAutoPrerotation = false;
1593 mEnableFrameTimestamps = false;
1594 mMaxBufferCount = NUM_BUFFER_SLOTS;
1595
1596 if (api == NATIVE_WINDOW_API_CPU) {
1597 mConnectedToCpu = false;
1598 }
1599 }
1600 return err;
1601 }
1602
detachNextBuffer(sp<GraphicBuffer> * outBuffer,sp<Fence> * outFence)1603 int Surface::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
1604 sp<Fence>* outFence) {
1605 ATRACE_CALL();
1606 ALOGV("Surface::detachNextBuffer");
1607
1608 if (outBuffer == nullptr || outFence == nullptr) {
1609 return BAD_VALUE;
1610 }
1611
1612 Mutex::Autolock lock(mMutex);
1613 if (mReportRemovedBuffers) {
1614 mRemovedBuffers.clear();
1615 }
1616
1617 sp<GraphicBuffer> buffer(nullptr);
1618 sp<Fence> fence(nullptr);
1619 status_t result = mGraphicBufferProducer->detachNextBuffer(
1620 &buffer, &fence);
1621 if (result != NO_ERROR) {
1622 return result;
1623 }
1624
1625 *outBuffer = buffer;
1626 if (fence != nullptr && fence->isValid()) {
1627 *outFence = fence;
1628 } else {
1629 *outFence = Fence::NO_FENCE;
1630 }
1631
1632 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
1633 if (mSlots[i].buffer != nullptr &&
1634 mSlots[i].buffer->getId() == buffer->getId()) {
1635 if (mReportRemovedBuffers) {
1636 mRemovedBuffers.push_back(mSlots[i].buffer);
1637 }
1638 mSlots[i].buffer = nullptr;
1639 }
1640 }
1641
1642 return NO_ERROR;
1643 }
1644
attachBuffer(ANativeWindowBuffer * buffer)1645 int Surface::attachBuffer(ANativeWindowBuffer* buffer)
1646 {
1647 ATRACE_CALL();
1648 ALOGV("Surface::attachBuffer");
1649
1650 Mutex::Autolock lock(mMutex);
1651 if (mReportRemovedBuffers) {
1652 mRemovedBuffers.clear();
1653 }
1654
1655 sp<GraphicBuffer> graphicBuffer(static_cast<GraphicBuffer*>(buffer));
1656 uint32_t priorGeneration = graphicBuffer->mGenerationNumber;
1657 graphicBuffer->mGenerationNumber = mGenerationNumber;
1658 int32_t attachedSlot = -1;
1659 status_t result = mGraphicBufferProducer->attachBuffer(&attachedSlot, graphicBuffer);
1660 if (result != NO_ERROR) {
1661 ALOGE("attachBuffer: IGraphicBufferProducer call failed (%d)", result);
1662 graphicBuffer->mGenerationNumber = priorGeneration;
1663 return result;
1664 }
1665 if (mReportRemovedBuffers && (mSlots[attachedSlot].buffer != nullptr)) {
1666 mRemovedBuffers.push_back(mSlots[attachedSlot].buffer);
1667 }
1668 mSlots[attachedSlot].buffer = graphicBuffer;
1669 mDequeuedSlots.insert(attachedSlot);
1670
1671 return NO_ERROR;
1672 }
1673
setUsage(uint64_t reqUsage)1674 int Surface::setUsage(uint64_t reqUsage)
1675 {
1676 ALOGV("Surface::setUsage");
1677 Mutex::Autolock lock(mMutex);
1678 if (reqUsage != mReqUsage) {
1679 mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1680 }
1681 mReqUsage = reqUsage;
1682 return OK;
1683 }
1684
setCrop(Rect const * rect)1685 int Surface::setCrop(Rect const* rect)
1686 {
1687 ATRACE_CALL();
1688
1689 Rect realRect(Rect::EMPTY_RECT);
1690 if (rect == nullptr || rect->isEmpty()) {
1691 realRect.clear();
1692 } else {
1693 realRect = *rect;
1694 }
1695
1696 ALOGV("Surface::setCrop rect=[%d %d %d %d]",
1697 realRect.left, realRect.top, realRect.right, realRect.bottom);
1698
1699 Mutex::Autolock lock(mMutex);
1700 mCrop = realRect;
1701 return NO_ERROR;
1702 }
1703
setBufferCount(int bufferCount)1704 int Surface::setBufferCount(int bufferCount)
1705 {
1706 ATRACE_CALL();
1707 ALOGV("Surface::setBufferCount");
1708 Mutex::Autolock lock(mMutex);
1709
1710 status_t err = NO_ERROR;
1711 if (bufferCount == 0) {
1712 err = mGraphicBufferProducer->setMaxDequeuedBufferCount(1);
1713 } else {
1714 int minUndequeuedBuffers = 0;
1715 err = mGraphicBufferProducer->query(
1716 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffers);
1717 if (err == NO_ERROR) {
1718 err = mGraphicBufferProducer->setMaxDequeuedBufferCount(
1719 bufferCount - minUndequeuedBuffers);
1720 }
1721 }
1722
1723 ALOGE_IF(err, "IGraphicBufferProducer::setBufferCount(%d) returned %s",
1724 bufferCount, strerror(-err));
1725
1726 return err;
1727 }
1728
setMaxDequeuedBufferCount(int maxDequeuedBuffers)1729 int Surface::setMaxDequeuedBufferCount(int maxDequeuedBuffers) {
1730 ATRACE_CALL();
1731 ALOGV("Surface::setMaxDequeuedBufferCount");
1732 Mutex::Autolock lock(mMutex);
1733
1734 status_t err = mGraphicBufferProducer->setMaxDequeuedBufferCount(
1735 maxDequeuedBuffers);
1736 ALOGE_IF(err, "IGraphicBufferProducer::setMaxDequeuedBufferCount(%d) "
1737 "returned %s", maxDequeuedBuffers, strerror(-err));
1738
1739 return err;
1740 }
1741
setAsyncMode(bool async)1742 int Surface::setAsyncMode(bool async) {
1743 ATRACE_CALL();
1744 ALOGV("Surface::setAsyncMode");
1745 Mutex::Autolock lock(mMutex);
1746
1747 status_t err = mGraphicBufferProducer->setAsyncMode(async);
1748 ALOGE_IF(err, "IGraphicBufferProducer::setAsyncMode(%d) returned %s",
1749 async, strerror(-err));
1750
1751 return err;
1752 }
1753
setSharedBufferMode(bool sharedBufferMode)1754 int Surface::setSharedBufferMode(bool sharedBufferMode) {
1755 ATRACE_CALL();
1756 ALOGV("Surface::setSharedBufferMode (%d)", sharedBufferMode);
1757 Mutex::Autolock lock(mMutex);
1758
1759 status_t err = mGraphicBufferProducer->setSharedBufferMode(
1760 sharedBufferMode);
1761 if (err == NO_ERROR) {
1762 mSharedBufferMode = sharedBufferMode;
1763 }
1764 ALOGE_IF(err, "IGraphicBufferProducer::setSharedBufferMode(%d) returned"
1765 "%s", sharedBufferMode, strerror(-err));
1766
1767 return err;
1768 }
1769
setAutoRefresh(bool autoRefresh)1770 int Surface::setAutoRefresh(bool autoRefresh) {
1771 ATRACE_CALL();
1772 ALOGV("Surface::setAutoRefresh (%d)", autoRefresh);
1773 Mutex::Autolock lock(mMutex);
1774
1775 status_t err = mGraphicBufferProducer->setAutoRefresh(autoRefresh);
1776 if (err == NO_ERROR) {
1777 mAutoRefresh = autoRefresh;
1778 }
1779 ALOGE_IF(err, "IGraphicBufferProducer::setAutoRefresh(%d) returned %s",
1780 autoRefresh, strerror(-err));
1781 return err;
1782 }
1783
setBuffersDimensions(uint32_t width,uint32_t height)1784 int Surface::setBuffersDimensions(uint32_t width, uint32_t height)
1785 {
1786 ATRACE_CALL();
1787 ALOGV("Surface::setBuffersDimensions");
1788
1789 if ((width && !height) || (!width && height))
1790 return BAD_VALUE;
1791
1792 Mutex::Autolock lock(mMutex);
1793 if (width != mReqWidth || height != mReqHeight) {
1794 mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1795 }
1796 mReqWidth = width;
1797 mReqHeight = height;
1798 return NO_ERROR;
1799 }
1800
setBuffersUserDimensions(uint32_t width,uint32_t height)1801 int Surface::setBuffersUserDimensions(uint32_t width, uint32_t height)
1802 {
1803 ATRACE_CALL();
1804 ALOGV("Surface::setBuffersUserDimensions");
1805
1806 if ((width && !height) || (!width && height))
1807 return BAD_VALUE;
1808
1809 Mutex::Autolock lock(mMutex);
1810 if (width != mUserWidth || height != mUserHeight) {
1811 mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1812 }
1813 mUserWidth = width;
1814 mUserHeight = height;
1815 return NO_ERROR;
1816 }
1817
setBuffersFormat(PixelFormat format)1818 int Surface::setBuffersFormat(PixelFormat format)
1819 {
1820 ALOGV("Surface::setBuffersFormat");
1821
1822 Mutex::Autolock lock(mMutex);
1823 if (format != mReqFormat) {
1824 mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1825 }
1826 mReqFormat = format;
1827 return NO_ERROR;
1828 }
1829
setScalingMode(int mode)1830 int Surface::setScalingMode(int mode)
1831 {
1832 ATRACE_CALL();
1833 ALOGV("Surface::setScalingMode(%d)", mode);
1834
1835 switch (mode) {
1836 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
1837 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
1838 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
1839 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
1840 break;
1841 default:
1842 ALOGE("unknown scaling mode: %d", mode);
1843 return BAD_VALUE;
1844 }
1845
1846 Mutex::Autolock lock(mMutex);
1847 mScalingMode = mode;
1848 return NO_ERROR;
1849 }
1850
setBuffersTransform(uint32_t transform)1851 int Surface::setBuffersTransform(uint32_t transform)
1852 {
1853 ATRACE_CALL();
1854 ALOGV("Surface::setBuffersTransform");
1855 Mutex::Autolock lock(mMutex);
1856 // Ensure NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY is sticky. If the client sets the flag, do not
1857 // override it until the surface is disconnected. This is a temporary workaround for camera
1858 // until they switch to using Buffer State Layers. Currently if client sets the buffer transform
1859 // it may be overriden by the buffer producer when the producer sets the buffer transform.
1860 if (transformToDisplayInverse()) {
1861 transform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
1862 }
1863 mTransform = transform;
1864 return NO_ERROR;
1865 }
1866
setBuffersStickyTransform(uint32_t transform)1867 int Surface::setBuffersStickyTransform(uint32_t transform)
1868 {
1869 ATRACE_CALL();
1870 ALOGV("Surface::setBuffersStickyTransform");
1871 Mutex::Autolock lock(mMutex);
1872 mStickyTransform = transform;
1873 return NO_ERROR;
1874 }
1875
setBuffersTimestamp(int64_t timestamp)1876 int Surface::setBuffersTimestamp(int64_t timestamp)
1877 {
1878 ALOGV("Surface::setBuffersTimestamp");
1879 Mutex::Autolock lock(mMutex);
1880 mTimestamp = timestamp;
1881 return NO_ERROR;
1882 }
1883
setBuffersDataSpace(Dataspace dataSpace)1884 int Surface::setBuffersDataSpace(Dataspace dataSpace)
1885 {
1886 ALOGV("Surface::setBuffersDataSpace");
1887 Mutex::Autolock lock(mMutex);
1888 mDataSpace = dataSpace;
1889 return NO_ERROR;
1890 }
1891
setBuffersSmpte2086Metadata(const android_smpte2086_metadata * metadata)1892 int Surface::setBuffersSmpte2086Metadata(const android_smpte2086_metadata* metadata) {
1893 ALOGV("Surface::setBuffersSmpte2086Metadata");
1894 Mutex::Autolock lock(mMutex);
1895 if (metadata) {
1896 mHdrMetadata.smpte2086 = *metadata;
1897 mHdrMetadata.validTypes |= HdrMetadata::SMPTE2086;
1898 } else {
1899 mHdrMetadata.validTypes &= ~HdrMetadata::SMPTE2086;
1900 }
1901 return NO_ERROR;
1902 }
1903
setBuffersCta8613Metadata(const android_cta861_3_metadata * metadata)1904 int Surface::setBuffersCta8613Metadata(const android_cta861_3_metadata* metadata) {
1905 ALOGV("Surface::setBuffersCta8613Metadata");
1906 Mutex::Autolock lock(mMutex);
1907 if (metadata) {
1908 mHdrMetadata.cta8613 = *metadata;
1909 mHdrMetadata.validTypes |= HdrMetadata::CTA861_3;
1910 } else {
1911 mHdrMetadata.validTypes &= ~HdrMetadata::CTA861_3;
1912 }
1913 return NO_ERROR;
1914 }
1915
setBuffersHdr10PlusMetadata(const size_t size,const uint8_t * metadata)1916 int Surface::setBuffersHdr10PlusMetadata(const size_t size, const uint8_t* metadata) {
1917 ALOGV("Surface::setBuffersBlobMetadata");
1918 Mutex::Autolock lock(mMutex);
1919 if (size > 0) {
1920 mHdrMetadata.hdr10plus.assign(metadata, metadata + size);
1921 mHdrMetadata.validTypes |= HdrMetadata::HDR10PLUS;
1922 } else {
1923 mHdrMetadata.validTypes &= ~HdrMetadata::HDR10PLUS;
1924 mHdrMetadata.hdr10plus.clear();
1925 }
1926 return NO_ERROR;
1927 }
1928
getBuffersDataSpace()1929 Dataspace Surface::getBuffersDataSpace() {
1930 ALOGV("Surface::getBuffersDataSpace");
1931 Mutex::Autolock lock(mMutex);
1932 return mDataSpace;
1933 }
1934
freeAllBuffers()1935 void Surface::freeAllBuffers() {
1936 if (!mDequeuedSlots.empty()) {
1937 ALOGE("%s: %zu buffers were freed while being dequeued!",
1938 __FUNCTION__, mDequeuedSlots.size());
1939 }
1940 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
1941 mSlots[i].buffer = nullptr;
1942 }
1943 }
1944
getAndFlushBuffersFromSlots(const std::vector<int32_t> & slots,std::vector<sp<GraphicBuffer>> * outBuffers)1945 status_t Surface::getAndFlushBuffersFromSlots(const std::vector<int32_t>& slots,
1946 std::vector<sp<GraphicBuffer>>* outBuffers) {
1947 ALOGV("Surface::getAndFlushBuffersFromSlots");
1948 for (int32_t i : slots) {
1949 if (i < 0 || i >= NUM_BUFFER_SLOTS) {
1950 ALOGE("%s: Invalid slotIndex: %d", __FUNCTION__, i);
1951 return BAD_VALUE;
1952 }
1953 }
1954
1955 Mutex::Autolock lock(mMutex);
1956 for (int32_t i : slots) {
1957 if (mSlots[i].buffer == nullptr) {
1958 ALOGW("%s: Discarded slot %d doesn't contain buffer!", __FUNCTION__, i);
1959 continue;
1960 }
1961 // Don't flush currently dequeued buffers
1962 if (mDequeuedSlots.count(i) > 0) {
1963 continue;
1964 }
1965 outBuffers->push_back(mSlots[i].buffer);
1966 mSlots[i].buffer = nullptr;
1967 }
1968 return OK;
1969 }
1970
setSurfaceDamage(android_native_rect_t * rects,size_t numRects)1971 void Surface::setSurfaceDamage(android_native_rect_t* rects, size_t numRects) {
1972 ATRACE_CALL();
1973 ALOGV("Surface::setSurfaceDamage");
1974 Mutex::Autolock lock(mMutex);
1975
1976 if (mConnectedToCpu || numRects == 0) {
1977 mDirtyRegion = Region::INVALID_REGION;
1978 return;
1979 }
1980
1981 mDirtyRegion.clear();
1982 for (size_t r = 0; r < numRects; ++r) {
1983 // We intentionally flip top and bottom here, since because they're
1984 // specified with a bottom-left origin, top > bottom, which fails
1985 // validation in the Region class. We will fix this up when we flip to a
1986 // top-left origin in queueBuffer.
1987 Rect rect(rects[r].left, rects[r].bottom, rects[r].right, rects[r].top);
1988 mDirtyRegion.orSelf(rect);
1989 }
1990 }
1991
1992 // ----------------------------------------------------------------------
1993 // the lock/unlock APIs must be used from the same thread
1994
copyBlt(const sp<GraphicBuffer> & dst,const sp<GraphicBuffer> & src,const Region & reg,int * dstFenceFd)1995 static status_t copyBlt(
1996 const sp<GraphicBuffer>& dst,
1997 const sp<GraphicBuffer>& src,
1998 const Region& reg,
1999 int *dstFenceFd)
2000 {
2001 if (dst->getId() == src->getId())
2002 return OK;
2003
2004 // src and dst with, height and format must be identical. no verification
2005 // is done here.
2006 status_t err;
2007 uint8_t* src_bits = nullptr;
2008 err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(),
2009 reinterpret_cast<void**>(&src_bits));
2010 ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
2011
2012 uint8_t* dst_bits = nullptr;
2013 err = dst->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(),
2014 reinterpret_cast<void**>(&dst_bits), *dstFenceFd);
2015 ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
2016 *dstFenceFd = -1;
2017
2018 Region::const_iterator head(reg.begin());
2019 Region::const_iterator tail(reg.end());
2020 if (head != tail && src_bits && dst_bits) {
2021 const size_t bpp = bytesPerPixel(src->format);
2022 const size_t dbpr = static_cast<uint32_t>(dst->stride) * bpp;
2023 const size_t sbpr = static_cast<uint32_t>(src->stride) * bpp;
2024
2025 while (head != tail) {
2026 const Rect& r(*head++);
2027 int32_t h = r.height();
2028 if (h <= 0) continue;
2029 size_t size = static_cast<uint32_t>(r.width()) * bpp;
2030 uint8_t const * s = src_bits +
2031 static_cast<uint32_t>(r.left + src->stride * r.top) * bpp;
2032 uint8_t * d = dst_bits +
2033 static_cast<uint32_t>(r.left + dst->stride * r.top) * bpp;
2034 if (dbpr==sbpr && size==sbpr) {
2035 size *= static_cast<size_t>(h);
2036 h = 1;
2037 }
2038 do {
2039 memcpy(d, s, size);
2040 d += dbpr;
2041 s += sbpr;
2042 } while (--h > 0);
2043 }
2044 }
2045
2046 if (src_bits)
2047 src->unlock();
2048
2049 if (dst_bits)
2050 dst->unlockAsync(dstFenceFd);
2051
2052 return err;
2053 }
2054
2055 // ----------------------------------------------------------------------------
2056
lock(ANativeWindow_Buffer * outBuffer,ARect * inOutDirtyBounds)2057 status_t Surface::lock(
2058 ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds)
2059 {
2060 if (mLockedBuffer != nullptr) {
2061 ALOGE("Surface::lock failed, already locked");
2062 return INVALID_OPERATION;
2063 }
2064
2065 if (!mConnectedToCpu) {
2066 int err = Surface::connect(NATIVE_WINDOW_API_CPU);
2067 if (err) {
2068 return err;
2069 }
2070 // we're intending to do software rendering from this point
2071 setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
2072 }
2073
2074 ANativeWindowBuffer* out;
2075 int fenceFd = -1;
2076 status_t err = dequeueBuffer(&out, &fenceFd);
2077 ALOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
2078 if (err == NO_ERROR) {
2079 sp<GraphicBuffer> backBuffer(GraphicBuffer::getSelf(out));
2080 const Rect bounds(backBuffer->width, backBuffer->height);
2081
2082 Region newDirtyRegion;
2083 if (inOutDirtyBounds) {
2084 newDirtyRegion.set(static_cast<Rect const&>(*inOutDirtyBounds));
2085 newDirtyRegion.andSelf(bounds);
2086 } else {
2087 newDirtyRegion.set(bounds);
2088 }
2089
2090 // figure out if we can copy the frontbuffer back
2091 const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
2092 const bool canCopyBack = (frontBuffer != nullptr &&
2093 backBuffer->width == frontBuffer->width &&
2094 backBuffer->height == frontBuffer->height &&
2095 backBuffer->format == frontBuffer->format);
2096
2097 if (canCopyBack) {
2098 // copy the area that is invalid and not repainted this round
2099 const Region copyback(mDirtyRegion.subtract(newDirtyRegion));
2100 if (!copyback.isEmpty()) {
2101 copyBlt(backBuffer, frontBuffer, copyback, &fenceFd);
2102 }
2103 } else {
2104 // if we can't copy-back anything, modify the user's dirty
2105 // region to make sure they redraw the whole buffer
2106 newDirtyRegion.set(bounds);
2107 mDirtyRegion.clear();
2108 Mutex::Autolock lock(mMutex);
2109 for (size_t i=0 ; i<NUM_BUFFER_SLOTS ; i++) {
2110 mSlots[i].dirtyRegion.clear();
2111 }
2112 }
2113
2114
2115 { // scope for the lock
2116 Mutex::Autolock lock(mMutex);
2117 int backBufferSlot(getSlotFromBufferLocked(backBuffer.get()));
2118 if (backBufferSlot >= 0) {
2119 Region& dirtyRegion(mSlots[backBufferSlot].dirtyRegion);
2120 mDirtyRegion.subtract(dirtyRegion);
2121 dirtyRegion = newDirtyRegion;
2122 }
2123 }
2124
2125 mDirtyRegion.orSelf(newDirtyRegion);
2126 if (inOutDirtyBounds) {
2127 *inOutDirtyBounds = newDirtyRegion.getBounds();
2128 }
2129
2130 void* vaddr;
2131 status_t res = backBuffer->lockAsync(
2132 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
2133 newDirtyRegion.bounds(), &vaddr, fenceFd);
2134
2135 ALOGW_IF(res, "failed locking buffer (handle = %p)",
2136 backBuffer->handle);
2137
2138 if (res != 0) {
2139 err = INVALID_OPERATION;
2140 } else {
2141 mLockedBuffer = backBuffer;
2142 outBuffer->width = backBuffer->width;
2143 outBuffer->height = backBuffer->height;
2144 outBuffer->stride = backBuffer->stride;
2145 outBuffer->format = backBuffer->format;
2146 outBuffer->bits = vaddr;
2147 }
2148 }
2149 return err;
2150 }
2151
unlockAndPost()2152 status_t Surface::unlockAndPost()
2153 {
2154 if (mLockedBuffer == nullptr) {
2155 ALOGE("Surface::unlockAndPost failed, no locked buffer");
2156 return INVALID_OPERATION;
2157 }
2158
2159 int fd = -1;
2160 status_t err = mLockedBuffer->unlockAsync(&fd);
2161 ALOGE_IF(err, "failed unlocking buffer (%p)", mLockedBuffer->handle);
2162
2163 err = queueBuffer(mLockedBuffer.get(), fd);
2164 ALOGE_IF(err, "queueBuffer (handle=%p) failed (%s)",
2165 mLockedBuffer->handle, strerror(-err));
2166
2167 mPostedBuffer = mLockedBuffer;
2168 mLockedBuffer = nullptr;
2169 return err;
2170 }
2171
waitForNextFrame(uint64_t lastFrame,nsecs_t timeout)2172 bool Surface::waitForNextFrame(uint64_t lastFrame, nsecs_t timeout) {
2173 Mutex::Autolock lock(mMutex);
2174 if (mNextFrameNumber > lastFrame) {
2175 return true;
2176 }
2177 return mQueueBufferCondition.waitRelative(mMutex, timeout) == OK;
2178 }
2179
getUniqueId(uint64_t * outId) const2180 status_t Surface::getUniqueId(uint64_t* outId) const {
2181 Mutex::Autolock lock(mMutex);
2182 return mGraphicBufferProducer->getUniqueId(outId);
2183 }
2184
getConsumerUsage(uint64_t * outUsage) const2185 int Surface::getConsumerUsage(uint64_t* outUsage) const {
2186 Mutex::Autolock lock(mMutex);
2187 return mGraphicBufferProducer->getConsumerUsage(outUsage);
2188 }
2189
getAndFlushRemovedBuffers(std::vector<sp<GraphicBuffer>> * out)2190 status_t Surface::getAndFlushRemovedBuffers(std::vector<sp<GraphicBuffer>>* out) {
2191 if (out == nullptr) {
2192 ALOGE("%s: out must not be null!", __FUNCTION__);
2193 return BAD_VALUE;
2194 }
2195
2196 Mutex::Autolock lock(mMutex);
2197 *out = mRemovedBuffers;
2198 mRemovedBuffers.clear();
2199 return OK;
2200 }
2201
attachAndQueueBufferWithDataspace(Surface * surface,sp<GraphicBuffer> buffer,Dataspace dataspace)2202 status_t Surface::attachAndQueueBufferWithDataspace(Surface* surface, sp<GraphicBuffer> buffer,
2203 Dataspace dataspace) {
2204 if (buffer == nullptr) {
2205 return BAD_VALUE;
2206 }
2207 int err = static_cast<ANativeWindow*>(surface)->perform(surface, NATIVE_WINDOW_API_CONNECT,
2208 NATIVE_WINDOW_API_CPU);
2209 if (err != OK) {
2210 return err;
2211 }
2212 ui::Dataspace tmpDataspace = surface->getBuffersDataSpace();
2213 err = surface->setBuffersDataSpace(dataspace);
2214 if (err != OK) {
2215 return err;
2216 }
2217 err = surface->attachBuffer(buffer->getNativeBuffer());
2218 if (err != OK) {
2219 return err;
2220 }
2221 err = static_cast<ANativeWindow*>(surface)->queueBuffer(surface, buffer->getNativeBuffer(), -1);
2222 if (err != OK) {
2223 return err;
2224 }
2225 err = surface->setBuffersDataSpace(tmpDataspace);
2226 if (err != OK) {
2227 return err;
2228 }
2229 err = surface->disconnect(NATIVE_WINDOW_API_CPU);
2230 return err;
2231 }
2232
setAutoPrerotation(bool autoPrerotation)2233 int Surface::setAutoPrerotation(bool autoPrerotation) {
2234 ATRACE_CALL();
2235 ALOGV("Surface::setAutoPrerotation (%d)", autoPrerotation);
2236 Mutex::Autolock lock(mMutex);
2237
2238 if (mAutoPrerotation == autoPrerotation) {
2239 return OK;
2240 }
2241
2242 status_t err = mGraphicBufferProducer->setAutoPrerotation(autoPrerotation);
2243 if (err == NO_ERROR) {
2244 mAutoPrerotation = autoPrerotation;
2245 }
2246 ALOGE_IF(err, "IGraphicBufferProducer::setAutoPrerotation(%d) returned %s", autoPrerotation,
2247 strerror(-err));
2248 return err;
2249 }
2250
onBuffersDiscarded(const std::vector<int32_t> & slots)2251 void Surface::ProducerListenerProxy::onBuffersDiscarded(const std::vector<int32_t>& slots) {
2252 ATRACE_CALL();
2253 sp<Surface> parent = mParent.promote();
2254 if (parent == nullptr) {
2255 return;
2256 }
2257
2258 std::vector<sp<GraphicBuffer>> discardedBufs;
2259 status_t res = parent->getAndFlushBuffersFromSlots(slots, &discardedBufs);
2260 if (res != OK) {
2261 ALOGE("%s: Failed to get buffers from slots: %s(%d)", __FUNCTION__,
2262 strerror(-res), res);
2263 return;
2264 }
2265
2266 mSurfaceListener->onBuffersDiscarded(discardedBufs);
2267 }
2268
setFrameRate(float frameRate,int8_t compatibility)2269 status_t Surface::setFrameRate(float frameRate, int8_t compatibility) {
2270 ATRACE_CALL();
2271 ALOGV("Surface::setFrameRate");
2272
2273 if (!ValidateFrameRate(frameRate, compatibility, "Surface::setFrameRate")) {
2274 return BAD_VALUE;
2275 }
2276
2277 return composerService()->setFrameRate(mGraphicBufferProducer, frameRate, compatibility);
2278 }
2279
2280 }; // namespace android
2281