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     return OK;
736 }
737 
cancelBuffer(android_native_buffer_t * buffer,int fenceFd)738 int Surface::cancelBuffer(android_native_buffer_t* buffer,
739         int fenceFd) {
740     ATRACE_CALL();
741     ALOGV("Surface::cancelBuffer");
742     Mutex::Autolock lock(mMutex);
743     int i = getSlotFromBufferLocked(buffer);
744     if (i < 0) {
745         if (fenceFd >= 0) {
746             close(fenceFd);
747         }
748         return i;
749     }
750     if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
751         if (fenceFd >= 0) {
752             close(fenceFd);
753         }
754         return OK;
755     }
756     sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
757     mGraphicBufferProducer->cancelBuffer(i, fence);
758 
759     if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
760         mSharedBufferHasBeenQueued = true;
761     }
762 
763     return OK;
764 }
765 
getSlotFromBufferLocked(android_native_buffer_t * buffer) const766 int Surface::getSlotFromBufferLocked(
767         android_native_buffer_t* buffer) const {
768     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
769         if (mSlots[i].buffer != nullptr &&
770                 mSlots[i].buffer->handle == buffer->handle) {
771             return i;
772         }
773     }
774     ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
775     return BAD_VALUE;
776 }
777 
lockBuffer_DEPRECATED(android_native_buffer_t * buffer)778 int Surface::lockBuffer_DEPRECATED(android_native_buffer_t* buffer __attribute__((unused))) {
779     ALOGV("Surface::lockBuffer");
780     Mutex::Autolock lock(mMutex);
781     return OK;
782 }
783 
queueBuffer(android_native_buffer_t * buffer,int fenceFd)784 int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
785     ATRACE_CALL();
786     ALOGV("Surface::queueBuffer");
787     Mutex::Autolock lock(mMutex);
788     int64_t timestamp;
789     bool isAutoTimestamp = false;
790 
791     if (mTimestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
792         timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
793         isAutoTimestamp = true;
794         ALOGV("Surface::queueBuffer making up timestamp: %.2f ms",
795             timestamp / 1000000.0);
796     } else {
797         timestamp = mTimestamp;
798     }
799     int i = getSlotFromBufferLocked(buffer);
800     if (i < 0) {
801         if (fenceFd >= 0) {
802             close(fenceFd);
803         }
804         return i;
805     }
806     if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
807         if (fenceFd >= 0) {
808             close(fenceFd);
809         }
810         return OK;
811     }
812 
813 
814     // Make sure the crop rectangle is entirely inside the buffer.
815     Rect crop(Rect::EMPTY_RECT);
816     mCrop.intersect(Rect(buffer->width, buffer->height), &crop);
817 
818     sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
819     IGraphicBufferProducer::QueueBufferOutput output;
820     IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
821             static_cast<android_dataspace>(mDataSpace), crop, mScalingMode,
822             mTransform ^ mStickyTransform, fence, mStickyTransform,
823             mEnableFrameTimestamps);
824 
825     // we should send HDR metadata as needed if this becomes a bottleneck
826     input.setHdrMetadata(mHdrMetadata);
827 
828     if (mConnectedToCpu || mDirtyRegion.bounds() == Rect::INVALID_RECT) {
829         input.setSurfaceDamage(Region::INVALID_REGION);
830     } else {
831         // Here we do two things:
832         // 1) The surface damage was specified using the OpenGL ES convention of
833         //    the origin being in the bottom-left corner. Here we flip to the
834         //    convention that the rest of the system uses (top-left corner) by
835         //    subtracting all top/bottom coordinates from the buffer height.
836         // 2) If the buffer is coming in rotated (for example, because the EGL
837         //    implementation is reacting to the transform hint coming back from
838         //    SurfaceFlinger), the surface damage needs to be rotated the
839         //    opposite direction, since it was generated assuming an unrotated
840         //    buffer (the app doesn't know that the EGL implementation is
841         //    reacting to the transform hint behind its back). The
842         //    transformations in the switch statement below apply those
843         //    complementary rotations (e.g., if 90 degrees, rotate 270 degrees).
844 
845         int width = buffer->width;
846         int height = buffer->height;
847         bool rotated90 = (mTransform ^ mStickyTransform) &
848                 NATIVE_WINDOW_TRANSFORM_ROT_90;
849         if (rotated90) {
850             std::swap(width, height);
851         }
852 
853         Region flippedRegion;
854         for (auto rect : mDirtyRegion) {
855             int left = rect.left;
856             int right = rect.right;
857             int top = height - rect.bottom; // Flip from OpenGL convention
858             int bottom = height - rect.top; // Flip from OpenGL convention
859             switch (mTransform ^ mStickyTransform) {
860                 case NATIVE_WINDOW_TRANSFORM_ROT_90: {
861                     // Rotate 270 degrees
862                     Rect flippedRect{top, width - right, bottom, width - left};
863                     flippedRegion.orSelf(flippedRect);
864                     break;
865                 }
866                 case NATIVE_WINDOW_TRANSFORM_ROT_180: {
867                     // Rotate 180 degrees
868                     Rect flippedRect{width - right, height - bottom,
869                             width - left, height - top};
870                     flippedRegion.orSelf(flippedRect);
871                     break;
872                 }
873                 case NATIVE_WINDOW_TRANSFORM_ROT_270: {
874                     // Rotate 90 degrees
875                     Rect flippedRect{height - bottom, left,
876                             height - top, right};
877                     flippedRegion.orSelf(flippedRect);
878                     break;
879                 }
880                 default: {
881                     Rect flippedRect{left, top, right, bottom};
882                     flippedRegion.orSelf(flippedRect);
883                     break;
884                 }
885             }
886         }
887 
888         input.setSurfaceDamage(flippedRegion);
889     }
890 
891     nsecs_t now = systemTime();
892     status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
893     mLastQueueDuration = systemTime() - now;
894     if (err != OK)  {
895         ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
896     }
897 
898     if (mEnableFrameTimestamps) {
899         mFrameEventHistory->applyDelta(output.frameTimestamps);
900         // Update timestamps with the local acquire fence.
901         // The consumer doesn't send it back to prevent us from having two
902         // file descriptors of the same fence.
903         mFrameEventHistory->updateAcquireFence(mNextFrameNumber,
904                 std::make_shared<FenceTime>(fence));
905 
906         // Cache timestamps of signaled fences so we can close their file
907         // descriptors.
908         mFrameEventHistory->updateSignalTimes();
909     }
910 
911     mLastFrameNumber = mNextFrameNumber;
912 
913     mDefaultWidth = output.width;
914     mDefaultHeight = output.height;
915     mNextFrameNumber = output.nextFrameNumber;
916 
917     // Ignore transform hint if sticky transform is set or transform to display inverse flag is
918     // set.
919     if (mStickyTransform == 0 && !transformToDisplayInverse()) {
920         mTransformHint = output.transformHint;
921     }
922 
923     mConsumerRunningBehind = (output.numPendingBuffers >= 2);
924 
925     if (!mConnectedToCpu) {
926         // Clear surface damage back to full-buffer
927         mDirtyRegion = Region::INVALID_REGION;
928     }
929 
930     if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
931         mSharedBufferHasBeenQueued = true;
932     }
933 
934     mQueueBufferCondition.broadcast();
935 
936     if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
937         static FenceMonitor gpuCompletionThread("GPU completion");
938         gpuCompletionThread.queueFence(fence);
939     }
940 
941     return err;
942 }
943 
querySupportedTimestampsLocked() const944 void Surface::querySupportedTimestampsLocked() const {
945     // mMutex must be locked when calling this method.
946 
947     if (mQueriedSupportedTimestamps) {
948         return;
949     }
950     mQueriedSupportedTimestamps = true;
951 
952     std::vector<FrameEvent> supportedFrameTimestamps;
953     status_t err = composerService()->getSupportedFrameTimestamps(
954             &supportedFrameTimestamps);
955 
956     if (err != NO_ERROR) {
957         return;
958     }
959 
960     for (auto sft : supportedFrameTimestamps) {
961         if (sft == FrameEvent::DISPLAY_PRESENT) {
962             mFrameTimestampsSupportsPresent = true;
963         }
964     }
965 }
966 
query(int what,int * value) const967 int Surface::query(int what, int* value) const {
968     ATRACE_CALL();
969     ALOGV("Surface::query");
970     { // scope for the lock
971         Mutex::Autolock lock(mMutex);
972         switch (what) {
973             case NATIVE_WINDOW_FORMAT:
974                 if (mReqFormat) {
975                     *value = static_cast<int>(mReqFormat);
976                     return NO_ERROR;
977                 }
978                 break;
979             case NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER: {
980                 if (composerService()->authenticateSurfaceTexture(
981                         mGraphicBufferProducer)) {
982                     *value = 1;
983                 } else {
984                     *value = 0;
985                 }
986                 return NO_ERROR;
987             }
988             case NATIVE_WINDOW_CONCRETE_TYPE:
989                 *value = NATIVE_WINDOW_SURFACE;
990                 return NO_ERROR;
991             case NATIVE_WINDOW_DEFAULT_WIDTH:
992                 *value = static_cast<int>(
993                         mUserWidth ? mUserWidth : mDefaultWidth);
994                 return NO_ERROR;
995             case NATIVE_WINDOW_DEFAULT_HEIGHT:
996                 *value = static_cast<int>(
997                         mUserHeight ? mUserHeight : mDefaultHeight);
998                 return NO_ERROR;
999             case NATIVE_WINDOW_TRANSFORM_HINT:
1000                 *value = static_cast<int>(mTransformHint);
1001                 return NO_ERROR;
1002             case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
1003                 status_t err = NO_ERROR;
1004                 if (!mConsumerRunningBehind) {
1005                     *value = 0;
1006                 } else {
1007                     err = mGraphicBufferProducer->query(what, value);
1008                     if (err == NO_ERROR) {
1009                         mConsumerRunningBehind = *value;
1010                     }
1011                 }
1012                 return err;
1013             }
1014             case NATIVE_WINDOW_BUFFER_AGE: {
1015                 if (mBufferAge > INT32_MAX) {
1016                     *value = 0;
1017                 } else {
1018                     *value = static_cast<int32_t>(mBufferAge);
1019                 }
1020                 return NO_ERROR;
1021             }
1022             case NATIVE_WINDOW_LAST_DEQUEUE_DURATION: {
1023                 int64_t durationUs = mLastDequeueDuration / 1000;
1024                 *value = durationUs > std::numeric_limits<int>::max() ?
1025                         std::numeric_limits<int>::max() :
1026                         static_cast<int>(durationUs);
1027                 return NO_ERROR;
1028             }
1029             case NATIVE_WINDOW_LAST_QUEUE_DURATION: {
1030                 int64_t durationUs = mLastQueueDuration / 1000;
1031                 *value = durationUs > std::numeric_limits<int>::max() ?
1032                         std::numeric_limits<int>::max() :
1033                         static_cast<int>(durationUs);
1034                 return NO_ERROR;
1035             }
1036             case NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT: {
1037                 querySupportedTimestampsLocked();
1038                 *value = mFrameTimestampsSupportsPresent ? 1 : 0;
1039                 return NO_ERROR;
1040             }
1041             case NATIVE_WINDOW_IS_VALID: {
1042                 *value = mGraphicBufferProducer != nullptr ? 1 : 0;
1043                 return NO_ERROR;
1044             }
1045             case NATIVE_WINDOW_DATASPACE: {
1046                 *value = static_cast<int>(mDataSpace);
1047                 return NO_ERROR;
1048             }
1049             case NATIVE_WINDOW_MAX_BUFFER_COUNT: {
1050                 *value = mMaxBufferCount;
1051                 return NO_ERROR;
1052             }
1053         }
1054     }
1055     return mGraphicBufferProducer->query(what, value);
1056 }
1057 
perform(int operation,va_list args)1058 int Surface::perform(int operation, va_list args)
1059 {
1060     int res = NO_ERROR;
1061     switch (operation) {
1062     case NATIVE_WINDOW_CONNECT:
1063         // deprecated. must return NO_ERROR.
1064         break;
1065     case NATIVE_WINDOW_DISCONNECT:
1066         // deprecated. must return NO_ERROR.
1067         break;
1068     case NATIVE_WINDOW_SET_USAGE:
1069         res = dispatchSetUsage(args);
1070         break;
1071     case NATIVE_WINDOW_SET_CROP:
1072         res = dispatchSetCrop(args);
1073         break;
1074     case NATIVE_WINDOW_SET_BUFFER_COUNT:
1075         res = dispatchSetBufferCount(args);
1076         break;
1077     case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
1078         res = dispatchSetBuffersGeometry(args);
1079         break;
1080     case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
1081         res = dispatchSetBuffersTransform(args);
1082         break;
1083     case NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM:
1084         res = dispatchSetBuffersStickyTransform(args);
1085         break;
1086     case NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP:
1087         res = dispatchSetBuffersTimestamp(args);
1088         break;
1089     case NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS:
1090         res = dispatchSetBuffersDimensions(args);
1091         break;
1092     case NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS:
1093         res = dispatchSetBuffersUserDimensions(args);
1094         break;
1095     case NATIVE_WINDOW_SET_BUFFERS_FORMAT:
1096         res = dispatchSetBuffersFormat(args);
1097         break;
1098     case NATIVE_WINDOW_LOCK:
1099         res = dispatchLock(args);
1100         break;
1101     case NATIVE_WINDOW_UNLOCK_AND_POST:
1102         res = dispatchUnlockAndPost(args);
1103         break;
1104     case NATIVE_WINDOW_SET_SCALING_MODE:
1105         res = dispatchSetScalingMode(args);
1106         break;
1107     case NATIVE_WINDOW_API_CONNECT:
1108         res = dispatchConnect(args);
1109         break;
1110     case NATIVE_WINDOW_API_DISCONNECT:
1111         res = dispatchDisconnect(args);
1112         break;
1113     case NATIVE_WINDOW_SET_SIDEBAND_STREAM:
1114         res = dispatchSetSidebandStream(args);
1115         break;
1116     case NATIVE_WINDOW_SET_BUFFERS_DATASPACE:
1117         res = dispatchSetBuffersDataSpace(args);
1118         break;
1119     case NATIVE_WINDOW_SET_BUFFERS_SMPTE2086_METADATA:
1120         res = dispatchSetBuffersSmpte2086Metadata(args);
1121         break;
1122     case NATIVE_WINDOW_SET_BUFFERS_CTA861_3_METADATA:
1123         res = dispatchSetBuffersCta8613Metadata(args);
1124         break;
1125     case NATIVE_WINDOW_SET_BUFFERS_HDR10_PLUS_METADATA:
1126         res = dispatchSetBuffersHdr10PlusMetadata(args);
1127         break;
1128     case NATIVE_WINDOW_SET_SURFACE_DAMAGE:
1129         res = dispatchSetSurfaceDamage(args);
1130         break;
1131     case NATIVE_WINDOW_SET_SHARED_BUFFER_MODE:
1132         res = dispatchSetSharedBufferMode(args);
1133         break;
1134     case NATIVE_WINDOW_SET_AUTO_REFRESH:
1135         res = dispatchSetAutoRefresh(args);
1136         break;
1137     case NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION:
1138         res = dispatchGetDisplayRefreshCycleDuration(args);
1139         break;
1140     case NATIVE_WINDOW_GET_NEXT_FRAME_ID:
1141         res = dispatchGetNextFrameId(args);
1142         break;
1143     case NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS:
1144         res = dispatchEnableFrameTimestamps(args);
1145         break;
1146     case NATIVE_WINDOW_GET_COMPOSITOR_TIMING:
1147         res = dispatchGetCompositorTiming(args);
1148         break;
1149     case NATIVE_WINDOW_GET_FRAME_TIMESTAMPS:
1150         res = dispatchGetFrameTimestamps(args);
1151         break;
1152     case NATIVE_WINDOW_GET_WIDE_COLOR_SUPPORT:
1153         res = dispatchGetWideColorSupport(args);
1154         break;
1155     case NATIVE_WINDOW_GET_HDR_SUPPORT:
1156         res = dispatchGetHdrSupport(args);
1157         break;
1158     case NATIVE_WINDOW_SET_USAGE64:
1159         res = dispatchSetUsage64(args);
1160         break;
1161     case NATIVE_WINDOW_GET_CONSUMER_USAGE64:
1162         res = dispatchGetConsumerUsage64(args);
1163         break;
1164     case NATIVE_WINDOW_SET_AUTO_PREROTATION:
1165         res = dispatchSetAutoPrerotation(args);
1166         break;
1167     case NATIVE_WINDOW_GET_LAST_DEQUEUE_START:
1168         res = dispatchGetLastDequeueStartTime(args);
1169         break;
1170     case NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT:
1171         res = dispatchSetDequeueTimeout(args);
1172         break;
1173     case NATIVE_WINDOW_GET_LAST_DEQUEUE_DURATION:
1174         res = dispatchGetLastDequeueDuration(args);
1175         break;
1176     case NATIVE_WINDOW_GET_LAST_QUEUE_DURATION:
1177         res = dispatchGetLastQueueDuration(args);
1178         break;
1179     case NATIVE_WINDOW_SET_FRAME_RATE:
1180         res = dispatchSetFrameRate(args);
1181         break;
1182     case NATIVE_WINDOW_SET_CANCEL_INTERCEPTOR:
1183         res = dispatchAddCancelInterceptor(args);
1184         break;
1185     case NATIVE_WINDOW_SET_DEQUEUE_INTERCEPTOR:
1186         res = dispatchAddDequeueInterceptor(args);
1187         break;
1188     case NATIVE_WINDOW_SET_PERFORM_INTERCEPTOR:
1189         res = dispatchAddPerformInterceptor(args);
1190         break;
1191     case NATIVE_WINDOW_SET_QUEUE_INTERCEPTOR:
1192         res = dispatchAddQueueInterceptor(args);
1193         break;
1194     case NATIVE_WINDOW_SET_QUERY_INTERCEPTOR:
1195         res = dispatchAddQueryInterceptor(args);
1196         break;
1197     case NATIVE_WINDOW_ALLOCATE_BUFFERS:
1198         allocateBuffers();
1199         res = NO_ERROR;
1200         break;
1201     case NATIVE_WINDOW_GET_LAST_QUEUED_BUFFER:
1202         res = dispatchGetLastQueuedBuffer(args);
1203         break;
1204     default:
1205         res = NAME_NOT_FOUND;
1206         break;
1207     }
1208     return res;
1209 }
1210 
dispatchConnect(va_list args)1211 int Surface::dispatchConnect(va_list args) {
1212     int api = va_arg(args, int);
1213     return connect(api);
1214 }
1215 
dispatchDisconnect(va_list args)1216 int Surface::dispatchDisconnect(va_list args) {
1217     int api = va_arg(args, int);
1218     return disconnect(api);
1219 }
1220 
dispatchSetUsage(va_list args)1221 int Surface::dispatchSetUsage(va_list args) {
1222     uint64_t usage = va_arg(args, uint32_t);
1223     return setUsage(usage);
1224 }
1225 
dispatchSetUsage64(va_list args)1226 int Surface::dispatchSetUsage64(va_list args) {
1227     uint64_t usage = va_arg(args, uint64_t);
1228     return setUsage(usage);
1229 }
1230 
dispatchSetCrop(va_list args)1231 int Surface::dispatchSetCrop(va_list args) {
1232     android_native_rect_t const* rect = va_arg(args, android_native_rect_t*);
1233     return setCrop(reinterpret_cast<Rect const*>(rect));
1234 }
1235 
dispatchSetBufferCount(va_list args)1236 int Surface::dispatchSetBufferCount(va_list args) {
1237     size_t bufferCount = va_arg(args, size_t);
1238     return setBufferCount(static_cast<int32_t>(bufferCount));
1239 }
1240 
dispatchSetBuffersGeometry(va_list args)1241 int Surface::dispatchSetBuffersGeometry(va_list args) {
1242     uint32_t width = va_arg(args, uint32_t);
1243     uint32_t height = va_arg(args, uint32_t);
1244     PixelFormat format = va_arg(args, PixelFormat);
1245     int err = setBuffersDimensions(width, height);
1246     if (err != 0) {
1247         return err;
1248     }
1249     return setBuffersFormat(format);
1250 }
1251 
dispatchSetBuffersDimensions(va_list args)1252 int Surface::dispatchSetBuffersDimensions(va_list args) {
1253     uint32_t width = va_arg(args, uint32_t);
1254     uint32_t height = va_arg(args, uint32_t);
1255     return setBuffersDimensions(width, height);
1256 }
1257 
dispatchSetBuffersUserDimensions(va_list args)1258 int Surface::dispatchSetBuffersUserDimensions(va_list args) {
1259     uint32_t width = va_arg(args, uint32_t);
1260     uint32_t height = va_arg(args, uint32_t);
1261     return setBuffersUserDimensions(width, height);
1262 }
1263 
dispatchSetBuffersFormat(va_list args)1264 int Surface::dispatchSetBuffersFormat(va_list args) {
1265     PixelFormat format = va_arg(args, PixelFormat);
1266     return setBuffersFormat(format);
1267 }
1268 
dispatchSetScalingMode(va_list args)1269 int Surface::dispatchSetScalingMode(va_list args) {
1270     int mode = va_arg(args, int);
1271     return setScalingMode(mode);
1272 }
1273 
dispatchSetBuffersTransform(va_list args)1274 int Surface::dispatchSetBuffersTransform(va_list args) {
1275     uint32_t transform = va_arg(args, uint32_t);
1276     return setBuffersTransform(transform);
1277 }
1278 
dispatchSetBuffersStickyTransform(va_list args)1279 int Surface::dispatchSetBuffersStickyTransform(va_list args) {
1280     uint32_t transform = va_arg(args, uint32_t);
1281     return setBuffersStickyTransform(transform);
1282 }
1283 
dispatchSetBuffersTimestamp(va_list args)1284 int Surface::dispatchSetBuffersTimestamp(va_list args) {
1285     int64_t timestamp = va_arg(args, int64_t);
1286     return setBuffersTimestamp(timestamp);
1287 }
1288 
dispatchLock(va_list args)1289 int Surface::dispatchLock(va_list args) {
1290     ANativeWindow_Buffer* outBuffer = va_arg(args, ANativeWindow_Buffer*);
1291     ARect* inOutDirtyBounds = va_arg(args, ARect*);
1292     return lock(outBuffer, inOutDirtyBounds);
1293 }
1294 
dispatchUnlockAndPost(va_list args)1295 int Surface::dispatchUnlockAndPost(va_list args __attribute__((unused))) {
1296     return unlockAndPost();
1297 }
1298 
dispatchSetSidebandStream(va_list args)1299 int Surface::dispatchSetSidebandStream(va_list args) {
1300     native_handle_t* sH = va_arg(args, native_handle_t*);
1301     sp<NativeHandle> sidebandHandle = NativeHandle::create(sH, false);
1302     setSidebandStream(sidebandHandle);
1303     return OK;
1304 }
1305 
dispatchSetBuffersDataSpace(va_list args)1306 int Surface::dispatchSetBuffersDataSpace(va_list args) {
1307     Dataspace dataspace = static_cast<Dataspace>(va_arg(args, int));
1308     return setBuffersDataSpace(dataspace);
1309 }
1310 
dispatchSetBuffersSmpte2086Metadata(va_list args)1311 int Surface::dispatchSetBuffersSmpte2086Metadata(va_list args) {
1312     const android_smpte2086_metadata* metadata =
1313         va_arg(args, const android_smpte2086_metadata*);
1314     return setBuffersSmpte2086Metadata(metadata);
1315 }
1316 
dispatchSetBuffersCta8613Metadata(va_list args)1317 int Surface::dispatchSetBuffersCta8613Metadata(va_list args) {
1318     const android_cta861_3_metadata* metadata =
1319         va_arg(args, const android_cta861_3_metadata*);
1320     return setBuffersCta8613Metadata(metadata);
1321 }
1322 
dispatchSetBuffersHdr10PlusMetadata(va_list args)1323 int Surface::dispatchSetBuffersHdr10PlusMetadata(va_list args) {
1324     const size_t size = va_arg(args, size_t);
1325     const uint8_t* metadata = va_arg(args, const uint8_t*);
1326     return setBuffersHdr10PlusMetadata(size, metadata);
1327 }
1328 
dispatchSetSurfaceDamage(va_list args)1329 int Surface::dispatchSetSurfaceDamage(va_list args) {
1330     android_native_rect_t* rects = va_arg(args, android_native_rect_t*);
1331     size_t numRects = va_arg(args, size_t);
1332     setSurfaceDamage(rects, numRects);
1333     return NO_ERROR;
1334 }
1335 
dispatchSetSharedBufferMode(va_list args)1336 int Surface::dispatchSetSharedBufferMode(va_list args) {
1337     bool sharedBufferMode = va_arg(args, int);
1338     return setSharedBufferMode(sharedBufferMode);
1339 }
1340 
dispatchSetAutoRefresh(va_list args)1341 int Surface::dispatchSetAutoRefresh(va_list args) {
1342     bool autoRefresh = va_arg(args, int);
1343     return setAutoRefresh(autoRefresh);
1344 }
1345 
dispatchGetDisplayRefreshCycleDuration(va_list args)1346 int Surface::dispatchGetDisplayRefreshCycleDuration(va_list args) {
1347     nsecs_t* outRefreshDuration = va_arg(args, int64_t*);
1348     return getDisplayRefreshCycleDuration(outRefreshDuration);
1349 }
1350 
dispatchGetNextFrameId(va_list args)1351 int Surface::dispatchGetNextFrameId(va_list args) {
1352     uint64_t* nextFrameId = va_arg(args, uint64_t*);
1353     *nextFrameId = getNextFrameNumber();
1354     return NO_ERROR;
1355 }
1356 
dispatchEnableFrameTimestamps(va_list args)1357 int Surface::dispatchEnableFrameTimestamps(va_list args) {
1358     bool enable = va_arg(args, int);
1359     enableFrameTimestamps(enable);
1360     return NO_ERROR;
1361 }
1362 
dispatchGetCompositorTiming(va_list args)1363 int Surface::dispatchGetCompositorTiming(va_list args) {
1364     nsecs_t* compositeDeadline = va_arg(args, int64_t*);
1365     nsecs_t* compositeInterval = va_arg(args, int64_t*);
1366     nsecs_t* compositeToPresentLatency = va_arg(args, int64_t*);
1367     return getCompositorTiming(compositeDeadline, compositeInterval,
1368             compositeToPresentLatency);
1369 }
1370 
dispatchGetFrameTimestamps(va_list args)1371 int Surface::dispatchGetFrameTimestamps(va_list args) {
1372     uint64_t frameId = va_arg(args, uint64_t);
1373     nsecs_t* outRequestedPresentTime = va_arg(args, int64_t*);
1374     nsecs_t* outAcquireTime = va_arg(args, int64_t*);
1375     nsecs_t* outLatchTime = va_arg(args, int64_t*);
1376     nsecs_t* outFirstRefreshStartTime = va_arg(args, int64_t*);
1377     nsecs_t* outLastRefreshStartTime = va_arg(args, int64_t*);
1378     nsecs_t* outGpuCompositionDoneTime = va_arg(args, int64_t*);
1379     nsecs_t* outDisplayPresentTime = va_arg(args, int64_t*);
1380     nsecs_t* outDequeueReadyTime = va_arg(args, int64_t*);
1381     nsecs_t* outReleaseTime = va_arg(args, int64_t*);
1382     return getFrameTimestamps(frameId,
1383             outRequestedPresentTime, outAcquireTime, outLatchTime,
1384             outFirstRefreshStartTime, outLastRefreshStartTime,
1385             outGpuCompositionDoneTime, outDisplayPresentTime,
1386             outDequeueReadyTime, outReleaseTime);
1387 }
1388 
dispatchGetWideColorSupport(va_list args)1389 int Surface::dispatchGetWideColorSupport(va_list args) {
1390     bool* outSupport = va_arg(args, bool*);
1391     return getWideColorSupport(outSupport);
1392 }
1393 
dispatchGetHdrSupport(va_list args)1394 int Surface::dispatchGetHdrSupport(va_list args) {
1395     bool* outSupport = va_arg(args, bool*);
1396     return getHdrSupport(outSupport);
1397 }
1398 
dispatchGetConsumerUsage64(va_list args)1399 int Surface::dispatchGetConsumerUsage64(va_list args) {
1400     uint64_t* usage = va_arg(args, uint64_t*);
1401     return getConsumerUsage(usage);
1402 }
1403 
dispatchSetAutoPrerotation(va_list args)1404 int Surface::dispatchSetAutoPrerotation(va_list args) {
1405     bool autoPrerotation = va_arg(args, int);
1406     return setAutoPrerotation(autoPrerotation);
1407 }
1408 
dispatchGetLastDequeueStartTime(va_list args)1409 int Surface::dispatchGetLastDequeueStartTime(va_list args) {
1410     int64_t* lastDequeueStartTime = va_arg(args, int64_t*);
1411     *lastDequeueStartTime = mLastDequeueStartTime;
1412     return NO_ERROR;
1413 }
1414 
dispatchSetDequeueTimeout(va_list args)1415 int Surface::dispatchSetDequeueTimeout(va_list args) {
1416     nsecs_t timeout = va_arg(args, int64_t);
1417     return setDequeueTimeout(timeout);
1418 }
1419 
dispatchGetLastDequeueDuration(va_list args)1420 int Surface::dispatchGetLastDequeueDuration(va_list args) {
1421     int64_t* lastDequeueDuration = va_arg(args, int64_t*);
1422     *lastDequeueDuration = mLastDequeueDuration;
1423     return NO_ERROR;
1424 }
1425 
dispatchGetLastQueueDuration(va_list args)1426 int Surface::dispatchGetLastQueueDuration(va_list args) {
1427     int64_t* lastQueueDuration = va_arg(args, int64_t*);
1428     *lastQueueDuration = mLastQueueDuration;
1429     return NO_ERROR;
1430 }
1431 
dispatchSetFrameRate(va_list args)1432 int Surface::dispatchSetFrameRate(va_list args) {
1433     float frameRate = static_cast<float>(va_arg(args, double));
1434     int8_t compatibility = static_cast<int8_t>(va_arg(args, int));
1435     return setFrameRate(frameRate, compatibility);
1436 }
1437 
dispatchAddCancelInterceptor(va_list args)1438 int Surface::dispatchAddCancelInterceptor(va_list args) {
1439     ANativeWindow_cancelBufferInterceptor interceptor =
1440             va_arg(args, ANativeWindow_cancelBufferInterceptor);
1441     void* data = va_arg(args, void*);
1442     std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1443     mCancelInterceptor = interceptor;
1444     mCancelInterceptorData = data;
1445     return NO_ERROR;
1446 }
1447 
dispatchAddDequeueInterceptor(va_list args)1448 int Surface::dispatchAddDequeueInterceptor(va_list args) {
1449     ANativeWindow_dequeueBufferInterceptor interceptor =
1450             va_arg(args, ANativeWindow_dequeueBufferInterceptor);
1451     void* data = va_arg(args, void*);
1452     std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1453     mDequeueInterceptor = interceptor;
1454     mDequeueInterceptorData = data;
1455     return NO_ERROR;
1456 }
1457 
dispatchAddPerformInterceptor(va_list args)1458 int Surface::dispatchAddPerformInterceptor(va_list args) {
1459     ANativeWindow_performInterceptor interceptor = va_arg(args, ANativeWindow_performInterceptor);
1460     void* data = va_arg(args, void*);
1461     std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1462     mPerformInterceptor = interceptor;
1463     mPerformInterceptorData = data;
1464     return NO_ERROR;
1465 }
1466 
dispatchAddQueueInterceptor(va_list args)1467 int Surface::dispatchAddQueueInterceptor(va_list args) {
1468     ANativeWindow_queueBufferInterceptor interceptor =
1469             va_arg(args, ANativeWindow_queueBufferInterceptor);
1470     void* data = va_arg(args, void*);
1471     std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1472     mQueueInterceptor = interceptor;
1473     mQueueInterceptorData = data;
1474     return NO_ERROR;
1475 }
1476 
dispatchAddQueryInterceptor(va_list args)1477 int Surface::dispatchAddQueryInterceptor(va_list args) {
1478     ANativeWindow_queryInterceptor interceptor = va_arg(args, ANativeWindow_queryInterceptor);
1479     void* data = va_arg(args, void*);
1480     std::lock_guard<std::shared_mutex> lock(mInterceptorMutex);
1481     mQueryInterceptor = interceptor;
1482     mQueryInterceptorData = data;
1483     return NO_ERROR;
1484 }
1485 
dispatchGetLastQueuedBuffer(va_list args)1486 int Surface::dispatchGetLastQueuedBuffer(va_list args) {
1487     AHardwareBuffer** buffer = va_arg(args, AHardwareBuffer**);
1488     int* fence = va_arg(args, int*);
1489     float* matrix = va_arg(args, float*);
1490     sp<GraphicBuffer> graphicBuffer;
1491     sp<Fence> spFence;
1492 
1493     int result = mGraphicBufferProducer->getLastQueuedBuffer(&graphicBuffer, &spFence, matrix);
1494 
1495     if (graphicBuffer != nullptr) {
1496         *buffer = reinterpret_cast<AHardwareBuffer*>(graphicBuffer.get());
1497         AHardwareBuffer_acquire(*buffer);
1498     } else {
1499         *buffer = nullptr;
1500     }
1501 
1502     if (spFence != nullptr) {
1503         *fence = spFence->dup();
1504     } else {
1505         *fence = -1;
1506     }
1507     return result;
1508 }
1509 
transformToDisplayInverse()1510 bool Surface::transformToDisplayInverse() {
1511     return (mTransform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) ==
1512             NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
1513 }
1514 
connect(int api)1515 int Surface::connect(int api) {
1516     static sp<IProducerListener> listener = new DummyProducerListener();
1517     return connect(api, listener);
1518 }
1519 
connect(int api,const sp<IProducerListener> & listener)1520 int Surface::connect(int api, const sp<IProducerListener>& listener) {
1521     return connect(api, listener, false);
1522 }
1523 
connect(int api,bool reportBufferRemoval,const sp<SurfaceListener> & sListener)1524 int Surface::connect(
1525         int api, bool reportBufferRemoval, const sp<SurfaceListener>& sListener) {
1526     if (sListener != nullptr) {
1527         mListenerProxy = new ProducerListenerProxy(this, sListener);
1528     }
1529     return connect(api, mListenerProxy, reportBufferRemoval);
1530 }
1531 
connect(int api,const sp<IProducerListener> & listener,bool reportBufferRemoval)1532 int Surface::connect(
1533         int api, const sp<IProducerListener>& listener, bool reportBufferRemoval) {
1534     ATRACE_CALL();
1535     ALOGV("Surface::connect");
1536     Mutex::Autolock lock(mMutex);
1537     IGraphicBufferProducer::QueueBufferOutput output;
1538     mReportRemovedBuffers = reportBufferRemoval;
1539     int err = mGraphicBufferProducer->connect(listener, api, mProducerControlledByApp, &output);
1540     if (err == NO_ERROR) {
1541         mDefaultWidth = output.width;
1542         mDefaultHeight = output.height;
1543         mNextFrameNumber = output.nextFrameNumber;
1544         mMaxBufferCount = output.maxBufferCount;
1545 
1546         // Ignore transform hint if sticky transform is set or transform to display inverse flag is
1547         // set. Transform hint should be ignored if the client is expected to always submit buffers
1548         // in the same orientation.
1549         if (mStickyTransform == 0 && !transformToDisplayInverse()) {
1550             mTransformHint = output.transformHint;
1551         }
1552 
1553         mConsumerRunningBehind = (output.numPendingBuffers >= 2);
1554     }
1555     if (!err && api == NATIVE_WINDOW_API_CPU) {
1556         mConnectedToCpu = true;
1557         // Clear the dirty region in case we're switching from a non-CPU API
1558         mDirtyRegion.clear();
1559     } else if (!err) {
1560         // Initialize the dirty region for tracking surface damage
1561         mDirtyRegion = Region::INVALID_REGION;
1562     }
1563 
1564     return err;
1565 }
1566 
1567 
disconnect(int api,IGraphicBufferProducer::DisconnectMode mode)1568 int Surface::disconnect(int api, IGraphicBufferProducer::DisconnectMode mode) {
1569     ATRACE_CALL();
1570     ALOGV("Surface::disconnect");
1571     Mutex::Autolock lock(mMutex);
1572     mRemovedBuffers.clear();
1573     mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1574     mSharedBufferHasBeenQueued = false;
1575     freeAllBuffers();
1576     int err = mGraphicBufferProducer->disconnect(api, mode);
1577     if (!err) {
1578         mReqFormat = 0;
1579         mReqWidth = 0;
1580         mReqHeight = 0;
1581         mReqUsage = 0;
1582         mCrop.clear();
1583         mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
1584         mTransform = 0;
1585         mStickyTransform = 0;
1586         mAutoPrerotation = false;
1587         mEnableFrameTimestamps = false;
1588         mMaxBufferCount = NUM_BUFFER_SLOTS;
1589 
1590         if (api == NATIVE_WINDOW_API_CPU) {
1591             mConnectedToCpu = false;
1592         }
1593     }
1594     return err;
1595 }
1596 
detachNextBuffer(sp<GraphicBuffer> * outBuffer,sp<Fence> * outFence)1597 int Surface::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
1598         sp<Fence>* outFence) {
1599     ATRACE_CALL();
1600     ALOGV("Surface::detachNextBuffer");
1601 
1602     if (outBuffer == nullptr || outFence == nullptr) {
1603         return BAD_VALUE;
1604     }
1605 
1606     Mutex::Autolock lock(mMutex);
1607     if (mReportRemovedBuffers) {
1608         mRemovedBuffers.clear();
1609     }
1610 
1611     sp<GraphicBuffer> buffer(nullptr);
1612     sp<Fence> fence(nullptr);
1613     status_t result = mGraphicBufferProducer->detachNextBuffer(
1614             &buffer, &fence);
1615     if (result != NO_ERROR) {
1616         return result;
1617     }
1618 
1619     *outBuffer = buffer;
1620     if (fence != nullptr && fence->isValid()) {
1621         *outFence = fence;
1622     } else {
1623         *outFence = Fence::NO_FENCE;
1624     }
1625 
1626     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
1627         if (mSlots[i].buffer != nullptr &&
1628                 mSlots[i].buffer->getId() == buffer->getId()) {
1629             if (mReportRemovedBuffers) {
1630                 mRemovedBuffers.push_back(mSlots[i].buffer);
1631             }
1632             mSlots[i].buffer = nullptr;
1633         }
1634     }
1635 
1636     return NO_ERROR;
1637 }
1638 
attachBuffer(ANativeWindowBuffer * buffer)1639 int Surface::attachBuffer(ANativeWindowBuffer* buffer)
1640 {
1641     ATRACE_CALL();
1642     ALOGV("Surface::attachBuffer");
1643 
1644     Mutex::Autolock lock(mMutex);
1645     if (mReportRemovedBuffers) {
1646         mRemovedBuffers.clear();
1647     }
1648 
1649     sp<GraphicBuffer> graphicBuffer(static_cast<GraphicBuffer*>(buffer));
1650     uint32_t priorGeneration = graphicBuffer->mGenerationNumber;
1651     graphicBuffer->mGenerationNumber = mGenerationNumber;
1652     int32_t attachedSlot = -1;
1653     status_t result = mGraphicBufferProducer->attachBuffer(&attachedSlot, graphicBuffer);
1654     if (result != NO_ERROR) {
1655         ALOGE("attachBuffer: IGraphicBufferProducer call failed (%d)", result);
1656         graphicBuffer->mGenerationNumber = priorGeneration;
1657         return result;
1658     }
1659     if (mReportRemovedBuffers && (mSlots[attachedSlot].buffer != nullptr)) {
1660         mRemovedBuffers.push_back(mSlots[attachedSlot].buffer);
1661     }
1662     mSlots[attachedSlot].buffer = graphicBuffer;
1663 
1664     return NO_ERROR;
1665 }
1666 
setUsage(uint64_t reqUsage)1667 int Surface::setUsage(uint64_t reqUsage)
1668 {
1669     ALOGV("Surface::setUsage");
1670     Mutex::Autolock lock(mMutex);
1671     if (reqUsage != mReqUsage) {
1672         mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1673     }
1674     mReqUsage = reqUsage;
1675     return OK;
1676 }
1677 
setCrop(Rect const * rect)1678 int Surface::setCrop(Rect const* rect)
1679 {
1680     ATRACE_CALL();
1681 
1682     Rect realRect(Rect::EMPTY_RECT);
1683     if (rect == nullptr || rect->isEmpty()) {
1684         realRect.clear();
1685     } else {
1686         realRect = *rect;
1687     }
1688 
1689     ALOGV("Surface::setCrop rect=[%d %d %d %d]",
1690             realRect.left, realRect.top, realRect.right, realRect.bottom);
1691 
1692     Mutex::Autolock lock(mMutex);
1693     mCrop = realRect;
1694     return NO_ERROR;
1695 }
1696 
setBufferCount(int bufferCount)1697 int Surface::setBufferCount(int bufferCount)
1698 {
1699     ATRACE_CALL();
1700     ALOGV("Surface::setBufferCount");
1701     Mutex::Autolock lock(mMutex);
1702 
1703     status_t err = NO_ERROR;
1704     if (bufferCount == 0) {
1705         err = mGraphicBufferProducer->setMaxDequeuedBufferCount(1);
1706     } else {
1707         int minUndequeuedBuffers = 0;
1708         err = mGraphicBufferProducer->query(
1709                 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffers);
1710         if (err == NO_ERROR) {
1711             err = mGraphicBufferProducer->setMaxDequeuedBufferCount(
1712                     bufferCount - minUndequeuedBuffers);
1713         }
1714     }
1715 
1716     ALOGE_IF(err, "IGraphicBufferProducer::setBufferCount(%d) returned %s",
1717              bufferCount, strerror(-err));
1718 
1719     return err;
1720 }
1721 
setMaxDequeuedBufferCount(int maxDequeuedBuffers)1722 int Surface::setMaxDequeuedBufferCount(int maxDequeuedBuffers) {
1723     ATRACE_CALL();
1724     ALOGV("Surface::setMaxDequeuedBufferCount");
1725     Mutex::Autolock lock(mMutex);
1726 
1727     status_t err = mGraphicBufferProducer->setMaxDequeuedBufferCount(
1728             maxDequeuedBuffers);
1729     ALOGE_IF(err, "IGraphicBufferProducer::setMaxDequeuedBufferCount(%d) "
1730             "returned %s", maxDequeuedBuffers, strerror(-err));
1731 
1732     return err;
1733 }
1734 
setAsyncMode(bool async)1735 int Surface::setAsyncMode(bool async) {
1736     ATRACE_CALL();
1737     ALOGV("Surface::setAsyncMode");
1738     Mutex::Autolock lock(mMutex);
1739 
1740     status_t err = mGraphicBufferProducer->setAsyncMode(async);
1741     ALOGE_IF(err, "IGraphicBufferProducer::setAsyncMode(%d) returned %s",
1742             async, strerror(-err));
1743 
1744     return err;
1745 }
1746 
setSharedBufferMode(bool sharedBufferMode)1747 int Surface::setSharedBufferMode(bool sharedBufferMode) {
1748     ATRACE_CALL();
1749     ALOGV("Surface::setSharedBufferMode (%d)", sharedBufferMode);
1750     Mutex::Autolock lock(mMutex);
1751 
1752     status_t err = mGraphicBufferProducer->setSharedBufferMode(
1753             sharedBufferMode);
1754     if (err == NO_ERROR) {
1755         mSharedBufferMode = sharedBufferMode;
1756     }
1757     ALOGE_IF(err, "IGraphicBufferProducer::setSharedBufferMode(%d) returned"
1758             "%s", sharedBufferMode, strerror(-err));
1759 
1760     return err;
1761 }
1762 
setAutoRefresh(bool autoRefresh)1763 int Surface::setAutoRefresh(bool autoRefresh) {
1764     ATRACE_CALL();
1765     ALOGV("Surface::setAutoRefresh (%d)", autoRefresh);
1766     Mutex::Autolock lock(mMutex);
1767 
1768     status_t err = mGraphicBufferProducer->setAutoRefresh(autoRefresh);
1769     if (err == NO_ERROR) {
1770         mAutoRefresh = autoRefresh;
1771     }
1772     ALOGE_IF(err, "IGraphicBufferProducer::setAutoRefresh(%d) returned %s",
1773             autoRefresh, strerror(-err));
1774     return err;
1775 }
1776 
setBuffersDimensions(uint32_t width,uint32_t height)1777 int Surface::setBuffersDimensions(uint32_t width, uint32_t height)
1778 {
1779     ATRACE_CALL();
1780     ALOGV("Surface::setBuffersDimensions");
1781 
1782     if ((width && !height) || (!width && height))
1783         return BAD_VALUE;
1784 
1785     Mutex::Autolock lock(mMutex);
1786     if (width != mReqWidth || height != mReqHeight) {
1787         mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1788     }
1789     mReqWidth = width;
1790     mReqHeight = height;
1791     return NO_ERROR;
1792 }
1793 
setBuffersUserDimensions(uint32_t width,uint32_t height)1794 int Surface::setBuffersUserDimensions(uint32_t width, uint32_t height)
1795 {
1796     ATRACE_CALL();
1797     ALOGV("Surface::setBuffersUserDimensions");
1798 
1799     if ((width && !height) || (!width && height))
1800         return BAD_VALUE;
1801 
1802     Mutex::Autolock lock(mMutex);
1803     if (width != mUserWidth || height != mUserHeight) {
1804         mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1805     }
1806     mUserWidth = width;
1807     mUserHeight = height;
1808     return NO_ERROR;
1809 }
1810 
setBuffersFormat(PixelFormat format)1811 int Surface::setBuffersFormat(PixelFormat format)
1812 {
1813     ALOGV("Surface::setBuffersFormat");
1814 
1815     Mutex::Autolock lock(mMutex);
1816     if (format != mReqFormat) {
1817         mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
1818     }
1819     mReqFormat = format;
1820     return NO_ERROR;
1821 }
1822 
setScalingMode(int mode)1823 int Surface::setScalingMode(int mode)
1824 {
1825     ATRACE_CALL();
1826     ALOGV("Surface::setScalingMode(%d)", mode);
1827 
1828     switch (mode) {
1829         case NATIVE_WINDOW_SCALING_MODE_FREEZE:
1830         case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
1831         case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
1832         case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
1833             break;
1834         default:
1835             ALOGE("unknown scaling mode: %d", mode);
1836             return BAD_VALUE;
1837     }
1838 
1839     Mutex::Autolock lock(mMutex);
1840     mScalingMode = mode;
1841     return NO_ERROR;
1842 }
1843 
setBuffersTransform(uint32_t transform)1844 int Surface::setBuffersTransform(uint32_t transform)
1845 {
1846     ATRACE_CALL();
1847     ALOGV("Surface::setBuffersTransform");
1848     Mutex::Autolock lock(mMutex);
1849     // Ensure NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY is sticky. If the client sets the flag, do not
1850     // override it until the surface is disconnected. This is a temporary workaround for camera
1851     // until they switch to using Buffer State Layers. Currently if client sets the buffer transform
1852     // it may be overriden by the buffer producer when the producer sets the buffer transform.
1853     if (transformToDisplayInverse()) {
1854         transform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
1855     }
1856     mTransform = transform;
1857     return NO_ERROR;
1858 }
1859 
setBuffersStickyTransform(uint32_t transform)1860 int Surface::setBuffersStickyTransform(uint32_t transform)
1861 {
1862     ATRACE_CALL();
1863     ALOGV("Surface::setBuffersStickyTransform");
1864     Mutex::Autolock lock(mMutex);
1865     mStickyTransform = transform;
1866     return NO_ERROR;
1867 }
1868 
setBuffersTimestamp(int64_t timestamp)1869 int Surface::setBuffersTimestamp(int64_t timestamp)
1870 {
1871     ALOGV("Surface::setBuffersTimestamp");
1872     Mutex::Autolock lock(mMutex);
1873     mTimestamp = timestamp;
1874     return NO_ERROR;
1875 }
1876 
setBuffersDataSpace(Dataspace dataSpace)1877 int Surface::setBuffersDataSpace(Dataspace dataSpace)
1878 {
1879     ALOGV("Surface::setBuffersDataSpace");
1880     Mutex::Autolock lock(mMutex);
1881     mDataSpace = dataSpace;
1882     return NO_ERROR;
1883 }
1884 
setBuffersSmpte2086Metadata(const android_smpte2086_metadata * metadata)1885 int Surface::setBuffersSmpte2086Metadata(const android_smpte2086_metadata* metadata) {
1886     ALOGV("Surface::setBuffersSmpte2086Metadata");
1887     Mutex::Autolock lock(mMutex);
1888     if (metadata) {
1889         mHdrMetadata.smpte2086 = *metadata;
1890         mHdrMetadata.validTypes |= HdrMetadata::SMPTE2086;
1891     } else {
1892         mHdrMetadata.validTypes &= ~HdrMetadata::SMPTE2086;
1893     }
1894     return NO_ERROR;
1895 }
1896 
setBuffersCta8613Metadata(const android_cta861_3_metadata * metadata)1897 int Surface::setBuffersCta8613Metadata(const android_cta861_3_metadata* metadata) {
1898     ALOGV("Surface::setBuffersCta8613Metadata");
1899     Mutex::Autolock lock(mMutex);
1900     if (metadata) {
1901         mHdrMetadata.cta8613 = *metadata;
1902         mHdrMetadata.validTypes |= HdrMetadata::CTA861_3;
1903     } else {
1904         mHdrMetadata.validTypes &= ~HdrMetadata::CTA861_3;
1905     }
1906     return NO_ERROR;
1907 }
1908 
setBuffersHdr10PlusMetadata(const size_t size,const uint8_t * metadata)1909 int Surface::setBuffersHdr10PlusMetadata(const size_t size, const uint8_t* metadata) {
1910     ALOGV("Surface::setBuffersBlobMetadata");
1911     Mutex::Autolock lock(mMutex);
1912     if (size > 0) {
1913         mHdrMetadata.hdr10plus.assign(metadata, metadata + size);
1914         mHdrMetadata.validTypes |= HdrMetadata::HDR10PLUS;
1915     } else {
1916         mHdrMetadata.validTypes &= ~HdrMetadata::HDR10PLUS;
1917         mHdrMetadata.hdr10plus.clear();
1918     }
1919     return NO_ERROR;
1920 }
1921 
getBuffersDataSpace()1922 Dataspace Surface::getBuffersDataSpace() {
1923     ALOGV("Surface::getBuffersDataSpace");
1924     Mutex::Autolock lock(mMutex);
1925     return mDataSpace;
1926 }
1927 
freeAllBuffers()1928 void Surface::freeAllBuffers() {
1929     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
1930         mSlots[i].buffer = nullptr;
1931     }
1932 }
1933 
getAndFlushBuffersFromSlots(const std::vector<int32_t> & slots,std::vector<sp<GraphicBuffer>> * outBuffers)1934 status_t Surface::getAndFlushBuffersFromSlots(const std::vector<int32_t>& slots,
1935         std::vector<sp<GraphicBuffer>>* outBuffers) {
1936     ALOGV("Surface::getAndFlushBuffersFromSlots");
1937     for (int32_t i : slots) {
1938         if (i < 0 || i >= NUM_BUFFER_SLOTS) {
1939             ALOGE("%s: Invalid slotIndex: %d", __FUNCTION__, i);
1940             return BAD_VALUE;
1941         }
1942     }
1943 
1944     Mutex::Autolock lock(mMutex);
1945     for (int32_t i : slots) {
1946         if (mSlots[i].buffer == nullptr) {
1947             ALOGW("%s: Discarded slot %d doesn't contain buffer!", __FUNCTION__, i);
1948             continue;
1949         }
1950         outBuffers->push_back(mSlots[i].buffer);
1951         mSlots[i].buffer = nullptr;
1952     }
1953     return OK;
1954 }
1955 
setSurfaceDamage(android_native_rect_t * rects,size_t numRects)1956 void Surface::setSurfaceDamage(android_native_rect_t* rects, size_t numRects) {
1957     ATRACE_CALL();
1958     ALOGV("Surface::setSurfaceDamage");
1959     Mutex::Autolock lock(mMutex);
1960 
1961     if (mConnectedToCpu || numRects == 0) {
1962         mDirtyRegion = Region::INVALID_REGION;
1963         return;
1964     }
1965 
1966     mDirtyRegion.clear();
1967     for (size_t r = 0; r < numRects; ++r) {
1968         // We intentionally flip top and bottom here, since because they're
1969         // specified with a bottom-left origin, top > bottom, which fails
1970         // validation in the Region class. We will fix this up when we flip to a
1971         // top-left origin in queueBuffer.
1972         Rect rect(rects[r].left, rects[r].bottom, rects[r].right, rects[r].top);
1973         mDirtyRegion.orSelf(rect);
1974     }
1975 }
1976 
1977 // ----------------------------------------------------------------------
1978 // the lock/unlock APIs must be used from the same thread
1979 
copyBlt(const sp<GraphicBuffer> & dst,const sp<GraphicBuffer> & src,const Region & reg,int * dstFenceFd)1980 static status_t copyBlt(
1981         const sp<GraphicBuffer>& dst,
1982         const sp<GraphicBuffer>& src,
1983         const Region& reg,
1984         int *dstFenceFd)
1985 {
1986     if (dst->getId() == src->getId())
1987         return OK;
1988 
1989     // src and dst with, height and format must be identical. no verification
1990     // is done here.
1991     status_t err;
1992     uint8_t* src_bits = nullptr;
1993     err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(),
1994             reinterpret_cast<void**>(&src_bits));
1995     ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
1996 
1997     uint8_t* dst_bits = nullptr;
1998     err = dst->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(),
1999             reinterpret_cast<void**>(&dst_bits), *dstFenceFd);
2000     ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
2001     *dstFenceFd = -1;
2002 
2003     Region::const_iterator head(reg.begin());
2004     Region::const_iterator tail(reg.end());
2005     if (head != tail && src_bits && dst_bits) {
2006         const size_t bpp = bytesPerPixel(src->format);
2007         const size_t dbpr = static_cast<uint32_t>(dst->stride) * bpp;
2008         const size_t sbpr = static_cast<uint32_t>(src->stride) * bpp;
2009 
2010         while (head != tail) {
2011             const Rect& r(*head++);
2012             int32_t h = r.height();
2013             if (h <= 0) continue;
2014             size_t size = static_cast<uint32_t>(r.width()) * bpp;
2015             uint8_t const * s = src_bits +
2016                     static_cast<uint32_t>(r.left + src->stride * r.top) * bpp;
2017             uint8_t       * d = dst_bits +
2018                     static_cast<uint32_t>(r.left + dst->stride * r.top) * bpp;
2019             if (dbpr==sbpr && size==sbpr) {
2020                 size *= static_cast<size_t>(h);
2021                 h = 1;
2022             }
2023             do {
2024                 memcpy(d, s, size);
2025                 d += dbpr;
2026                 s += sbpr;
2027             } while (--h > 0);
2028         }
2029     }
2030 
2031     if (src_bits)
2032         src->unlock();
2033 
2034     if (dst_bits)
2035         dst->unlockAsync(dstFenceFd);
2036 
2037     return err;
2038 }
2039 
2040 // ----------------------------------------------------------------------------
2041 
lock(ANativeWindow_Buffer * outBuffer,ARect * inOutDirtyBounds)2042 status_t Surface::lock(
2043         ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds)
2044 {
2045     if (mLockedBuffer != nullptr) {
2046         ALOGE("Surface::lock failed, already locked");
2047         return INVALID_OPERATION;
2048     }
2049 
2050     if (!mConnectedToCpu) {
2051         int err = Surface::connect(NATIVE_WINDOW_API_CPU);
2052         if (err) {
2053             return err;
2054         }
2055         // we're intending to do software rendering from this point
2056         setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
2057     }
2058 
2059     ANativeWindowBuffer* out;
2060     int fenceFd = -1;
2061     status_t err = dequeueBuffer(&out, &fenceFd);
2062     ALOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
2063     if (err == NO_ERROR) {
2064         sp<GraphicBuffer> backBuffer(GraphicBuffer::getSelf(out));
2065         const Rect bounds(backBuffer->width, backBuffer->height);
2066 
2067         Region newDirtyRegion;
2068         if (inOutDirtyBounds) {
2069             newDirtyRegion.set(static_cast<Rect const&>(*inOutDirtyBounds));
2070             newDirtyRegion.andSelf(bounds);
2071         } else {
2072             newDirtyRegion.set(bounds);
2073         }
2074 
2075         // figure out if we can copy the frontbuffer back
2076         const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
2077         const bool canCopyBack = (frontBuffer != nullptr &&
2078                 backBuffer->width  == frontBuffer->width &&
2079                 backBuffer->height == frontBuffer->height &&
2080                 backBuffer->format == frontBuffer->format);
2081 
2082         if (canCopyBack) {
2083             // copy the area that is invalid and not repainted this round
2084             const Region copyback(mDirtyRegion.subtract(newDirtyRegion));
2085             if (!copyback.isEmpty()) {
2086                 copyBlt(backBuffer, frontBuffer, copyback, &fenceFd);
2087             }
2088         } else {
2089             // if we can't copy-back anything, modify the user's dirty
2090             // region to make sure they redraw the whole buffer
2091             newDirtyRegion.set(bounds);
2092             mDirtyRegion.clear();
2093             Mutex::Autolock lock(mMutex);
2094             for (size_t i=0 ; i<NUM_BUFFER_SLOTS ; i++) {
2095                 mSlots[i].dirtyRegion.clear();
2096             }
2097         }
2098 
2099 
2100         { // scope for the lock
2101             Mutex::Autolock lock(mMutex);
2102             int backBufferSlot(getSlotFromBufferLocked(backBuffer.get()));
2103             if (backBufferSlot >= 0) {
2104                 Region& dirtyRegion(mSlots[backBufferSlot].dirtyRegion);
2105                 mDirtyRegion.subtract(dirtyRegion);
2106                 dirtyRegion = newDirtyRegion;
2107             }
2108         }
2109 
2110         mDirtyRegion.orSelf(newDirtyRegion);
2111         if (inOutDirtyBounds) {
2112             *inOutDirtyBounds = newDirtyRegion.getBounds();
2113         }
2114 
2115         void* vaddr;
2116         status_t res = backBuffer->lockAsync(
2117                 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
2118                 newDirtyRegion.bounds(), &vaddr, fenceFd);
2119 
2120         ALOGW_IF(res, "failed locking buffer (handle = %p)",
2121                 backBuffer->handle);
2122 
2123         if (res != 0) {
2124             err = INVALID_OPERATION;
2125         } else {
2126             mLockedBuffer = backBuffer;
2127             outBuffer->width  = backBuffer->width;
2128             outBuffer->height = backBuffer->height;
2129             outBuffer->stride = backBuffer->stride;
2130             outBuffer->format = backBuffer->format;
2131             outBuffer->bits   = vaddr;
2132         }
2133     }
2134     return err;
2135 }
2136 
unlockAndPost()2137 status_t Surface::unlockAndPost()
2138 {
2139     if (mLockedBuffer == nullptr) {
2140         ALOGE("Surface::unlockAndPost failed, no locked buffer");
2141         return INVALID_OPERATION;
2142     }
2143 
2144     int fd = -1;
2145     status_t err = mLockedBuffer->unlockAsync(&fd);
2146     ALOGE_IF(err, "failed unlocking buffer (%p)", mLockedBuffer->handle);
2147 
2148     err = queueBuffer(mLockedBuffer.get(), fd);
2149     ALOGE_IF(err, "queueBuffer (handle=%p) failed (%s)",
2150             mLockedBuffer->handle, strerror(-err));
2151 
2152     mPostedBuffer = mLockedBuffer;
2153     mLockedBuffer = nullptr;
2154     return err;
2155 }
2156 
waitForNextFrame(uint64_t lastFrame,nsecs_t timeout)2157 bool Surface::waitForNextFrame(uint64_t lastFrame, nsecs_t timeout) {
2158     Mutex::Autolock lock(mMutex);
2159     if (mNextFrameNumber > lastFrame) {
2160       return true;
2161     }
2162     return mQueueBufferCondition.waitRelative(mMutex, timeout) == OK;
2163 }
2164 
getUniqueId(uint64_t * outId) const2165 status_t Surface::getUniqueId(uint64_t* outId) const {
2166     Mutex::Autolock lock(mMutex);
2167     return mGraphicBufferProducer->getUniqueId(outId);
2168 }
2169 
getConsumerUsage(uint64_t * outUsage) const2170 int Surface::getConsumerUsage(uint64_t* outUsage) const {
2171     Mutex::Autolock lock(mMutex);
2172     return mGraphicBufferProducer->getConsumerUsage(outUsage);
2173 }
2174 
getAndFlushRemovedBuffers(std::vector<sp<GraphicBuffer>> * out)2175 status_t Surface::getAndFlushRemovedBuffers(std::vector<sp<GraphicBuffer>>* out) {
2176     if (out == nullptr) {
2177         ALOGE("%s: out must not be null!", __FUNCTION__);
2178         return BAD_VALUE;
2179     }
2180 
2181     Mutex::Autolock lock(mMutex);
2182     *out = mRemovedBuffers;
2183     mRemovedBuffers.clear();
2184     return OK;
2185 }
2186 
attachAndQueueBufferWithDataspace(Surface * surface,sp<GraphicBuffer> buffer,Dataspace dataspace)2187 status_t Surface::attachAndQueueBufferWithDataspace(Surface* surface, sp<GraphicBuffer> buffer,
2188                                                     Dataspace dataspace) {
2189     if (buffer == nullptr) {
2190         return BAD_VALUE;
2191     }
2192     int err = static_cast<ANativeWindow*>(surface)->perform(surface, NATIVE_WINDOW_API_CONNECT,
2193                                                             NATIVE_WINDOW_API_CPU);
2194     if (err != OK) {
2195         return err;
2196     }
2197     ui::Dataspace tmpDataspace = surface->getBuffersDataSpace();
2198     err = surface->setBuffersDataSpace(dataspace);
2199     if (err != OK) {
2200         return err;
2201     }
2202     err = surface->attachBuffer(buffer->getNativeBuffer());
2203     if (err != OK) {
2204         return err;
2205     }
2206     err = static_cast<ANativeWindow*>(surface)->queueBuffer(surface, buffer->getNativeBuffer(), -1);
2207     if (err != OK) {
2208         return err;
2209     }
2210     err = surface->setBuffersDataSpace(tmpDataspace);
2211     if (err != OK) {
2212         return err;
2213     }
2214     err = surface->disconnect(NATIVE_WINDOW_API_CPU);
2215     return err;
2216 }
2217 
setAutoPrerotation(bool autoPrerotation)2218 int Surface::setAutoPrerotation(bool autoPrerotation) {
2219     ATRACE_CALL();
2220     ALOGV("Surface::setAutoPrerotation (%d)", autoPrerotation);
2221     Mutex::Autolock lock(mMutex);
2222 
2223     if (mAutoPrerotation == autoPrerotation) {
2224         return OK;
2225     }
2226 
2227     status_t err = mGraphicBufferProducer->setAutoPrerotation(autoPrerotation);
2228     if (err == NO_ERROR) {
2229         mAutoPrerotation = autoPrerotation;
2230     }
2231     ALOGE_IF(err, "IGraphicBufferProducer::setAutoPrerotation(%d) returned %s", autoPrerotation,
2232              strerror(-err));
2233     return err;
2234 }
2235 
onBuffersDiscarded(const std::vector<int32_t> & slots)2236 void Surface::ProducerListenerProxy::onBuffersDiscarded(const std::vector<int32_t>& slots) {
2237     ATRACE_CALL();
2238     sp<Surface> parent = mParent.promote();
2239     if (parent == nullptr) {
2240         return;
2241     }
2242 
2243     std::vector<sp<GraphicBuffer>> discardedBufs;
2244     status_t res = parent->getAndFlushBuffersFromSlots(slots, &discardedBufs);
2245     if (res != OK) {
2246         ALOGE("%s: Failed to get buffers from slots: %s(%d)", __FUNCTION__,
2247                 strerror(-res), res);
2248         return;
2249     }
2250 
2251     mSurfaceListener->onBuffersDiscarded(discardedBufs);
2252 }
2253 
setFrameRate(float frameRate,int8_t compatibility)2254 status_t Surface::setFrameRate(float frameRate, int8_t compatibility) {
2255     ATRACE_CALL();
2256     ALOGV("Surface::setFrameRate");
2257 
2258     if (!ValidateFrameRate(frameRate, compatibility, "Surface::setFrameRate")) {
2259         return BAD_VALUE;
2260     }
2261 
2262     return composerService()->setFrameRate(mGraphicBufferProducer, frameRate, compatibility);
2263 }
2264 
2265 }; // namespace android
2266