-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSurface.cpp
More file actions
2669 lines (2303 loc) · 88.6 KB
/
Surface.cpp
File metadata and controls
2669 lines (2303 loc) · 88.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Surface"
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
//#define LOG_NDEBUG 0
#include <gui/Surface.h>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <thread>
#include <inttypes.h>
#include <android/gui/DisplayStatInfo.h>
#include <android/native_window.h>
#include <utils/Log.h>
#include <utils/Trace.h>
#include <utils/NativeHandle.h>
#include <ui/DynamicDisplayInfo.h>
#include <ui/Fence.h>
#include <ui/GraphicBuffer.h>
#include <ui/Region.h>
#include <gui/BufferItem.h>
#include <gui/IProducerListener.h>
#include <gui/ISurfaceComposer.h>
#include <gui/LayerState.h>
#include <private/gui/ComposerService.h>
#include <private/gui/ComposerServiceAIDL.h>
namespace android {
using ui::Dataspace;
namespace {
bool isInterceptorRegistrationOp(int op) {
return op == NATIVE_WINDOW_SET_CANCEL_INTERCEPTOR ||
op == NATIVE_WINDOW_SET_DEQUEUE_INTERCEPTOR ||
op == NATIVE_WINDOW_SET_PERFORM_INTERCEPTOR ||
op == NATIVE_WINDOW_SET_QUEUE_INTERCEPTOR ||
op == NATIVE_WINDOW_SET_QUERY_INTERCEPTOR;
}
} // namespace
Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp,
const sp<IBinder>& surfaceControlHandle)
: mGraphicBufferProducer(bufferProducer),
mCrop(Rect::EMPTY_RECT),
mBufferAge(0),
mGenerationNumber(0),
mSharedBufferMode(false),
mAutoRefresh(false),
mAutoPrerotation(false),
mSharedBufferSlot(BufferItem::INVALID_BUFFER_SLOT),
mSharedBufferHasBeenQueued(false),
mQueriedSupportedTimestamps(false),
mFrameTimestampsSupportsPresent(false),
mEnableFrameTimestamps(false),
mFrameEventHistory(std::make_unique<ProducerFrameEventHistory>()) {
// Initialize the ANativeWindow function pointers.
ANativeWindow::setSwapInterval = hook_setSwapInterval;
ANativeWindow::dequeueBuffer = hook_dequeueBuffer;
ANativeWindow::cancelBuffer = hook_cancelBuffer;
ANativeWindow::queueBuffer = hook_queueBuffer;
ANativeWindow::query = hook_query;
ANativeWindow::perform = hook_perform;
ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
ANativeWindow::cancelBuffer_DEPRECATED = hook_cancelBuffer_DEPRECATED;
ANativeWindow::lockBuffer_DEPRECATED = hook_lockBuffer_DEPRECATED;
ANativeWindow::queueBuffer_DEPRECATED = hook_queueBuffer_DEPRECATED;
const_cast<int&>(ANativeWindow::minSwapInterval) = 0;
const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;
mReqWidth = 0;
mReqHeight = 0;
mReqFormat = 0;
mReqUsage = 0;
mTimestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
mDataSpace = Dataspace::UNKNOWN;
mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
mTransform = 0;
mStickyTransform = 0;
mDefaultWidth = 0;
mDefaultHeight = 0;
mUserWidth = 0;
mUserHeight = 0;
mTransformHint = 0;
mConsumerRunningBehind = false;
mConnectedToCpu = false;
mProducerControlledByApp = controlledByApp;
mSwapIntervalZero = false;
mMaxBufferCount = NUM_BUFFER_SLOTS;
mSurfaceControlHandle = surfaceControlHandle;
}
Surface::~Surface() {
if (mConnectedToCpu) {
Surface::disconnect(NATIVE_WINDOW_API_CPU);
}
}
sp<ISurfaceComposer> Surface::composerService() const {
return ComposerService::getComposerService();
}
sp<gui::ISurfaceComposer> Surface::composerServiceAIDL() const {
return ComposerServiceAIDL::getComposerService();
}
nsecs_t Surface::now() const {
return systemTime();
}
sp<IGraphicBufferProducer> Surface::getIGraphicBufferProducer() const {
return mGraphicBufferProducer;
}
void Surface::setSidebandStream(const sp<NativeHandle>& stream) {
mGraphicBufferProducer->setSidebandStream(stream);
}
void Surface::allocateBuffers() {
uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
mGraphicBufferProducer->allocateBuffers(reqWidth, reqHeight,
mReqFormat, mReqUsage);
}
status_t Surface::setGenerationNumber(uint32_t generation) {
status_t result = mGraphicBufferProducer->setGenerationNumber(generation);
if (result == NO_ERROR) {
mGenerationNumber = generation;
}
return result;
}
uint64_t Surface::getNextFrameNumber() const {
Mutex::Autolock lock(mMutex);
return mNextFrameNumber;
}
String8 Surface::getConsumerName() const {
return mGraphicBufferProducer->getConsumerName();
}
status_t Surface::setDequeueTimeout(nsecs_t timeout) {
return mGraphicBufferProducer->setDequeueTimeout(timeout);
}
status_t Surface::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
sp<Fence>* outFence, float outTransformMatrix[16]) {
return mGraphicBufferProducer->getLastQueuedBuffer(outBuffer, outFence,
outTransformMatrix);
}
status_t Surface::getDisplayRefreshCycleDuration(nsecs_t* outRefreshDuration) {
ATRACE_CALL();
gui::DisplayStatInfo stats;
binder::Status status = composerServiceAIDL()->getDisplayStats(nullptr, &stats);
if (!status.isOk()) {
return status.transactionError();
}
*outRefreshDuration = stats.vsyncPeriod;
return NO_ERROR;
}
void Surface::enableFrameTimestamps(bool enable) {
Mutex::Autolock lock(mMutex);
// If going from disabled to enabled, get the initial values for
// compositor and display timing.
if (!mEnableFrameTimestamps && enable) {
FrameEventHistoryDelta delta;
mGraphicBufferProducer->getFrameTimestamps(&delta);
mFrameEventHistory->applyDelta(delta);
}
mEnableFrameTimestamps = enable;
}
status_t Surface::getCompositorTiming(
nsecs_t* compositeDeadline, nsecs_t* compositeInterval,
nsecs_t* compositeToPresentLatency) {
Mutex::Autolock lock(mMutex);
if (!mEnableFrameTimestamps) {
return INVALID_OPERATION;
}
if (compositeDeadline != nullptr) {
*compositeDeadline =
mFrameEventHistory->getNextCompositeDeadline(now());
}
if (compositeInterval != nullptr) {
*compositeInterval = mFrameEventHistory->getCompositeInterval();
}
if (compositeToPresentLatency != nullptr) {
*compositeToPresentLatency =
mFrameEventHistory->getCompositeToPresentLatency();
}
return NO_ERROR;
}
static bool 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) {
bool checkForLatch = (outLatchTime != nullptr) && !e->hasLatchInfo();
bool checkForFirstRefreshStart = (outFirstRefreshStartTime != nullptr) &&
!e->hasFirstRefreshStartInfo();
bool checkForGpuCompositionDone = (outGpuCompositionDoneTime != nullptr) &&
!e->hasGpuCompositionDoneInfo();
bool checkForDisplayPresent = (outDisplayPresentTime != nullptr) &&
!e->hasDisplayPresentInfo();
// LastRefreshStart, DequeueReady, and Release are never available for the
// last frame.
bool checkForLastRefreshStart = (outLastRefreshStartTime != nullptr) &&
!e->hasLastRefreshStartInfo() &&
(e->frameNumber != lastFrameNumber);
bool checkForDequeueReady = (outDequeueReadyTime != nullptr) &&
!e->hasDequeueReadyInfo() && (e->frameNumber != lastFrameNumber);
bool checkForRelease = (outReleaseTime != nullptr) &&
!e->hasReleaseInfo() && (e->frameNumber != lastFrameNumber);
// RequestedPresent and Acquire info are always available producer-side.
return checkForLatch || checkForFirstRefreshStart ||
checkForLastRefreshStart || checkForGpuCompositionDone ||
checkForDisplayPresent || checkForDequeueReady || checkForRelease;
}
static void getFrameTimestamp(nsecs_t *dst, const nsecs_t& src) {
if (dst != nullptr) {
// We always get valid timestamps for these eventually.
*dst = (src == FrameEvents::TIMESTAMP_PENDING) ?
NATIVE_WINDOW_TIMESTAMP_PENDING : src;
}
}
static void getFrameTimestampFence(nsecs_t *dst,
const std::shared_ptr<FenceTime>& src, bool fenceShouldBeKnown) {
if (dst != nullptr) {
if (!fenceShouldBeKnown) {
*dst = NATIVE_WINDOW_TIMESTAMP_PENDING;
return;
}
nsecs_t signalTime = src->getSignalTime();
*dst = (signalTime == Fence::SIGNAL_TIME_PENDING) ?
NATIVE_WINDOW_TIMESTAMP_PENDING :
(signalTime == Fence::SIGNAL_TIME_INVALID) ?
NATIVE_WINDOW_TIMESTAMP_INVALID :
signalTime;
}
}
status_t Surface::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) {
ATRACE_CALL();
Mutex::Autolock lock(mMutex);
if (!mEnableFrameTimestamps) {
return INVALID_OPERATION;
}
// Verify the requested timestamps are supported.
querySupportedTimestampsLocked();
if (outDisplayPresentTime != nullptr && !mFrameTimestampsSupportsPresent) {
return BAD_VALUE;
}
FrameEvents* events = mFrameEventHistory->getFrame(frameNumber);
if (events == nullptr) {
// If the entry isn't available in the producer, it's definitely not
// available in the consumer.
return NAME_NOT_FOUND;
}
// Update our cache of events if the requested events are not available.
if (checkConsumerForUpdates(events, mLastFrameNumber,
outLatchTime, outFirstRefreshStartTime, outLastRefreshStartTime,
outGpuCompositionDoneTime, outDisplayPresentTime,
outDequeueReadyTime, outReleaseTime)) {
FrameEventHistoryDelta delta;
mGraphicBufferProducer->getFrameTimestamps(&delta);
mFrameEventHistory->applyDelta(delta);
events = mFrameEventHistory->getFrame(frameNumber);
}
if (events == nullptr) {
// The entry was available before the update, but was overwritten
// after the update. Make sure not to send the wrong frame's data.
return NAME_NOT_FOUND;
}
getFrameTimestamp(outRequestedPresentTime, events->requestedPresentTime);
getFrameTimestamp(outLatchTime, events->latchTime);
getFrameTimestamp(outFirstRefreshStartTime, events->firstRefreshStartTime);
getFrameTimestamp(outLastRefreshStartTime, events->lastRefreshStartTime);
getFrameTimestamp(outDequeueReadyTime, events->dequeueReadyTime);
getFrameTimestampFence(outAcquireTime, events->acquireFence,
events->hasAcquireInfo());
getFrameTimestampFence(outGpuCompositionDoneTime,
events->gpuCompositionDoneFence,
events->hasGpuCompositionDoneInfo());
getFrameTimestampFence(outDisplayPresentTime, events->displayPresentFence,
events->hasDisplayPresentInfo());
getFrameTimestampFence(outReleaseTime, events->releaseFence,
events->hasReleaseInfo());
return NO_ERROR;
}
status_t Surface::getWideColorSupport(bool* supported) {
ATRACE_CALL();
const sp<IBinder> display = ComposerServiceAIDL::getInstance().getInternalDisplayToken();
if (display == nullptr) {
return NAME_NOT_FOUND;
}
*supported = false;
binder::Status status = composerServiceAIDL()->isWideColorDisplay(display, supported);
return status.transactionError();
}
status_t Surface::getHdrSupport(bool* supported) {
ATRACE_CALL();
const sp<IBinder> display = ComposerServiceAIDL::getInstance().getInternalDisplayToken();
if (display == nullptr) {
return NAME_NOT_FOUND;
}
ui::DynamicDisplayInfo info;
if (status_t err = composerService()->getDynamicDisplayInfo(display, &info); err != NO_ERROR) {
return err;
}
*supported = !info.hdrCapabilities.getSupportedHdrTypes().empty();
return NO_ERROR;
}
int Surface::hook_setSwapInterval(ANativeWindow* window, int interval) {
Surface* c = getSelf(window);
return c->setSwapInterval(interval);
}
int Surface::hook_dequeueBuffer(ANativeWindow* window,
ANativeWindowBuffer** buffer, int* fenceFd) {
Surface* c = getSelf(window);
{
std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
if (c->mDequeueInterceptor != nullptr) {
auto interceptor = c->mDequeueInterceptor;
auto data = c->mDequeueInterceptorData;
return interceptor(window, Surface::dequeueBufferInternal, data, buffer, fenceFd);
}
}
return c->dequeueBuffer(buffer, fenceFd);
}
int Surface::dequeueBufferInternal(ANativeWindow* window, ANativeWindowBuffer** buffer,
int* fenceFd) {
Surface* c = getSelf(window);
return c->dequeueBuffer(buffer, fenceFd);
}
int Surface::hook_cancelBuffer(ANativeWindow* window,
ANativeWindowBuffer* buffer, int fenceFd) {
Surface* c = getSelf(window);
{
std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
if (c->mCancelInterceptor != nullptr) {
auto interceptor = c->mCancelInterceptor;
auto data = c->mCancelInterceptorData;
return interceptor(window, Surface::cancelBufferInternal, data, buffer, fenceFd);
}
}
return c->cancelBuffer(buffer, fenceFd);
}
int Surface::cancelBufferInternal(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
Surface* c = getSelf(window);
return c->cancelBuffer(buffer, fenceFd);
}
int Surface::hook_queueBuffer(ANativeWindow* window,
ANativeWindowBuffer* buffer, int fenceFd) {
Surface* c = getSelf(window);
{
std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
if (c->mQueueInterceptor != nullptr) {
auto interceptor = c->mQueueInterceptor;
auto data = c->mQueueInterceptorData;
return interceptor(window, Surface::queueBufferInternal, data, buffer, fenceFd);
}
}
return c->queueBuffer(buffer, fenceFd);
}
int Surface::queueBufferInternal(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
Surface* c = getSelf(window);
return c->queueBuffer(buffer, fenceFd);
}
int Surface::hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer** buffer) {
Surface* c = getSelf(window);
ANativeWindowBuffer* buf;
int fenceFd = -1;
int result = c->dequeueBuffer(&buf, &fenceFd);
if (result != OK) {
return result;
}
sp<Fence> fence(new Fence(fenceFd));
int waitResult = fence->waitForever("dequeueBuffer_DEPRECATED");
if (waitResult != OK) {
ALOGE("dequeueBuffer_DEPRECATED: Fence::wait returned an error: %d",
waitResult);
c->cancelBuffer(buf, -1);
return waitResult;
}
*buffer = buf;
return result;
}
int Surface::hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer* buffer) {
Surface* c = getSelf(window);
return c->cancelBuffer(buffer, -1);
}
int Surface::hook_lockBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer* buffer) {
Surface* c = getSelf(window);
return c->lockBuffer_DEPRECATED(buffer);
}
int Surface::hook_queueBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer* buffer) {
Surface* c = getSelf(window);
return c->queueBuffer(buffer, -1);
}
int Surface::hook_perform(ANativeWindow* window, int operation, ...) {
va_list args;
va_start(args, operation);
Surface* c = getSelf(window);
int result;
// Don't acquire shared ownership of the interceptor mutex if we're going to
// do interceptor registration, as otherwise we'll deadlock on acquiring
// exclusive ownership.
if (!isInterceptorRegistrationOp(operation)) {
std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
if (c->mPerformInterceptor != nullptr) {
result = c->mPerformInterceptor(window, Surface::performInternal,
c->mPerformInterceptorData, operation, args);
va_end(args);
return result;
}
}
result = c->perform(operation, args);
va_end(args);
return result;
}
int Surface::performInternal(ANativeWindow* window, int operation, va_list args) {
Surface* c = getSelf(window);
return c->perform(operation, args);
}
int Surface::hook_query(const ANativeWindow* window, int what, int* value) {
const Surface* c = getSelf(window);
{
std::shared_lock<std::shared_mutex> lock(c->mInterceptorMutex);
if (c->mQueryInterceptor != nullptr) {
auto interceptor = c->mQueryInterceptor;
auto data = c->mQueryInterceptorData;
return interceptor(window, Surface::queryInternal, data, what, value);
}
}
return c->query(what, value);
}
int Surface::queryInternal(const ANativeWindow* window, int what, int* value) {
const Surface* c = getSelf(window);
return c->query(what, value);
}
int Surface::setSwapInterval(int interval) {
ATRACE_CALL();
// EGL specification states:
// interval is silently clamped to minimum and maximum implementation
// dependent values before being stored.
if (interval < minSwapInterval)
interval = minSwapInterval;
if (interval > maxSwapInterval)
interval = maxSwapInterval;
const bool wasSwapIntervalZero = mSwapIntervalZero;
mSwapIntervalZero = (interval == 0);
if (mSwapIntervalZero != wasSwapIntervalZero) {
mGraphicBufferProducer->setAsyncMode(mSwapIntervalZero);
}
return NO_ERROR;
}
class FenceMonitor {
public:
explicit FenceMonitor(const char* name) : mName(name), mFencesQueued(0), mFencesSignaled(0) {
std::thread thread(&FenceMonitor::loop, this);
pthread_setname_np(thread.native_handle(), mName);
thread.detach();
}
void queueFence(const sp<Fence>& fence) {
char message[64];
std::lock_guard<std::mutex> lock(mMutex);
if (fence->getSignalTime() != Fence::SIGNAL_TIME_PENDING) {
snprintf(message, sizeof(message), "%s fence %u has signaled", mName, mFencesQueued);
ATRACE_NAME(message);
// Need an increment on both to make the trace number correct.
mFencesQueued++;
mFencesSignaled++;
return;
}
snprintf(message, sizeof(message), "Trace %s fence %u", mName, mFencesQueued);
ATRACE_NAME(message);
mQueue.push_back(fence);
mCondition.notify_one();
mFencesQueued++;
ATRACE_INT(mName, int32_t(mQueue.size()));
}
private:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
void loop() {
while (true) {
threadLoop();
}
}
#pragma clang diagnostic pop
void threadLoop() {
sp<Fence> fence;
uint32_t fenceNum;
{
std::unique_lock<std::mutex> lock(mMutex);
while (mQueue.empty()) {
mCondition.wait(lock);
}
fence = mQueue[0];
fenceNum = mFencesSignaled;
}
{
char message[64];
snprintf(message, sizeof(message), "waiting for %s %u", mName, fenceNum);
ATRACE_NAME(message);
status_t result = fence->waitForever(message);
if (result != OK) {
ALOGE("Error waiting for fence: %d", result);
}
}
{
std::lock_guard<std::mutex> lock(mMutex);
mQueue.pop_front();
mFencesSignaled++;
ATRACE_INT(mName, int32_t(mQueue.size()));
}
}
const char* mName;
uint32_t mFencesQueued;
uint32_t mFencesSignaled;
std::deque<sp<Fence>> mQueue;
std::condition_variable mCondition;
std::mutex mMutex;
};
void Surface::getDequeueBufferInputLocked(
IGraphicBufferProducer::DequeueBufferInput* dequeueInput) {
LOG_ALWAYS_FATAL_IF(dequeueInput == nullptr, "input is null");
dequeueInput->width = mReqWidth ? mReqWidth : mUserWidth;
dequeueInput->height = mReqHeight ? mReqHeight : mUserHeight;
dequeueInput->format = mReqFormat;
dequeueInput->usage = mReqUsage;
dequeueInput->getTimestamps = mEnableFrameTimestamps;
}
int Surface::dequeueBuffer(android_native_buffer_t** buffer, int* fenceFd) {
ATRACE_CALL();
ALOGV("Surface::dequeueBuffer");
IGraphicBufferProducer::DequeueBufferInput dqInput;
{
Mutex::Autolock lock(mMutex);
if (mReportRemovedBuffers) {
mRemovedBuffers.clear();
}
getDequeueBufferInputLocked(&dqInput);
if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot !=
BufferItem::INVALID_BUFFER_SLOT) {
sp<GraphicBuffer>& gbuf(mSlots[mSharedBufferSlot].buffer);
if (gbuf != nullptr) {
*buffer = gbuf.get();
*fenceFd = -1;
return OK;
}
}
} // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffer
int buf = -1;
sp<Fence> fence;
nsecs_t startTime = systemTime();
FrameEventHistoryDelta frameTimestamps;
status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, dqInput.width,
dqInput.height, dqInput.format,
dqInput.usage, &mBufferAge,
dqInput.getTimestamps ?
&frameTimestamps : nullptr);
mLastDequeueDuration = systemTime() - startTime;
if (result < 0) {
ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer"
"(%d, %d, %d, %#" PRIx64 ") failed: %d",
dqInput.width, dqInput.height, dqInput.format, dqInput.usage, result);
return result;
}
if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
ALOGE("dequeueBuffer: IGraphicBufferProducer returned invalid slot number %d", buf);
android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
return FAILED_TRANSACTION;
}
Mutex::Autolock lock(mMutex);
// Write this while holding the mutex
mLastDequeueStartTime = startTime;
sp<GraphicBuffer>& gbuf(mSlots[buf].buffer);
// this should never happen
ALOGE_IF(fence == nullptr, "Surface::dequeueBuffer: received null Fence! buf=%d", buf);
if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
static FenceMonitor hwcReleaseThread("HWC release");
hwcReleaseThread.queueFence(fence);
}
if (result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
freeAllBuffers();
}
if (dqInput.getTimestamps) {
mFrameEventHistory->applyDelta(frameTimestamps);
}
if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == nullptr) {
if (mReportRemovedBuffers && (gbuf != nullptr)) {
mRemovedBuffers.push_back(gbuf);
}
result = mGraphicBufferProducer->requestBuffer(buf, &gbuf);
if (result != NO_ERROR) {
ALOGE("dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: %d", result);
mGraphicBufferProducer->cancelBuffer(buf, fence);
return result;
}
}
if (fence->isValid()) {
*fenceFd = fence->dup();
if (*fenceFd == -1) {
ALOGE("dequeueBuffer: error duping fence: %d", errno);
// dup() should never fail; something is badly wrong. Soldier on
// and hope for the best; the worst that should happen is some
// visible corruption that lasts until the next frame.
}
} else {
*fenceFd = -1;
}
*buffer = gbuf.get();
if (mSharedBufferMode && mAutoRefresh) {
mSharedBufferSlot = buf;
mSharedBufferHasBeenQueued = false;
} else if (mSharedBufferSlot == buf) {
mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
mSharedBufferHasBeenQueued = false;
}
mDequeuedSlots.insert(buf);
return OK;
}
int Surface::dequeueBuffers(std::vector<BatchBuffer>* buffers) {
using DequeueBufferInput = IGraphicBufferProducer::DequeueBufferInput;
using DequeueBufferOutput = IGraphicBufferProducer::DequeueBufferOutput;
using CancelBufferInput = IGraphicBufferProducer::CancelBufferInput;
using RequestBufferOutput = IGraphicBufferProducer::RequestBufferOutput;
ATRACE_CALL();
ALOGV("Surface::dequeueBuffers");
if (buffers->size() == 0) {
ALOGE("%s: must dequeue at least 1 buffer!", __FUNCTION__);
return BAD_VALUE;
}
if (mSharedBufferMode) {
ALOGE("%s: batch operation is not supported in shared buffer mode!",
__FUNCTION__);
return INVALID_OPERATION;
}
size_t numBufferRequested = buffers->size();
DequeueBufferInput input;
{
Mutex::Autolock lock(mMutex);
if (mReportRemovedBuffers) {
mRemovedBuffers.clear();
}
getDequeueBufferInputLocked(&input);
} // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffers
std::vector<DequeueBufferInput> dequeueInput(numBufferRequested, input);
std::vector<DequeueBufferOutput> dequeueOutput;
nsecs_t startTime = systemTime();
status_t result = mGraphicBufferProducer->dequeueBuffers(dequeueInput, &dequeueOutput);
mLastDequeueDuration = systemTime() - startTime;
if (result < 0) {
ALOGV("%s: IGraphicBufferProducer::dequeueBuffers"
"(%d, %d, %d, %#" PRIx64 ") failed: %d",
__FUNCTION__, input.width, input.height, input.format, input.usage, result);
return result;
}
std::vector<CancelBufferInput> cancelBufferInputs(numBufferRequested);
std::vector<status_t> cancelBufferOutputs;
for (size_t i = 0; i < numBufferRequested; i++) {
cancelBufferInputs[i].slot = dequeueOutput[i].slot;
cancelBufferInputs[i].fence = dequeueOutput[i].fence;
}
for (const auto& output : dequeueOutput) {
if (output.result < 0) {
mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
ALOGV("%s: IGraphicBufferProducer::dequeueBuffers"
"(%d, %d, %d, %#" PRIx64 ") failed: %d",
__FUNCTION__, input.width, input.height, input.format, input.usage,
output.result);
return output.result;
}
if (output.slot < 0 || output.slot >= NUM_BUFFER_SLOTS) {
mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
ALOGE("%s: IGraphicBufferProducer returned invalid slot number %d",
__FUNCTION__, output.slot);
android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
return FAILED_TRANSACTION;
}
if (input.getTimestamps && !output.timestamps.has_value()) {
mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
ALOGE("%s: no frame timestamp returns!", __FUNCTION__);
return FAILED_TRANSACTION;
}
// this should never happen
ALOGE_IF(output.fence == nullptr,
"%s: received null Fence! slot=%d", __FUNCTION__, output.slot);
}
Mutex::Autolock lock(mMutex);
// Write this while holding the mutex
mLastDequeueStartTime = startTime;
std::vector<int32_t> requestBufferSlots;
requestBufferSlots.reserve(numBufferRequested);
// handle release all buffers and request buffers
for (const auto& output : dequeueOutput) {
if (output.result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
ALOGV("%s: RELEASE_ALL_BUFFERS during batch operation", __FUNCTION__);
freeAllBuffers();
break;
}
}
for (const auto& output : dequeueOutput) {
// Collect slots that needs requesting buffer
sp<GraphicBuffer>& gbuf(mSlots[output.slot].buffer);
if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == nullptr) {
if (mReportRemovedBuffers && (gbuf != nullptr)) {
mRemovedBuffers.push_back(gbuf);
}
requestBufferSlots.push_back(output.slot);
}
}
// Batch request Buffer
std::vector<RequestBufferOutput> reqBufferOutput;
if (requestBufferSlots.size() > 0) {
result = mGraphicBufferProducer->requestBuffers(requestBufferSlots, &reqBufferOutput);
if (result != NO_ERROR) {
ALOGE("%s: IGraphicBufferProducer::requestBuffers failed: %d",
__FUNCTION__, result);
mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
return result;
}
// Check if we have any single failure
for (size_t i = 0; i < requestBufferSlots.size(); i++) {
if (reqBufferOutput[i].result != OK) {
ALOGE("%s: IGraphicBufferProducer::requestBuffers failed at %zu-th buffer, slot %d",
__FUNCTION__, i, requestBufferSlots[i]);
mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
return reqBufferOutput[i].result;
}
}
// Fill request buffer results to mSlots
for (size_t i = 0; i < requestBufferSlots.size(); i++) {
mSlots[requestBufferSlots[i]].buffer = reqBufferOutput[i].buffer;
}
}
for (size_t batchIdx = 0; batchIdx < numBufferRequested; batchIdx++) {
const auto& output = dequeueOutput[batchIdx];
int slot = output.slot;
sp<GraphicBuffer>& gbuf(mSlots[slot].buffer);
if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
static FenceMonitor hwcReleaseThread("HWC release");
hwcReleaseThread.queueFence(output.fence);
}
if (input.getTimestamps) {
mFrameEventHistory->applyDelta(output.timestamps.value());
}
if (output.fence->isValid()) {
buffers->at(batchIdx).fenceFd = output.fence->dup();
if (buffers->at(batchIdx).fenceFd == -1) {
ALOGE("%s: error duping fence: %d", __FUNCTION__, errno);
// dup() should never fail; something is badly wrong. Soldier on
// and hope for the best; the worst that should happen is some
// visible corruption that lasts until the next frame.
}
} else {
buffers->at(batchIdx).fenceFd = -1;
}
buffers->at(batchIdx).buffer = gbuf.get();
mDequeuedSlots.insert(slot);
}
return OK;
}
int Surface::cancelBuffer(android_native_buffer_t* buffer,
int fenceFd) {
ATRACE_CALL();
ALOGV("Surface::cancelBuffer");
Mutex::Autolock lock(mMutex);
int i = getSlotFromBufferLocked(buffer);
if (i < 0) {
if (fenceFd >= 0) {
close(fenceFd);
}
return i;
}
if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
if (fenceFd >= 0) {
close(fenceFd);
}
return OK;
}
sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
mGraphicBufferProducer->cancelBuffer(i, fence);
if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
mSharedBufferHasBeenQueued = true;
}
mDequeuedSlots.erase(i);
return OK;
}
int Surface::cancelBuffers(const std::vector<BatchBuffer>& buffers) {
using CancelBufferInput = IGraphicBufferProducer::CancelBufferInput;
ATRACE_CALL();
ALOGV("Surface::cancelBuffers");
if (mSharedBufferMode) {
ALOGE("%s: batch operation is not supported in shared buffer mode!",
__FUNCTION__);
return INVALID_OPERATION;
}
size_t numBuffers = buffers.size();
std::vector<CancelBufferInput> cancelBufferInputs(numBuffers);
std::vector<status_t> cancelBufferOutputs;
size_t numBuffersCancelled = 0;
int badSlotResult = 0;
for (size_t i = 0; i < numBuffers; i++) {
int slot = getSlotFromBufferLocked(buffers[i].buffer);
int fenceFd = buffers[i].fenceFd;
if (slot < 0) {
if (fenceFd >= 0) {
close(fenceFd);
}
ALOGE("%s: cannot find slot number for cancelled buffer", __FUNCTION__);
badSlotResult = slot;
} else {
sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
cancelBufferInputs[numBuffersCancelled].slot = slot;
cancelBufferInputs[numBuffersCancelled++].fence = fence;
}
}
cancelBufferInputs.resize(numBuffersCancelled);
mGraphicBufferProducer->cancelBuffers(cancelBufferInputs, &cancelBufferOutputs);
for (size_t i = 0; i < numBuffersCancelled; i++) {
mDequeuedSlots.erase(cancelBufferInputs[i].slot);
}
if (badSlotResult != 0) {
return badSlotResult;
}
return OK;
}
int Surface::getSlotFromBufferLocked(
android_native_buffer_t* buffer) const {
if (buffer == nullptr) {
ALOGE("%s: input buffer is null!", __FUNCTION__);
return BAD_VALUE;
}
for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
if (mSlots[i].buffer != nullptr &&