• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 #include "MockConsumer.h"
18 
19 #include <gtest/gtest.h>
20 
21 #include <SurfaceFlingerProperties.h>
22 #include <android/gui/IDisplayEventConnection.h>
23 #include <android/gui/ISurfaceComposer.h>
24 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
25 #include <binder/ProcessState.h>
26 #include <configstore/Utils.h>
27 #include <gui/BufferItemConsumer.h>
28 #include <gui/IProducerListener.h>
29 #include <gui/ISurfaceComposer.h>
30 #include <gui/Surface.h>
31 #include <gui/SurfaceComposerClient.h>
32 #include <gui/SyncScreenCaptureListener.h>
33 #include <inttypes.h>
34 #include <private/gui/ComposerService.h>
35 #include <private/gui/ComposerServiceAIDL.h>
36 #include <sys/types.h>
37 #include <ui/BufferQueueDefs.h>
38 #include <ui/DisplayMode.h>
39 #include <ui/Rect.h>
40 #include <utils/Errors.h>
41 #include <utils/String8.h>
42 
43 #include <limits>
44 #include <thread>
45 
46 namespace android {
47 
48 using namespace std::chrono_literals;
49 // retrieve wide-color and hdr settings from configstore
50 using namespace android::hardware::configstore;
51 using namespace android::hardware::configstore::V1_0;
52 using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
53 using gui::IDisplayEventConnection;
54 using gui::IRegionSamplingListener;
55 using ui::ColorMode;
56 
57 using Transaction = SurfaceComposerClient::Transaction;
58 
59 static bool hasWideColorDisplay = android::sysprop::has_wide_color_display(false);
60 
61 static bool hasHdrDisplay = android::sysprop::has_HDR_display(false);
62 
63 class FakeSurfaceComposer;
64 class FakeProducerFrameEventHistory;
65 
66 static constexpr uint64_t NO_FRAME_INDEX = std::numeric_limits<uint64_t>::max();
67 
68 class FakeSurfaceListener : public SurfaceListener {
69 public:
FakeSurfaceListener(bool enableReleasedCb=false)70     FakeSurfaceListener(bool enableReleasedCb = false)
71           : mEnableReleaseCb(enableReleasedCb), mBuffersReleased(0) {}
72     virtual ~FakeSurfaceListener() = default;
73 
onBufferReleased()74     virtual void onBufferReleased() {
75         mBuffersReleased++;
76     }
needsReleaseNotify()77     virtual bool needsReleaseNotify() {
78         return mEnableReleaseCb;
79     }
onBuffersDiscarded(const std::vector<sp<GraphicBuffer>> & buffers)80     virtual void onBuffersDiscarded(const std::vector<sp<GraphicBuffer>>& buffers) {
81         mDiscardedBuffers.insert(mDiscardedBuffers.end(), buffers.begin(), buffers.end());
82     }
83 
getReleaseNotifyCount() const84     int getReleaseNotifyCount() const {
85         return mBuffersReleased;
86     }
getDiscardedBuffers() const87     const std::vector<sp<GraphicBuffer>>& getDiscardedBuffers() const {
88         return mDiscardedBuffers;
89     }
90 private:
91     // No need to use lock given the test triggers the listener in the same
92     // thread context.
93     bool mEnableReleaseCb;
94     int32_t mBuffersReleased;
95     std::vector<sp<GraphicBuffer>> mDiscardedBuffers;
96 };
97 
98 class SurfaceTest : public ::testing::Test {
99 protected:
SurfaceTest()100     SurfaceTest() {
101         ProcessState::self()->startThreadPool();
102     }
103 
SetUp()104     virtual void SetUp() {
105         mComposerClient = new SurfaceComposerClient;
106         ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
107 
108         // TODO(brianderson): The following sometimes fails and is a source of
109         //   test flakiness.
110         mSurfaceControl = mComposerClient->createSurface(
111                 String8("Test Surface"), 32, 32, PIXEL_FORMAT_RGBA_8888, 0);
112         SurfaceComposerClient::Transaction().apply(true);
113 
114         ASSERT_TRUE(mSurfaceControl != nullptr);
115         ASSERT_TRUE(mSurfaceControl->isValid());
116 
117         Transaction t;
118         ASSERT_EQ(NO_ERROR, t.setLayer(mSurfaceControl, 0x7fffffff).show(mSurfaceControl).apply());
119 
120         mSurface = mSurfaceControl->getSurface();
121         ASSERT_TRUE(mSurface != nullptr);
122     }
123 
TearDown()124     virtual void TearDown() {
125         mComposerClient->dispose();
126     }
127 
testSurfaceListener(bool hasSurfaceListener,bool enableReleasedCb,int32_t extraDiscardedBuffers)128     void testSurfaceListener(bool hasSurfaceListener, bool enableReleasedCb,
129             int32_t extraDiscardedBuffers) {
130         sp<IGraphicBufferProducer> producer;
131         sp<IGraphicBufferConsumer> consumer;
132         BufferQueue::createBufferQueue(&producer, &consumer);
133 
134         sp<MockConsumer> mockConsumer(new MockConsumer);
135         consumer->consumerConnect(mockConsumer, false);
136         consumer->setConsumerName(String8("TestConsumer"));
137 
138         sp<Surface> surface = new Surface(producer);
139         sp<ANativeWindow> window(surface);
140         sp<FakeSurfaceListener> listener;
141         if (hasSurfaceListener) {
142             listener = new FakeSurfaceListener(enableReleasedCb);
143         }
144         ASSERT_EQ(OK, surface->connect(
145                 NATIVE_WINDOW_API_CPU,
146                 /*reportBufferRemoval*/true,
147                 /*listener*/listener));
148         const int BUFFER_COUNT = 4 + extraDiscardedBuffers;
149         ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(window.get(), BUFFER_COUNT));
150 
151         ANativeWindowBuffer* buffers[BUFFER_COUNT];
152         // Dequeue first to allocate a number of buffers
153         for (int i = 0; i < BUFFER_COUNT; i++) {
154             ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(window.get(), &buffers[i]));
155         }
156         for (int i = 0; i < BUFFER_COUNT; i++) {
157             ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffers[i], -1));
158         }
159 
160         ANativeWindowBuffer* buffer;
161         // Fill BUFFER_COUNT-1 buffers
162         for (int i = 0; i < BUFFER_COUNT-1; i++) {
163             ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(window.get(), &buffer));
164             ASSERT_EQ(NO_ERROR, window->queueBuffer(window.get(), buffer, -1));
165         }
166 
167         // Dequeue 1 buffer
168         ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(window.get(), &buffer));
169 
170         // Acquire and free 1+extraDiscardedBuffers buffer, check onBufferReleased is called.
171         std::vector<BufferItem> releasedItems;
172         releasedItems.resize(1+extraDiscardedBuffers);
173         for (int i = 0; i < releasedItems.size(); i++) {
174             ASSERT_EQ(NO_ERROR, consumer->acquireBuffer(&releasedItems[i], 0));
175             ASSERT_EQ(NO_ERROR, consumer->releaseBuffer(releasedItems[i].mSlot,
176                     releasedItems[i].mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR,
177                     Fence::NO_FENCE));
178         }
179         int32_t expectedReleaseCb = (enableReleasedCb ? releasedItems.size() : 0);
180         if (hasSurfaceListener) {
181             ASSERT_EQ(expectedReleaseCb, listener->getReleaseNotifyCount());
182         }
183 
184         // Acquire 1 buffer, leaving 1+extraDiscardedBuffers filled buffer in queue
185         BufferItem item;
186         ASSERT_EQ(NO_ERROR, consumer->acquireBuffer(&item, 0));
187 
188         // Discard free buffers
189         ASSERT_EQ(NO_ERROR, consumer->discardFreeBuffers());
190 
191         if (hasSurfaceListener) {
192             ASSERT_EQ(expectedReleaseCb, listener->getReleaseNotifyCount());
193 
194             // Check onBufferDiscarded is called with correct buffer
195             auto discardedBuffers = listener->getDiscardedBuffers();
196             ASSERT_EQ(discardedBuffers.size(), releasedItems.size());
197             for (int i = 0; i < releasedItems.size(); i++) {
198                 ASSERT_EQ(discardedBuffers[i], releasedItems[i].mGraphicBuffer);
199             }
200 
201             ASSERT_EQ(expectedReleaseCb, listener->getReleaseNotifyCount());
202         }
203 
204         // Disconnect the surface
205         ASSERT_EQ(NO_ERROR, surface->disconnect(NATIVE_WINDOW_API_CPU));
206     }
207 
captureDisplay(DisplayCaptureArgs & captureArgs,ScreenCaptureResults & captureResults)208     static status_t captureDisplay(DisplayCaptureArgs& captureArgs,
209                                    ScreenCaptureResults& captureResults) {
210         const auto sf = ComposerServiceAIDL::getComposerService();
211         SurfaceComposerClient::Transaction().apply(true);
212 
213         const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
214         binder::Status status = sf->captureDisplay(captureArgs, captureListener);
215         if (status.transactionError() != NO_ERROR) {
216             return status.transactionError();
217         }
218         captureResults = captureListener->waitForResults();
219         return captureResults.result;
220     }
221 
222     sp<Surface> mSurface;
223     sp<SurfaceComposerClient> mComposerClient;
224     sp<SurfaceControl> mSurfaceControl;
225 };
226 
TEST_F(SurfaceTest,CreateSurfaceReturnsErrorBadClient)227 TEST_F(SurfaceTest, CreateSurfaceReturnsErrorBadClient) {
228     mComposerClient->dispose();
229     ASSERT_EQ(NO_INIT, mComposerClient->initCheck());
230 
231     sp<SurfaceControl> sc;
232     status_t err = mComposerClient->createSurfaceChecked(
233             String8("Test Surface"), 32, 32, PIXEL_FORMAT_RGBA_8888, &sc, 0);
234     ASSERT_EQ(NO_INIT, err);
235 }
236 
TEST_F(SurfaceTest,QueuesToWindowComposerIsTrueWhenVisible)237 TEST_F(SurfaceTest, QueuesToWindowComposerIsTrueWhenVisible) {
238     sp<ANativeWindow> anw(mSurface);
239     int result = -123;
240     int err = anw->query(anw.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER,
241             &result);
242     EXPECT_EQ(NO_ERROR, err);
243     EXPECT_EQ(1, result);
244 }
245 
TEST_F(SurfaceTest,QueuesToWindowComposerIsTrueWhenPurgatorized)246 TEST_F(SurfaceTest, QueuesToWindowComposerIsTrueWhenPurgatorized) {
247     mSurfaceControl.clear();
248     // Wait for the async clean-up to complete.
249     std::this_thread::sleep_for(50ms);
250 
251     sp<ANativeWindow> anw(mSurface);
252     int result = -123;
253     int err = anw->query(anw.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER,
254             &result);
255     EXPECT_EQ(NO_ERROR, err);
256     EXPECT_EQ(1, result);
257 }
258 
259 // This test probably doesn't belong here.
TEST_F(SurfaceTest,ScreenshotsOfProtectedBuffersDontSucceed)260 TEST_F(SurfaceTest, ScreenshotsOfProtectedBuffersDontSucceed) {
261     sp<ANativeWindow> anw(mSurface);
262 
263     // Verify the screenshot works with no protected buffers.
264     const sp<IBinder> display = ComposerServiceAIDL::getInstance().getInternalDisplayToken();
265     ASSERT_FALSE(display == nullptr);
266 
267     DisplayCaptureArgs captureArgs;
268     captureArgs.displayToken = display;
269     captureArgs.width = 64;
270     captureArgs.height = 64;
271 
272     ScreenCaptureResults captureResults;
273     ASSERT_EQ(NO_ERROR, captureDisplay(captureArgs, captureResults));
274 
275     ASSERT_EQ(NO_ERROR, native_window_api_connect(anw.get(),
276             NATIVE_WINDOW_API_CPU));
277     // Set the PROTECTED usage bit and verify that the screenshot fails.  Note
278     // that we need to dequeue a buffer in order for it to actually get
279     // allocated in SurfaceFlinger.
280     ASSERT_EQ(NO_ERROR, native_window_set_usage(anw.get(),
281             GRALLOC_USAGE_PROTECTED));
282     ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(anw.get(), 3));
283     ANativeWindowBuffer* buf = nullptr;
284 
285     status_t err = native_window_dequeue_buffer_and_wait(anw.get(), &buf);
286     if (err) {
287         // we could fail if GRALLOC_USAGE_PROTECTED is not supported.
288         // that's okay as long as this is the reason for the failure.
289         // try again without the GRALLOC_USAGE_PROTECTED bit.
290         ASSERT_EQ(NO_ERROR, native_window_set_usage(anw.get(), 0));
291         ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(anw.get(),
292                 &buf));
293         return;
294     }
295     ASSERT_EQ(NO_ERROR, anw->cancelBuffer(anw.get(), buf, -1));
296 
297     for (int i = 0; i < 4; i++) {
298         // Loop to make sure SurfaceFlinger has retired a protected buffer.
299         ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(anw.get(),
300                 &buf));
301         ASSERT_EQ(NO_ERROR, anw->queueBuffer(anw.get(), buf, -1));
302     }
303     ASSERT_EQ(NO_ERROR, captureDisplay(captureArgs, captureResults));
304 }
305 
TEST_F(SurfaceTest,ConcreteTypeIsSurface)306 TEST_F(SurfaceTest, ConcreteTypeIsSurface) {
307     sp<ANativeWindow> anw(mSurface);
308     int result = -123;
309     int err = anw->query(anw.get(), NATIVE_WINDOW_CONCRETE_TYPE, &result);
310     EXPECT_EQ(NO_ERROR, err);
311     EXPECT_EQ(NATIVE_WINDOW_SURFACE, result);
312 }
313 
TEST_F(SurfaceTest,LayerCountIsOne)314 TEST_F(SurfaceTest, LayerCountIsOne) {
315     sp<ANativeWindow> anw(mSurface);
316     int result = -123;
317     int err = anw->query(anw.get(), NATIVE_WINDOW_LAYER_COUNT, &result);
318     EXPECT_EQ(NO_ERROR, err);
319     EXPECT_EQ(1, result);
320 }
321 
TEST_F(SurfaceTest,QueryConsumerUsage)322 TEST_F(SurfaceTest, QueryConsumerUsage) {
323     const int TEST_USAGE_FLAGS =
324             GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
325     sp<IGraphicBufferProducer> producer;
326     sp<IGraphicBufferConsumer> consumer;
327     BufferQueue::createBufferQueue(&producer, &consumer);
328     sp<BufferItemConsumer> c = new BufferItemConsumer(consumer,
329             TEST_USAGE_FLAGS);
330     sp<Surface> s = new Surface(producer);
331 
332     sp<ANativeWindow> anw(s);
333 
334     int flags = -1;
335     int err = anw->query(anw.get(), NATIVE_WINDOW_CONSUMER_USAGE_BITS, &flags);
336 
337     ASSERT_EQ(NO_ERROR, err);
338     ASSERT_EQ(TEST_USAGE_FLAGS, flags);
339 }
340 
TEST_F(SurfaceTest,QueryDefaultBuffersDataSpace)341 TEST_F(SurfaceTest, QueryDefaultBuffersDataSpace) {
342     const android_dataspace TEST_DATASPACE = HAL_DATASPACE_V0_SRGB;
343     sp<IGraphicBufferProducer> producer;
344     sp<IGraphicBufferConsumer> consumer;
345     BufferQueue::createBufferQueue(&producer, &consumer);
346     sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
347 
348     cpuConsumer->setDefaultBufferDataSpace(TEST_DATASPACE);
349 
350     sp<Surface> s = new Surface(producer);
351 
352     sp<ANativeWindow> anw(s);
353 
354     android_dataspace dataSpace;
355 
356     int err = anw->query(anw.get(), NATIVE_WINDOW_DEFAULT_DATASPACE,
357             reinterpret_cast<int*>(&dataSpace));
358 
359     ASSERT_EQ(NO_ERROR, err);
360     ASSERT_EQ(TEST_DATASPACE, dataSpace);
361 }
362 
TEST_F(SurfaceTest,SettingGenerationNumber)363 TEST_F(SurfaceTest, SettingGenerationNumber) {
364     sp<IGraphicBufferProducer> producer;
365     sp<IGraphicBufferConsumer> consumer;
366     BufferQueue::createBufferQueue(&producer, &consumer);
367     sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
368     sp<Surface> surface = new Surface(producer);
369     sp<ANativeWindow> window(surface);
370 
371     // Allocate a buffer with a generation number of 0
372     ANativeWindowBuffer* buffer;
373     int fenceFd;
374     ASSERT_EQ(NO_ERROR, native_window_api_connect(window.get(),
375             NATIVE_WINDOW_API_CPU));
376     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fenceFd));
377     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fenceFd));
378 
379     // Detach the buffer and check its generation number
380     sp<GraphicBuffer> graphicBuffer;
381     sp<Fence> fence;
382     ASSERT_EQ(NO_ERROR, surface->detachNextBuffer(&graphicBuffer, &fence));
383     ASSERT_EQ(0U, graphicBuffer->getGenerationNumber());
384 
385     ASSERT_EQ(NO_ERROR, surface->setGenerationNumber(1));
386     buffer = static_cast<ANativeWindowBuffer*>(graphicBuffer.get());
387 
388     // This should change the generation number of the GraphicBuffer
389     ASSERT_EQ(NO_ERROR, surface->attachBuffer(buffer));
390 
391     // Check that the new generation number sticks with the buffer
392     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, -1));
393     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fenceFd));
394     graphicBuffer = static_cast<GraphicBuffer*>(buffer);
395     ASSERT_EQ(1U, graphicBuffer->getGenerationNumber());
396 }
397 
TEST_F(SurfaceTest,GetConsumerName)398 TEST_F(SurfaceTest, GetConsumerName) {
399     sp<IGraphicBufferProducer> producer;
400     sp<IGraphicBufferConsumer> consumer;
401     BufferQueue::createBufferQueue(&producer, &consumer);
402 
403     sp<MockConsumer> mockConsumer(new MockConsumer);
404     consumer->consumerConnect(mockConsumer, false);
405     consumer->setConsumerName(String8("TestConsumer"));
406 
407     sp<Surface> surface = new Surface(producer);
408     sp<ANativeWindow> window(surface);
409     native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU);
410 
411     EXPECT_STREQ("TestConsumer", surface->getConsumerName().string());
412 }
413 
TEST_F(SurfaceTest,GetWideColorSupport)414 TEST_F(SurfaceTest, GetWideColorSupport) {
415     sp<IGraphicBufferProducer> producer;
416     sp<IGraphicBufferConsumer> consumer;
417     BufferQueue::createBufferQueue(&producer, &consumer);
418 
419     sp<MockConsumer> mockConsumer(new MockConsumer);
420     consumer->consumerConnect(mockConsumer, false);
421     consumer->setConsumerName(String8("TestConsumer"));
422 
423     sp<Surface> surface = new Surface(producer);
424     sp<ANativeWindow> window(surface);
425     native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU);
426 
427     bool supported;
428     surface->getWideColorSupport(&supported);
429 
430     // NOTE: This test assumes that device that supports
431     // wide-color (as indicated by BoardConfig) must also
432     // have a wide-color primary display.
433     // That assumption allows this test to cover devices
434     // that advertised a wide-color color mode without
435     // actually supporting wide-color to pass this test
436     // as well as the case of a device that does support
437     // wide-color (via BoardConfig) and has a wide-color
438     // primary display.
439     // NOT covered at this time is a device that supports
440     // wide color in the BoardConfig but does not support
441     // a wide-color color mode on the primary display.
442     ASSERT_EQ(hasWideColorDisplay, supported);
443 }
444 
TEST_F(SurfaceTest,GetHdrSupport)445 TEST_F(SurfaceTest, GetHdrSupport) {
446     sp<IGraphicBufferProducer> producer;
447     sp<IGraphicBufferConsumer> consumer;
448     BufferQueue::createBufferQueue(&producer, &consumer);
449 
450     sp<MockConsumer> mockConsumer(new MockConsumer);
451     consumer->consumerConnect(mockConsumer, false);
452     consumer->setConsumerName(String8("TestConsumer"));
453 
454     sp<Surface> surface = new Surface(producer);
455     sp<ANativeWindow> window(surface);
456     native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU);
457 
458     bool supported;
459     status_t result = surface->getHdrSupport(&supported);
460     ASSERT_EQ(NO_ERROR, result);
461 
462     // NOTE: This is not a CTS test.
463     // This test verifies that when the BoardConfig TARGET_HAS_HDR_DISPLAY
464     // is TRUE, getHdrSupport is also true.
465     // TODO: Add check for an HDR color mode on the primary display.
466     ASSERT_EQ(hasHdrDisplay, supported);
467 }
468 
TEST_F(SurfaceTest,SetHdrMetadata)469 TEST_F(SurfaceTest, SetHdrMetadata) {
470     sp<IGraphicBufferProducer> producer;
471     sp<IGraphicBufferConsumer> consumer;
472     BufferQueue::createBufferQueue(&producer, &consumer);
473 
474     sp<MockConsumer> mockConsumer(new MockConsumer);
475     consumer->consumerConnect(mockConsumer, false);
476     consumer->setConsumerName(String8("TestConsumer"));
477 
478     sp<Surface> surface = new Surface(producer);
479     sp<ANativeWindow> window(surface);
480     native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU);
481 
482     bool supported;
483     status_t result = surface->getHdrSupport(&supported);
484     ASSERT_EQ(NO_ERROR, result);
485 
486     if (!hasHdrDisplay || !supported) {
487         return;
488     }
489     const android_smpte2086_metadata smpte2086 = {
490         {0.680, 0.320},
491         {0.265, 0.690},
492         {0.150, 0.060},
493         {0.3127, 0.3290},
494         100.0,
495         0.1,
496     };
497     const android_cta861_3_metadata cta861_3 = {
498         78.0,
499         62.0,
500     };
501 
502     std::vector<uint8_t> hdr10plus;
503     hdr10plus.push_back(0xff);
504 
505     int error = native_window_set_buffers_smpte2086_metadata(window.get(), &smpte2086);
506     ASSERT_EQ(error, NO_ERROR);
507     error = native_window_set_buffers_cta861_3_metadata(window.get(), &cta861_3);
508     ASSERT_EQ(error, NO_ERROR);
509     error = native_window_set_buffers_hdr10_plus_metadata(window.get(), hdr10plus.size(),
510                                                           hdr10plus.data());
511     ASSERT_EQ(error, NO_ERROR);
512 }
513 
TEST_F(SurfaceTest,DynamicSetBufferCount)514 TEST_F(SurfaceTest, DynamicSetBufferCount) {
515     sp<IGraphicBufferProducer> producer;
516     sp<IGraphicBufferConsumer> consumer;
517     BufferQueue::createBufferQueue(&producer, &consumer);
518 
519     sp<MockConsumer> mockConsumer(new MockConsumer);
520     consumer->consumerConnect(mockConsumer, false);
521     consumer->setConsumerName(String8("TestConsumer"));
522 
523     sp<Surface> surface = new Surface(producer);
524     sp<ANativeWindow> window(surface);
525 
526     ASSERT_EQ(NO_ERROR, native_window_api_connect(window.get(),
527             NATIVE_WINDOW_API_CPU));
528     native_window_set_buffer_count(window.get(), 4);
529 
530     int fence;
531     ANativeWindowBuffer* buffer;
532     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
533     native_window_set_buffer_count(window.get(), 3);
534     ASSERT_EQ(NO_ERROR, window->queueBuffer(window.get(), buffer, fence));
535     native_window_set_buffer_count(window.get(), 2);
536     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
537     ASSERT_EQ(NO_ERROR, window->queueBuffer(window.get(), buffer, fence));
538 }
539 
TEST_F(SurfaceTest,GetAndFlushRemovedBuffers)540 TEST_F(SurfaceTest, GetAndFlushRemovedBuffers) {
541     sp<IGraphicBufferProducer> producer;
542     sp<IGraphicBufferConsumer> consumer;
543     BufferQueue::createBufferQueue(&producer, &consumer);
544 
545     sp<MockConsumer> mockConsumer(new MockConsumer);
546     consumer->consumerConnect(mockConsumer, false);
547     consumer->setConsumerName(String8("TestConsumer"));
548 
549     sp<Surface> surface = new Surface(producer);
550     sp<ANativeWindow> window(surface);
551     sp<StubProducerListener> listener = new StubProducerListener();
552     ASSERT_EQ(OK, surface->connect(
553             NATIVE_WINDOW_API_CPU,
554             /*listener*/listener,
555             /*reportBufferRemoval*/true));
556     const int BUFFER_COUNT = 4;
557     ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(window.get(), BUFFER_COUNT));
558 
559     sp<GraphicBuffer> detachedBuffer;
560     sp<Fence> outFence;
561     int fences[BUFFER_COUNT];
562     ANativeWindowBuffer* buffers[BUFFER_COUNT];
563     // Allocate buffers because detachNextBuffer requires allocated buffers
564     for (int i = 0; i < BUFFER_COUNT; i++) {
565         ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffers[i], &fences[i]));
566     }
567     for (int i = 0; i < BUFFER_COUNT; i++) {
568         ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffers[i], fences[i]));
569     }
570 
571     // Test detached buffer is correctly reported
572     ASSERT_EQ(NO_ERROR, surface->detachNextBuffer(&detachedBuffer, &outFence));
573     std::vector<sp<GraphicBuffer>> removedBuffers;
574     ASSERT_EQ(OK, surface->getAndFlushRemovedBuffers(&removedBuffers));
575     ASSERT_EQ(1u, removedBuffers.size());
576     ASSERT_EQ(detachedBuffer->handle, removedBuffers.at(0)->handle);
577     // Test the list is flushed one getAndFlushRemovedBuffers returns
578     ASSERT_EQ(OK, surface->getAndFlushRemovedBuffers(&removedBuffers));
579     ASSERT_EQ(0u, removedBuffers.size());
580 
581 
582     // Test removed buffer list is cleanup after next dequeueBuffer call
583     ASSERT_EQ(NO_ERROR, surface->detachNextBuffer(&detachedBuffer, &outFence));
584     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffers[0], &fences[0]));
585     ASSERT_EQ(OK, surface->getAndFlushRemovedBuffers(&removedBuffers));
586     ASSERT_EQ(0u, removedBuffers.size());
587     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffers[0], fences[0]));
588 
589     // Test removed buffer list is cleanup after next detachNextBuffer call
590     ASSERT_EQ(NO_ERROR, surface->detachNextBuffer(&detachedBuffer, &outFence));
591     ASSERT_EQ(NO_ERROR, surface->detachNextBuffer(&detachedBuffer, &outFence));
592     ASSERT_EQ(OK, surface->getAndFlushRemovedBuffers(&removedBuffers));
593     ASSERT_EQ(1u, removedBuffers.size());
594     ASSERT_EQ(detachedBuffer->handle, removedBuffers.at(0)->handle);
595 
596     // Re-allocate buffers since all buffers are detached up to now
597     for (int i = 0; i < BUFFER_COUNT; i++) {
598         ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffers[i], &fences[i]));
599     }
600     for (int i = 0; i < BUFFER_COUNT; i++) {
601         ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffers[i], fences[i]));
602     }
603 
604     ASSERT_EQ(NO_ERROR, surface->detachNextBuffer(&detachedBuffer, &outFence));
605     ASSERT_EQ(NO_ERROR, surface->attachBuffer(detachedBuffer.get()));
606     ASSERT_EQ(OK, surface->getAndFlushRemovedBuffers(&removedBuffers));
607     // Depends on which slot GraphicBufferProducer impl pick, the attach call might
608     // get 0 or 1 buffer removed.
609     ASSERT_LE(removedBuffers.size(), 1u);
610 }
611 
TEST_F(SurfaceTest,SurfaceListenerTest)612 TEST_F(SurfaceTest, SurfaceListenerTest) {
613     // Test discarding 1 free buffers with no listener
614     testSurfaceListener(/*hasListener*/false, /*enableReleaseCb*/false, /*extraDiscardedBuffers*/0);
615     // Test discarding 2 free buffers with no listener
616     testSurfaceListener(/*hasListener*/false, /*enableReleaseCb*/false, /*extraDiscardedBuffers*/1);
617     // Test discarding 1 free buffers with a listener, disabling onBufferReleased
618     testSurfaceListener(/*hasListener*/true, /*enableReleasedCb*/false, /*extraDiscardedBuffers*/0);
619     // Test discarding 2 free buffers with a listener, disabling onBufferReleased
620     testSurfaceListener(/*hasListener*/true, /*enableReleasedCb*/false, /*extraDiscardedBuffers*/1);
621     // Test discarding 1 free buffers with a listener, enabling onBufferReleased
622     testSurfaceListener(/*hasListener*/true, /*enableReleasedCb*/true, /*extraDiscardedBuffers*/0);
623     // Test discarding 3 free buffers with a listener, enabling onBufferReleased
624     testSurfaceListener(/*hasListener*/true, /*enableReleasedCb*/true, /*extraDiscardedBuffers*/2);
625 }
626 
TEST_F(SurfaceTest,TestGetLastDequeueStartTime)627 TEST_F(SurfaceTest, TestGetLastDequeueStartTime) {
628     sp<ANativeWindow> anw(mSurface);
629     ASSERT_EQ(NO_ERROR, native_window_api_connect(anw.get(), NATIVE_WINDOW_API_CPU));
630 
631     ANativeWindowBuffer* buffer = nullptr;
632     int32_t fenceFd = -1;
633 
634     nsecs_t before = systemTime(CLOCK_MONOTONIC);
635     anw->dequeueBuffer(anw.get(), &buffer, &fenceFd);
636     nsecs_t after = systemTime(CLOCK_MONOTONIC);
637 
638     nsecs_t lastDequeueTime = ANativeWindow_getLastDequeueStartTime(anw.get());
639     ASSERT_LE(before, lastDequeueTime);
640     ASSERT_GE(after, lastDequeueTime);
641 }
642 
643 class FakeConsumer : public BnConsumerListener {
644 public:
onFrameAvailable(const BufferItem &)645     void onFrameAvailable(const BufferItem& /*item*/) override {}
onBuffersReleased()646     void onBuffersReleased() override {}
onSidebandStreamChanged()647     void onSidebandStreamChanged() override {}
648 
addAndGetFrameTimestamps(const NewFrameEventsEntry * newTimestamps,FrameEventHistoryDelta * outDelta)649     void addAndGetFrameTimestamps(
650             const NewFrameEventsEntry* newTimestamps,
651             FrameEventHistoryDelta* outDelta) override {
652         if (newTimestamps) {
653             if (mGetFrameTimestampsEnabled) {
654                 EXPECT_GT(mNewFrameEntryOverride.frameNumber, 0u) <<
655                         "Test should set mNewFrameEntryOverride before queuing "
656                         "a frame.";
657                 EXPECT_EQ(newTimestamps->frameNumber,
658                         mNewFrameEntryOverride.frameNumber) <<
659                         "Test attempting to add NewFrameEntryOverride with "
660                         "incorrect frame number.";
661                 mFrameEventHistory.addQueue(mNewFrameEntryOverride);
662                 mNewFrameEntryOverride.frameNumber = 0;
663             }
664             mAddFrameTimestampsCount++;
665             mLastAddedFrameNumber = newTimestamps->frameNumber;
666         }
667         if (outDelta) {
668             mFrameEventHistory.getAndResetDelta(outDelta);
669             mGetFrameTimestampsCount++;
670         }
671         mAddAndGetFrameTimestampsCallCount++;
672     }
673 
674     bool mGetFrameTimestampsEnabled = false;
675 
676     ConsumerFrameEventHistory mFrameEventHistory;
677     int mAddAndGetFrameTimestampsCallCount = 0;
678     int mAddFrameTimestampsCount = 0;
679     int mGetFrameTimestampsCount = 0;
680     uint64_t mLastAddedFrameNumber = NO_FRAME_INDEX;
681 
682     NewFrameEventsEntry mNewFrameEntryOverride = { 0, 0, 0, nullptr };
683 };
684 
685 class FakeSurfaceComposer : public ISurfaceComposer {
686 public:
~FakeSurfaceComposer()687     ~FakeSurfaceComposer() override {}
688 
setSupportsPresent(bool supportsPresent)689     void setSupportsPresent(bool supportsPresent) {
690         mSupportsPresent = supportsPresent;
691     }
692 
createConnection()693     sp<ISurfaceComposerClient> createConnection() override { return nullptr; }
createDisplayEventConnection(ISurfaceComposer::VsyncSource,ISurfaceComposer::EventRegistrationFlags)694     sp<IDisplayEventConnection> createDisplayEventConnection(
695             ISurfaceComposer::VsyncSource, ISurfaceComposer::EventRegistrationFlags) override {
696         return nullptr;
697     }
setTransactionState(const FrameTimelineInfo &,const Vector<ComposerState> &,const Vector<DisplayState> &,uint32_t,const sp<IBinder> &,const InputWindowCommands &,int64_t,bool,const client_cache_t &,bool,const std::vector<ListenerCallbacks> &,uint64_t)698     status_t setTransactionState(const FrameTimelineInfo& /*frameTimelineInfo*/,
699                                  const Vector<ComposerState>& /*state*/,
700                                  const Vector<DisplayState>& /*displays*/, uint32_t /*flags*/,
701                                  const sp<IBinder>& /*applyToken*/,
702                                  const InputWindowCommands& /*inputWindowCommands*/,
703                                  int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/,
704                                  const client_cache_t& /*cachedBuffer*/,
705                                  bool /*hasListenerCallbacks*/,
706                                  const std::vector<ListenerCallbacks>& /*listenerCallbacks*/,
707                                  uint64_t /*transactionId*/) override {
708         return NO_ERROR;
709     }
710 
bootFinished()711     void bootFinished() override {}
authenticateSurfaceTexture(const sp<IGraphicBufferProducer> &) const712     bool authenticateSurfaceTexture(
713             const sp<IGraphicBufferProducer>& /*surface*/) const override {
714         return false;
715     }
716 
getSupportedFrameTimestamps(std::vector<FrameEvent> * outSupported) const717     status_t getSupportedFrameTimestamps(std::vector<FrameEvent>* outSupported)
718             const override {
719         *outSupported = {
720                 FrameEvent::REQUESTED_PRESENT,
721                 FrameEvent::ACQUIRE,
722                 FrameEvent::LATCH,
723                 FrameEvent::FIRST_REFRESH_START,
724                 FrameEvent::LAST_REFRESH_START,
725                 FrameEvent::GPU_COMPOSITION_DONE,
726                 FrameEvent::DEQUEUE_READY,
727                 FrameEvent::RELEASE
728         };
729         if (mSupportsPresent) {
730             outSupported->push_back(
731                         FrameEvent::DISPLAY_PRESENT);
732         }
733         return NO_ERROR;
734     }
735 
getStaticDisplayInfo(const sp<IBinder> &,ui::StaticDisplayInfo *)736     status_t getStaticDisplayInfo(const sp<IBinder>& /*display*/, ui::StaticDisplayInfo*) override {
737         return NO_ERROR;
738     }
getDynamicDisplayInfo(const sp<IBinder> &,ui::DynamicDisplayInfo *)739     status_t getDynamicDisplayInfo(const sp<IBinder>& /*display*/,
740                                    ui::DynamicDisplayInfo*) override {
741         return NO_ERROR;
742     }
getDisplayNativePrimaries(const sp<IBinder> &,ui::DisplayPrimaries &)743     status_t getDisplayNativePrimaries(const sp<IBinder>& /*display*/,
744             ui::DisplayPrimaries& /*primaries*/) override {
745         return NO_ERROR;
746     }
setActiveColorMode(const sp<IBinder> &,ColorMode)747     status_t setActiveColorMode(const sp<IBinder>& /*display*/, ColorMode /*colorMode*/) override {
748         return NO_ERROR;
749     }
setBootDisplayMode(const sp<IBinder> &,ui::DisplayModeId)750     status_t setBootDisplayMode(const sp<IBinder>& /*display*/, ui::DisplayModeId /*id*/) override {
751         return NO_ERROR;
752     }
753 
clearAnimationFrameStats()754     status_t clearAnimationFrameStats() override { return NO_ERROR; }
getAnimationFrameStats(FrameStats *) const755     status_t getAnimationFrameStats(FrameStats* /*outStats*/) const override {
756         return NO_ERROR;
757     }
overrideHdrTypes(const sp<IBinder> &,const std::vector<ui::Hdr> &)758     status_t overrideHdrTypes(const sp<IBinder>& /*display*/,
759                               const std::vector<ui::Hdr>& /*hdrTypes*/) override {
760         return NO_ERROR;
761     }
onPullAtom(const int32_t,std::string *,bool *)762     status_t onPullAtom(const int32_t /*atomId*/, std::string* /*outData*/,
763                         bool* /*success*/) override {
764         return NO_ERROR;
765     }
enableVSyncInjections(bool)766     status_t enableVSyncInjections(bool /*enable*/) override {
767         return NO_ERROR;
768     }
injectVSync(nsecs_t)769     status_t injectVSync(nsecs_t /*when*/) override { return NO_ERROR; }
getLayerDebugInfo(std::vector<LayerDebugInfo> *)770     status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* /*layers*/) override {
771         return NO_ERROR;
772     }
getCompositionPreference(ui::Dataspace *,ui::PixelFormat *,ui::Dataspace *,ui::PixelFormat *) const773     status_t getCompositionPreference(
774             ui::Dataspace* /*outDefaultDataspace*/, ui::PixelFormat* /*outDefaultPixelFormat*/,
775             ui::Dataspace* /*outWideColorGamutDataspace*/,
776             ui::PixelFormat* /*outWideColorGamutPixelFormat*/) const override {
777         return NO_ERROR;
778     }
getDisplayedContentSamplingAttributes(const sp<IBinder> &,ui::PixelFormat *,ui::Dataspace *,uint8_t *) const779     status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& /*display*/,
780                                                    ui::PixelFormat* /*outFormat*/,
781                                                    ui::Dataspace* /*outDataspace*/,
782                                                    uint8_t* /*outComponentMask*/) const override {
783         return NO_ERROR;
784     }
setDisplayContentSamplingEnabled(const sp<IBinder> &,bool,uint8_t,uint64_t)785     status_t setDisplayContentSamplingEnabled(const sp<IBinder>& /*display*/, bool /*enable*/,
786                                               uint8_t /*componentMask*/,
787                                               uint64_t /*maxFrames*/) override {
788         return NO_ERROR;
789     }
getDisplayedContentSample(const sp<IBinder> &,uint64_t,uint64_t,DisplayedFrameStats *) const790     status_t getDisplayedContentSample(const sp<IBinder>& /*display*/, uint64_t /*maxFrames*/,
791                                        uint64_t /*timestamp*/,
792                                        DisplayedFrameStats* /*outStats*/) const override {
793         return NO_ERROR;
794     }
795 
getColorManagement(bool *) const796     status_t getColorManagement(bool* /*outGetColorManagement*/) const override { return NO_ERROR; }
getProtectedContentSupport(bool *) const797     status_t getProtectedContentSupport(bool* /*outSupported*/) const override { return NO_ERROR; }
798 
addRegionSamplingListener(const Rect &,const sp<IBinder> &,const sp<IRegionSamplingListener> &)799     status_t addRegionSamplingListener(const Rect& /*samplingArea*/,
800                                        const sp<IBinder>& /*stopLayerHandle*/,
801                                        const sp<IRegionSamplingListener>& /*listener*/) override {
802         return NO_ERROR;
803     }
removeRegionSamplingListener(const sp<IRegionSamplingListener> &)804     status_t removeRegionSamplingListener(
805             const sp<IRegionSamplingListener>& /*listener*/) override {
806         return NO_ERROR;
807     }
addFpsListener(int32_t,const sp<gui::IFpsListener> &)808     status_t addFpsListener(int32_t /*taskId*/, const sp<gui::IFpsListener>& /*listener*/) {
809         return NO_ERROR;
810     }
removeFpsListener(const sp<gui::IFpsListener> &)811     status_t removeFpsListener(const sp<gui::IFpsListener>& /*listener*/) { return NO_ERROR; }
812 
addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> &)813     status_t addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener>& /*listener*/) {
814         return NO_ERROR;
815     }
816 
removeTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> &)817     status_t removeTunnelModeEnabledListener(
818             const sp<gui::ITunnelModeEnabledListener>& /*listener*/) {
819         return NO_ERROR;
820     }
821 
setDesiredDisplayModeSpecs(const sp<IBinder> &,ui::DisplayModeId,bool,float,float,float,float)822     status_t setDesiredDisplayModeSpecs(const sp<IBinder>& /*displayToken*/,
823                                         ui::DisplayModeId /*defaultMode*/,
824                                         bool /*allowGroupSwitching*/,
825                                         float /*primaryRefreshRateMin*/,
826                                         float /*primaryRefreshRateMax*/,
827                                         float /*appRequestRefreshRateMin*/,
828                                         float /*appRequestRefreshRateMax*/) {
829         return NO_ERROR;
830     }
getDesiredDisplayModeSpecs(const sp<IBinder> &,ui::DisplayModeId *,bool *,float *,float *,float *,float *)831     status_t getDesiredDisplayModeSpecs(const sp<IBinder>& /*displayToken*/,
832                                         ui::DisplayModeId* /*outDefaultMode*/,
833                                         bool* /*outAllowGroupSwitching*/,
834                                         float* /*outPrimaryRefreshRateMin*/,
835                                         float* /*outPrimaryRefreshRateMax*/,
836                                         float* /*outAppRequestRefreshRateMin*/,
837                                         float* /*outAppRequestRefreshRateMax*/) override {
838         return NO_ERROR;
839     };
840 
setGlobalShadowSettings(const half4 &,const half4 &,float,float,float)841     status_t setGlobalShadowSettings(const half4& /*ambientColor*/, const half4& /*spotColor*/,
842                                      float /*lightPosY*/, float /*lightPosZ*/,
843                                      float /*lightRadius*/) override {
844         return NO_ERROR;
845     }
846 
getDisplayDecorationSupport(const sp<IBinder> &,std::optional<DisplayDecorationSupport> *) const847     status_t getDisplayDecorationSupport(
848             const sp<IBinder>& /*displayToken*/,
849             std::optional<DisplayDecorationSupport>* /*outSupport*/) const override {
850         return NO_ERROR;
851     }
852 
setFrameRate(const sp<IGraphicBufferProducer> &,float,int8_t,int8_t)853     status_t setFrameRate(const sp<IGraphicBufferProducer>& /*surface*/, float /*frameRate*/,
854                           int8_t /*compatibility*/, int8_t /*changeFrameRateStrategy*/) override {
855         return NO_ERROR;
856     }
857 
setFrameTimelineInfo(const sp<IGraphicBufferProducer> &,const FrameTimelineInfo &)858     status_t setFrameTimelineInfo(const sp<IGraphicBufferProducer>& /*surface*/,
859                                   const FrameTimelineInfo& /*frameTimelineInfo*/) override {
860         return NO_ERROR;
861     }
862 
addTransactionTraceListener(const sp<gui::ITransactionTraceListener> &)863     status_t addTransactionTraceListener(
864             const sp<gui::ITransactionTraceListener>& /*listener*/) override {
865         return NO_ERROR;
866     }
867 
getGPUContextPriority()868     int getGPUContextPriority() override { return 0; };
869 
getMaxAcquiredBufferCount(int *) const870     status_t getMaxAcquiredBufferCount(int* /*buffers*/) const override { return NO_ERROR; }
871 
addWindowInfosListener(const sp<gui::IWindowInfosListener> &) const872     status_t addWindowInfosListener(
873             const sp<gui::IWindowInfosListener>& /*windowInfosListener*/) const override {
874         return NO_ERROR;
875     }
876 
removeWindowInfosListener(const sp<gui::IWindowInfosListener> &) const877     status_t removeWindowInfosListener(
878             const sp<gui::IWindowInfosListener>& /*windowInfosListener*/) const override {
879         return NO_ERROR;
880     }
881 
setOverrideFrameRate(uid_t,float)882     status_t setOverrideFrameRate(uid_t /*uid*/, float /*frameRate*/) override { return NO_ERROR; }
883 
884 protected:
onAsBinder()885     IBinder* onAsBinder() override { return nullptr; }
886 
887 private:
888     bool mSupportsPresent{true};
889 };
890 
891 class FakeSurfaceComposerAIDL : public gui::ISurfaceComposer {
892 public:
~FakeSurfaceComposerAIDL()893     ~FakeSurfaceComposerAIDL() override {}
894 
setSupportsPresent(bool supportsPresent)895     void setSupportsPresent(bool supportsPresent) { mSupportsPresent = supportsPresent; }
896 
createDisplay(const std::string &,bool,sp<IBinder> *)897     binder::Status createDisplay(const std::string& /*displayName*/, bool /*secure*/,
898                                  sp<IBinder>* /*outDisplay*/) override {
899         return binder::Status::ok();
900     }
901 
destroyDisplay(const sp<IBinder> &)902     binder::Status destroyDisplay(const sp<IBinder>& /*display*/) override {
903         return binder::Status::ok();
904     }
905 
getPhysicalDisplayIds(std::vector<int64_t> *)906     binder::Status getPhysicalDisplayIds(std::vector<int64_t>* /*outDisplayIds*/) override {
907         return binder::Status::ok();
908     }
909 
getPrimaryPhysicalDisplayId(int64_t *)910     binder::Status getPrimaryPhysicalDisplayId(int64_t* /*outDisplayId*/) override {
911         return binder::Status::ok();
912     }
913 
getPhysicalDisplayToken(int64_t,sp<IBinder> *)914     binder::Status getPhysicalDisplayToken(int64_t /*displayId*/,
915                                            sp<IBinder>* /*outDisplay*/) override {
916         return binder::Status::ok();
917     }
918 
setPowerMode(const sp<IBinder> &,int)919     binder::Status setPowerMode(const sp<IBinder>& /*display*/, int /*mode*/) override {
920         return binder::Status::ok();
921     }
922 
getDisplayStats(const sp<IBinder> &,gui::DisplayStatInfo *)923     binder::Status getDisplayStats(const sp<IBinder>& /*display*/,
924                                    gui::DisplayStatInfo* /*outStatInfo*/) override {
925         return binder::Status::ok();
926     }
927 
getDisplayState(const sp<IBinder> &,gui::DisplayState *)928     binder::Status getDisplayState(const sp<IBinder>& /*display*/,
929                                    gui::DisplayState* /*outState*/) override {
930         return binder::Status::ok();
931     }
932 
clearBootDisplayMode(const sp<IBinder> &)933     binder::Status clearBootDisplayMode(const sp<IBinder>& /*display*/) override {
934         return binder::Status::ok();
935     }
936 
getBootDisplayModeSupport(bool *)937     binder::Status getBootDisplayModeSupport(bool* /*outMode*/) override {
938         return binder::Status::ok();
939     }
940 
setAutoLowLatencyMode(const sp<IBinder> &,bool)941     binder::Status setAutoLowLatencyMode(const sp<IBinder>& /*display*/, bool /*on*/) override {
942         return binder::Status::ok();
943     }
944 
setGameContentType(const sp<IBinder> &,bool)945     binder::Status setGameContentType(const sp<IBinder>& /*display*/, bool /*on*/) override {
946         return binder::Status::ok();
947     }
948 
captureDisplay(const DisplayCaptureArgs &,const sp<IScreenCaptureListener> &)949     binder::Status captureDisplay(const DisplayCaptureArgs&,
950                                   const sp<IScreenCaptureListener>&) override {
951         return binder::Status::ok();
952     }
953 
captureDisplayById(int64_t,const sp<IScreenCaptureListener> &)954     binder::Status captureDisplayById(int64_t, const sp<IScreenCaptureListener>&) override {
955         return binder::Status::ok();
956     }
957 
captureLayers(const LayerCaptureArgs &,const sp<IScreenCaptureListener> &)958     binder::Status captureLayers(const LayerCaptureArgs&,
959                                  const sp<IScreenCaptureListener>&) override {
960         return binder::Status::ok();
961     }
962 
isWideColorDisplay(const sp<IBinder> &,bool *)963     binder::Status isWideColorDisplay(const sp<IBinder>& /*token*/,
964                                       bool* /*outIsWideColorDisplay*/) override {
965         return binder::Status::ok();
966     }
967 
getDisplayBrightnessSupport(const sp<IBinder> &,bool *)968     binder::Status getDisplayBrightnessSupport(const sp<IBinder>& /*displayToken*/,
969                                                bool* /*outSupport*/) override {
970         return binder::Status::ok();
971     }
972 
setDisplayBrightness(const sp<IBinder> &,const gui::DisplayBrightness &)973     binder::Status setDisplayBrightness(const sp<IBinder>& /*displayToken*/,
974                                         const gui::DisplayBrightness& /*brightness*/) override {
975         return binder::Status::ok();
976     }
977 
addHdrLayerInfoListener(const sp<IBinder> &,const sp<gui::IHdrLayerInfoListener> &)978     binder::Status addHdrLayerInfoListener(
979             const sp<IBinder>& /*displayToken*/,
980             const sp<gui::IHdrLayerInfoListener>& /*listener*/) override {
981         return binder::Status::ok();
982     }
983 
removeHdrLayerInfoListener(const sp<IBinder> &,const sp<gui::IHdrLayerInfoListener> &)984     binder::Status removeHdrLayerInfoListener(
985             const sp<IBinder>& /*displayToken*/,
986             const sp<gui::IHdrLayerInfoListener>& /*listener*/) override {
987         return binder::Status::ok();
988     }
989 
notifyPowerBoost(int)990     binder::Status notifyPowerBoost(int /*boostId*/) override { return binder::Status::ok(); }
991 
992 protected:
onAsBinder()993     IBinder* onAsBinder() override { return nullptr; }
994 
995 private:
996     bool mSupportsPresent{true};
997 };
998 
999 class FakeProducerFrameEventHistory : public ProducerFrameEventHistory {
1000 public:
FakeProducerFrameEventHistory(FenceToFenceTimeMap * fenceMap)1001     explicit FakeProducerFrameEventHistory(FenceToFenceTimeMap* fenceMap) : mFenceMap(fenceMap) {}
1002 
~FakeProducerFrameEventHistory()1003     ~FakeProducerFrameEventHistory() {}
1004 
updateAcquireFence(uint64_t frameNumber,std::shared_ptr<FenceTime> && acquire)1005     void updateAcquireFence(uint64_t frameNumber,
1006             std::shared_ptr<FenceTime>&& acquire) override {
1007         // Verify the acquire fence being added isn't the one from the consumer.
1008         EXPECT_NE(mConsumerAcquireFence, acquire);
1009         // Override the fence, so we can verify this was called by the
1010         // producer after the frame is queued.
1011         ProducerFrameEventHistory::updateAcquireFence(frameNumber,
1012                 std::shared_ptr<FenceTime>(mAcquireFenceOverride));
1013     }
1014 
setAcquireFenceOverride(const std::shared_ptr<FenceTime> & acquireFenceOverride,const std::shared_ptr<FenceTime> & consumerAcquireFence)1015     void setAcquireFenceOverride(
1016             const std::shared_ptr<FenceTime>& acquireFenceOverride,
1017             const std::shared_ptr<FenceTime>& consumerAcquireFence) {
1018         mAcquireFenceOverride = acquireFenceOverride;
1019         mConsumerAcquireFence = consumerAcquireFence;
1020     }
1021 
1022 protected:
createFenceTime(const sp<Fence> & fence) const1023     std::shared_ptr<FenceTime> createFenceTime(const sp<Fence>& fence)
1024             const override {
1025         return mFenceMap->createFenceTimeForTest(fence);
1026     }
1027 
1028     FenceToFenceTimeMap* mFenceMap{nullptr};
1029 
1030     std::shared_ptr<FenceTime> mAcquireFenceOverride{FenceTime::NO_FENCE};
1031     std::shared_ptr<FenceTime> mConsumerAcquireFence{FenceTime::NO_FENCE};
1032 };
1033 
1034 
1035 class TestSurface : public Surface {
1036 public:
TestSurface(const sp<IGraphicBufferProducer> & bufferProducer,FenceToFenceTimeMap * fenceMap)1037     TestSurface(const sp<IGraphicBufferProducer>& bufferProducer,
1038             FenceToFenceTimeMap* fenceMap)
1039         : Surface(bufferProducer),
1040           mFakeSurfaceComposer(new FakeSurfaceComposer) {
1041         mFakeFrameEventHistory = new FakeProducerFrameEventHistory(fenceMap);
1042         mFrameEventHistory.reset(mFakeFrameEventHistory);
1043     }
1044 
~TestSurface()1045     ~TestSurface() override {}
1046 
composerService() const1047     sp<ISurfaceComposer> composerService() const override {
1048         return mFakeSurfaceComposer;
1049     }
1050 
now() const1051     nsecs_t now() const override {
1052         return mNow;
1053     }
1054 
setNow(nsecs_t now)1055     void setNow(nsecs_t now) {
1056         mNow = now;
1057     }
1058 
1059 public:
1060     sp<FakeSurfaceComposer> mFakeSurfaceComposer;
1061     nsecs_t mNow = 0;
1062 
1063     // mFrameEventHistory owns the instance of FakeProducerFrameEventHistory,
1064     // but this raw pointer gives access to test functionality.
1065     FakeProducerFrameEventHistory* mFakeFrameEventHistory;
1066 };
1067 
1068 
1069 class GetFrameTimestampsTest : public ::testing::Test {
1070 protected:
1071     struct FenceAndFenceTime {
FenceAndFenceTimeandroid::GetFrameTimestampsTest::FenceAndFenceTime1072         explicit FenceAndFenceTime(FenceToFenceTimeMap& fenceMap)
1073            : mFence(new Fence),
1074              mFenceTime(fenceMap.createFenceTimeForTest(mFence)) {}
1075         sp<Fence> mFence { nullptr };
1076         std::shared_ptr<FenceTime> mFenceTime { nullptr };
1077     };
1078 
1079     struct RefreshEvents {
RefreshEventsandroid::GetFrameTimestampsTest::RefreshEvents1080         RefreshEvents(FenceToFenceTimeMap& fenceMap, nsecs_t refreshStart)
1081           : mFenceMap(fenceMap),
1082             kCompositorTiming(
1083                 {refreshStart, refreshStart + 1, refreshStart + 2 }),
1084             kStartTime(refreshStart + 3),
1085             kGpuCompositionDoneTime(refreshStart + 4),
1086             kPresentTime(refreshStart + 5) {}
1087 
signalPostCompositeFencesandroid::GetFrameTimestampsTest::RefreshEvents1088         void signalPostCompositeFences() {
1089             mFenceMap.signalAllForTest(
1090                         mGpuCompositionDone.mFence, kGpuCompositionDoneTime);
1091             mFenceMap.signalAllForTest(mPresent.mFence, kPresentTime);
1092         }
1093 
1094         FenceToFenceTimeMap& mFenceMap;
1095 
1096         FenceAndFenceTime mGpuCompositionDone { mFenceMap };
1097         FenceAndFenceTime mPresent { mFenceMap };
1098 
1099         const CompositorTiming kCompositorTiming;
1100 
1101         const nsecs_t kStartTime;
1102         const nsecs_t kGpuCompositionDoneTime;
1103         const nsecs_t kPresentTime;
1104     };
1105 
1106     struct FrameEvents {
FrameEventsandroid::GetFrameTimestampsTest::FrameEvents1107         FrameEvents(FenceToFenceTimeMap& fenceMap, nsecs_t frameStartTime)
1108             : mFenceMap(fenceMap),
1109               kPostedTime(frameStartTime + 100),
1110               kRequestedPresentTime(frameStartTime + 200),
1111               kProducerAcquireTime(frameStartTime + 300),
1112               kConsumerAcquireTime(frameStartTime + 301),
1113               kLatchTime(frameStartTime + 500),
1114               kDequeueReadyTime(frameStartTime + 600),
1115               kReleaseTime(frameStartTime + 700),
1116               mRefreshes {
1117                     { mFenceMap, frameStartTime + 410 },
1118                     { mFenceMap, frameStartTime + 420 },
1119                     { mFenceMap, frameStartTime + 430 } } {}
1120 
signalQueueFencesandroid::GetFrameTimestampsTest::FrameEvents1121         void signalQueueFences() {
1122             mFenceMap.signalAllForTest(
1123                         mAcquireConsumer.mFence, kConsumerAcquireTime);
1124             mFenceMap.signalAllForTest(
1125                         mAcquireProducer.mFence, kProducerAcquireTime);
1126         }
1127 
signalRefreshFencesandroid::GetFrameTimestampsTest::FrameEvents1128         void signalRefreshFences() {
1129             for (auto& re : mRefreshes) {
1130                 re.signalPostCompositeFences();
1131             }
1132         }
1133 
signalReleaseFencesandroid::GetFrameTimestampsTest::FrameEvents1134         void signalReleaseFences() {
1135             mFenceMap.signalAllForTest(mRelease.mFence, kReleaseTime);
1136         }
1137 
1138         FenceToFenceTimeMap& mFenceMap;
1139 
1140         FenceAndFenceTime mAcquireConsumer { mFenceMap };
1141         FenceAndFenceTime mAcquireProducer { mFenceMap };
1142         FenceAndFenceTime mRelease { mFenceMap };
1143 
1144         const nsecs_t kPostedTime;
1145         const nsecs_t kRequestedPresentTime;
1146         const nsecs_t kProducerAcquireTime;
1147         const nsecs_t kConsumerAcquireTime;
1148         const nsecs_t kLatchTime;
1149         const nsecs_t kDequeueReadyTime;
1150         const nsecs_t kReleaseTime;
1151 
1152         RefreshEvents mRefreshes[3];
1153     };
1154 
GetFrameTimestampsTest()1155     GetFrameTimestampsTest() {}
1156 
SetUp()1157     virtual void SetUp() {
1158         BufferQueue::createBufferQueue(&mProducer, &mConsumer);
1159         mFakeConsumer = new FakeConsumer;
1160         mCfeh = &mFakeConsumer->mFrameEventHistory;
1161         mConsumer->consumerConnect(mFakeConsumer, false);
1162         mConsumer->setConsumerName(String8("TestConsumer"));
1163         mSurface = new TestSurface(mProducer, &mFenceMap);
1164         mWindow = mSurface;
1165 
1166         ASSERT_EQ(NO_ERROR, native_window_api_connect(mWindow.get(),
1167                 NATIVE_WINDOW_API_CPU));
1168         native_window_set_buffer_count(mWindow.get(), 4);
1169     }
1170 
disableFrameTimestamps()1171     void disableFrameTimestamps() {
1172         mFakeConsumer->mGetFrameTimestampsEnabled = false;
1173         native_window_enable_frame_timestamps(mWindow.get(), 0);
1174         mFrameTimestampsEnabled = false;
1175     }
1176 
enableFrameTimestamps()1177     void enableFrameTimestamps() {
1178         mFakeConsumer->mGetFrameTimestampsEnabled = true;
1179         native_window_enable_frame_timestamps(mWindow.get(), 1);
1180         mFrameTimestampsEnabled = true;
1181     }
1182 
getAllFrameTimestamps(uint64_t frameId)1183     int getAllFrameTimestamps(uint64_t frameId) {
1184         return native_window_get_frame_timestamps(mWindow.get(), frameId,
1185                 &outRequestedPresentTime, &outAcquireTime, &outLatchTime,
1186                 &outFirstRefreshStartTime, &outLastRefreshStartTime,
1187                 &outGpuCompositionDoneTime, &outDisplayPresentTime,
1188                 &outDequeueReadyTime, &outReleaseTime);
1189     }
1190 
resetTimestamps()1191     void resetTimestamps() {
1192         outRequestedPresentTime = -1;
1193         outAcquireTime = -1;
1194         outLatchTime = -1;
1195         outFirstRefreshStartTime = -1;
1196         outLastRefreshStartTime = -1;
1197         outGpuCompositionDoneTime = -1;
1198         outDisplayPresentTime = -1;
1199         outDequeueReadyTime = -1;
1200         outReleaseTime = -1;
1201     }
1202 
getNextFrameId()1203     uint64_t getNextFrameId() {
1204         uint64_t frameId = -1;
1205         int status = native_window_get_next_frame_id(mWindow.get(), &frameId);
1206         EXPECT_EQ(status, NO_ERROR);
1207         return frameId;
1208     }
1209 
dequeueAndQueue(uint64_t frameIndex)1210     void dequeueAndQueue(uint64_t frameIndex) {
1211         int fence = -1;
1212         ANativeWindowBuffer* buffer = nullptr;
1213         ASSERT_EQ(NO_ERROR,
1214                 mWindow->dequeueBuffer(mWindow.get(), &buffer, &fence));
1215 
1216         int oldAddFrameTimestampsCount =
1217                 mFakeConsumer->mAddFrameTimestampsCount;
1218 
1219         FrameEvents* frame = &mFrames[frameIndex];
1220         uint64_t frameNumber = frameIndex + 1;
1221 
1222         NewFrameEventsEntry fe;
1223         fe.frameNumber = frameNumber;
1224         fe.postedTime = frame->kPostedTime;
1225         fe.requestedPresentTime = frame->kRequestedPresentTime;
1226         fe.acquireFence = frame->mAcquireConsumer.mFenceTime;
1227         mFakeConsumer->mNewFrameEntryOverride = fe;
1228 
1229         mSurface->mFakeFrameEventHistory->setAcquireFenceOverride(
1230                     frame->mAcquireProducer.mFenceTime,
1231                     frame->mAcquireConsumer.mFenceTime);
1232 
1233         ASSERT_EQ(NO_ERROR, mWindow->queueBuffer(mWindow.get(), buffer, fence));
1234 
1235         EXPECT_EQ(frameNumber, mFakeConsumer->mLastAddedFrameNumber);
1236 
1237         EXPECT_EQ(
1238                 oldAddFrameTimestampsCount + (mFrameTimestampsEnabled ? 1 : 0),
1239                 mFakeConsumer->mAddFrameTimestampsCount);
1240     }
1241 
addFrameEvents(bool gpuComposited,uint64_t iOldFrame,int64_t iNewFrame)1242     void addFrameEvents(
1243             bool gpuComposited, uint64_t iOldFrame, int64_t iNewFrame) {
1244         FrameEvents* oldFrame =
1245                 (iOldFrame == NO_FRAME_INDEX) ? nullptr : &mFrames[iOldFrame];
1246         FrameEvents* newFrame = &mFrames[iNewFrame];
1247 
1248         uint64_t nOldFrame = (iOldFrame == NO_FRAME_INDEX) ? 0 : iOldFrame + 1;
1249         uint64_t nNewFrame = iNewFrame + 1;
1250 
1251         // Latch, Composite, and Release the frames in a plausible order.
1252         // Note: The timestamps won't necessarily match the order, but
1253         // that's okay for the purposes of this test.
1254         std::shared_ptr<FenceTime> gpuDoneFenceTime = FenceTime::NO_FENCE;
1255 
1256         // Composite the previous frame one more time, which helps verify
1257         // LastRefresh is updated properly.
1258         if (oldFrame != nullptr) {
1259             mCfeh->addPreComposition(nOldFrame,
1260                                      oldFrame->mRefreshes[2].kStartTime);
1261             gpuDoneFenceTime = gpuComposited ?
1262                     oldFrame->mRefreshes[2].mGpuCompositionDone.mFenceTime :
1263                     FenceTime::NO_FENCE;
1264             mCfeh->addPostComposition(nOldFrame, gpuDoneFenceTime,
1265                     oldFrame->mRefreshes[2].mPresent.mFenceTime,
1266                     oldFrame->mRefreshes[2].kCompositorTiming);
1267         }
1268 
1269         // Latch the new frame.
1270         mCfeh->addLatch(nNewFrame, newFrame->kLatchTime);
1271 
1272         mCfeh->addPreComposition(nNewFrame, newFrame->mRefreshes[0].kStartTime);
1273         gpuDoneFenceTime = gpuComposited ?
1274                 newFrame->mRefreshes[0].mGpuCompositionDone.mFenceTime :
1275                 FenceTime::NO_FENCE;
1276         // HWC2 releases the previous buffer after a new latch just before
1277         // calling postComposition.
1278         if (oldFrame != nullptr) {
1279             mCfeh->addRelease(nOldFrame, oldFrame->kDequeueReadyTime,
1280                     std::shared_ptr<FenceTime>(oldFrame->mRelease.mFenceTime));
1281         }
1282         mCfeh->addPostComposition(nNewFrame, gpuDoneFenceTime,
1283                 newFrame->mRefreshes[0].mPresent.mFenceTime,
1284                 newFrame->mRefreshes[0].kCompositorTiming);
1285 
1286         mCfeh->addPreComposition(nNewFrame, newFrame->mRefreshes[1].kStartTime);
1287         gpuDoneFenceTime = gpuComposited ?
1288                 newFrame->mRefreshes[1].mGpuCompositionDone.mFenceTime :
1289                 FenceTime::NO_FENCE;
1290         mCfeh->addPostComposition(nNewFrame, gpuDoneFenceTime,
1291                 newFrame->mRefreshes[1].mPresent.mFenceTime,
1292                 newFrame->mRefreshes[1].kCompositorTiming);
1293     }
1294 
1295     sp<IGraphicBufferProducer> mProducer;
1296     sp<IGraphicBufferConsumer> mConsumer;
1297     sp<FakeConsumer> mFakeConsumer;
1298     ConsumerFrameEventHistory* mCfeh;
1299     sp<TestSurface> mSurface;
1300     sp<ANativeWindow> mWindow;
1301 
1302     FenceToFenceTimeMap mFenceMap;
1303 
1304     bool mFrameTimestampsEnabled = false;
1305 
1306     int64_t outRequestedPresentTime = -1;
1307     int64_t outAcquireTime = -1;
1308     int64_t outLatchTime = -1;
1309     int64_t outFirstRefreshStartTime = -1;
1310     int64_t outLastRefreshStartTime = -1;
1311     int64_t outGpuCompositionDoneTime = -1;
1312     int64_t outDisplayPresentTime = -1;
1313     int64_t outDequeueReadyTime = -1;
1314     int64_t outReleaseTime = -1;
1315 
1316     FrameEvents mFrames[3] {
1317         { mFenceMap, 1000 }, { mFenceMap, 2000 }, { mFenceMap, 3000 } };
1318 };
1319 
1320 
1321 // This test verifies that the frame timestamps are not retrieved when not
1322 // explicitly enabled via native_window_enable_frame_timestamps.
1323 // We want to check this to make sure there's no overhead for users
1324 // that don't need the timestamp information.
TEST_F(GetFrameTimestampsTest,DefaultDisabled)1325 TEST_F(GetFrameTimestampsTest, DefaultDisabled) {
1326     int fence;
1327     ANativeWindowBuffer* buffer;
1328 
1329     EXPECT_EQ(0, mFakeConsumer->mAddFrameTimestampsCount);
1330     EXPECT_EQ(0, mFakeConsumer->mGetFrameTimestampsCount);
1331 
1332     const uint64_t fId = getNextFrameId();
1333 
1334     // Verify the producer doesn't get frame timestamps piggybacked on dequeue.
1335     ASSERT_EQ(NO_ERROR, mWindow->dequeueBuffer(mWindow.get(), &buffer, &fence));
1336     EXPECT_EQ(0, mFakeConsumer->mAddFrameTimestampsCount);
1337     EXPECT_EQ(0, mFakeConsumer->mGetFrameTimestampsCount);
1338 
1339     // Verify the producer doesn't get frame timestamps piggybacked on queue.
1340     // It is okay that frame timestamps are added in the consumer since it is
1341     // still needed for SurfaceFlinger dumps.
1342     ASSERT_EQ(NO_ERROR, mWindow->queueBuffer(mWindow.get(), buffer, fence));
1343     EXPECT_EQ(1, mFakeConsumer->mAddFrameTimestampsCount);
1344     EXPECT_EQ(0, mFakeConsumer->mGetFrameTimestampsCount);
1345 
1346     // Verify attempts to get frame timestamps fail.
1347     int result = getAllFrameTimestamps(fId);
1348     EXPECT_EQ(INVALID_OPERATION, result);
1349     EXPECT_EQ(0, mFakeConsumer->mGetFrameTimestampsCount);
1350 
1351     // Verify compositor timing query fails.
1352     nsecs_t compositeDeadline = 0;
1353     nsecs_t compositeInterval = 0;
1354     nsecs_t compositeToPresentLatency = 0;
1355     result = native_window_get_compositor_timing(mWindow.get(),
1356         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1357     EXPECT_EQ(INVALID_OPERATION, result);
1358 }
1359 
1360 // This test verifies that the frame timestamps are retrieved if explicitly
1361 // enabled via native_window_enable_frame_timestamps.
TEST_F(GetFrameTimestampsTest,EnabledSimple)1362 TEST_F(GetFrameTimestampsTest, EnabledSimple) {
1363     CompositorTiming initialCompositorTiming {
1364         1000000000, // 1s deadline
1365         16666667, // 16ms interval
1366         50000000, // 50ms present latency
1367     };
1368     mCfeh->initializeCompositorTiming(initialCompositorTiming);
1369 
1370     enableFrameTimestamps();
1371 
1372     // Verify the compositor timing query gets the initial compositor values
1373     // after timststamps are enabled; even before the first frame is queued
1374     // or dequeued.
1375     nsecs_t compositeDeadline = 0;
1376     nsecs_t compositeInterval = 0;
1377     nsecs_t compositeToPresentLatency = 0;
1378     mSurface->setNow(initialCompositorTiming.deadline - 1);
1379     int result = native_window_get_compositor_timing(mWindow.get(),
1380         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1381     EXPECT_EQ(NO_ERROR, result);
1382     EXPECT_EQ(initialCompositorTiming.deadline, compositeDeadline);
1383     EXPECT_EQ(initialCompositorTiming.interval, compositeInterval);
1384     EXPECT_EQ(initialCompositorTiming.presentLatency,
1385               compositeToPresentLatency);
1386 
1387     int fence;
1388     ANativeWindowBuffer* buffer;
1389 
1390     EXPECT_EQ(0, mFakeConsumer->mAddFrameTimestampsCount);
1391     EXPECT_EQ(1, mFakeConsumer->mGetFrameTimestampsCount);
1392 
1393     const uint64_t fId1 = getNextFrameId();
1394 
1395     // Verify getFrameTimestamps is piggybacked on dequeue.
1396     ASSERT_EQ(NO_ERROR, mWindow->dequeueBuffer(mWindow.get(), &buffer, &fence));
1397     EXPECT_EQ(0, mFakeConsumer->mAddFrameTimestampsCount);
1398     EXPECT_EQ(2, mFakeConsumer->mGetFrameTimestampsCount);
1399 
1400     NewFrameEventsEntry f1;
1401     f1.frameNumber = 1;
1402     f1.postedTime = mFrames[0].kPostedTime;
1403     f1.requestedPresentTime = mFrames[0].kRequestedPresentTime;
1404     f1.acquireFence = mFrames[0].mAcquireConsumer.mFenceTime;
1405     mSurface->mFakeFrameEventHistory->setAcquireFenceOverride(
1406             mFrames[0].mAcquireProducer.mFenceTime,
1407             mFrames[0].mAcquireConsumer.mFenceTime);
1408     mFakeConsumer->mNewFrameEntryOverride = f1;
1409     mFrames[0].signalQueueFences();
1410 
1411     // Verify getFrameTimestamps is piggybacked on queue.
1412     ASSERT_EQ(NO_ERROR, mWindow->queueBuffer(mWindow.get(), buffer, fence));
1413     EXPECT_EQ(1, mFakeConsumer->mAddFrameTimestampsCount);
1414     EXPECT_EQ(1u, mFakeConsumer->mLastAddedFrameNumber);
1415     EXPECT_EQ(3, mFakeConsumer->mGetFrameTimestampsCount);
1416 
1417     // Verify queries for timestamps that the producer doesn't know about
1418     // triggers a call to see if the consumer has any new timestamps.
1419     result = getAllFrameTimestamps(fId1);
1420     EXPECT_EQ(NO_ERROR, result);
1421     EXPECT_EQ(4, mFakeConsumer->mGetFrameTimestampsCount);
1422 }
1423 
TEST_F(GetFrameTimestampsTest,QueryPresentSupported)1424 TEST_F(GetFrameTimestampsTest, QueryPresentSupported) {
1425     bool displayPresentSupported = true;
1426     mSurface->mFakeSurfaceComposer->setSupportsPresent(displayPresentSupported);
1427 
1428     // Verify supported bits are forwarded.
1429     int supportsPresent = -1;
1430     mWindow.get()->query(mWindow.get(),
1431             NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &supportsPresent);
1432     EXPECT_EQ(displayPresentSupported, supportsPresent);
1433 }
1434 
TEST_F(GetFrameTimestampsTest,QueryPresentNotSupported)1435 TEST_F(GetFrameTimestampsTest, QueryPresentNotSupported) {
1436     bool displayPresentSupported = false;
1437     mSurface->mFakeSurfaceComposer->setSupportsPresent(displayPresentSupported);
1438 
1439     // Verify supported bits are forwarded.
1440     int supportsPresent = -1;
1441     mWindow.get()->query(mWindow.get(),
1442             NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &supportsPresent);
1443     EXPECT_EQ(displayPresentSupported, supportsPresent);
1444 }
1445 
TEST_F(GetFrameTimestampsTest,SnapToNextTickBasic)1446 TEST_F(GetFrameTimestampsTest, SnapToNextTickBasic) {
1447     nsecs_t phase = 4000;
1448     nsecs_t interval = 1000;
1449 
1450     // Timestamp in previous interval.
1451     nsecs_t timestamp = 3500;
1452     EXPECT_EQ(4000, ProducerFrameEventHistory::snapToNextTick(
1453             timestamp, phase, interval));
1454 
1455     // Timestamp in next interval.
1456     timestamp = 4500;
1457     EXPECT_EQ(5000, ProducerFrameEventHistory::snapToNextTick(
1458             timestamp, phase, interval));
1459 
1460     // Timestamp multiple intervals before.
1461     timestamp = 2500;
1462     EXPECT_EQ(3000, ProducerFrameEventHistory::snapToNextTick(
1463             timestamp, phase, interval));
1464 
1465     // Timestamp multiple intervals after.
1466     timestamp = 6500;
1467     EXPECT_EQ(7000, ProducerFrameEventHistory::snapToNextTick(
1468             timestamp, phase, interval));
1469 
1470     // Timestamp on previous interval.
1471     timestamp = 3000;
1472     EXPECT_EQ(3000, ProducerFrameEventHistory::snapToNextTick(
1473             timestamp, phase, interval));
1474 
1475     // Timestamp on next interval.
1476     timestamp = 5000;
1477     EXPECT_EQ(5000, ProducerFrameEventHistory::snapToNextTick(
1478             timestamp, phase, interval));
1479 
1480     // Timestamp equal to phase.
1481     timestamp = 4000;
1482     EXPECT_EQ(4000, ProducerFrameEventHistory::snapToNextTick(
1483             timestamp, phase, interval));
1484 }
1485 
1486 // int(big_timestamp / interval) < 0, which can cause a crash or invalid result
1487 // if the number of intervals elapsed is internally stored in an int.
TEST_F(GetFrameTimestampsTest,SnapToNextTickOverflow)1488 TEST_F(GetFrameTimestampsTest, SnapToNextTickOverflow) {
1489       nsecs_t phase = 0;
1490       nsecs_t interval = 4000;
1491       nsecs_t big_timestamp = 8635916564000;
1492       int32_t intervals = big_timestamp / interval;
1493 
1494       EXPECT_LT(intervals, 0);
1495       EXPECT_EQ(8635916564000, ProducerFrameEventHistory::snapToNextTick(
1496             big_timestamp, phase, interval));
1497       EXPECT_EQ(8635916564000, ProducerFrameEventHistory::snapToNextTick(
1498             big_timestamp, big_timestamp, interval));
1499 }
1500 
1501 // This verifies the compositor timing is updated by refresh events
1502 // and piggy backed on a queue, dequeue, and enabling of timestamps..
TEST_F(GetFrameTimestampsTest,CompositorTimingUpdatesBasic)1503 TEST_F(GetFrameTimestampsTest, CompositorTimingUpdatesBasic) {
1504     CompositorTiming initialCompositorTiming {
1505         1000000000, // 1s deadline
1506         16666667, // 16ms interval
1507         50000000, // 50ms present latency
1508     };
1509     mCfeh->initializeCompositorTiming(initialCompositorTiming);
1510 
1511     enableFrameTimestamps();
1512 
1513     // We get the initial values before any frames are submitted.
1514     nsecs_t compositeDeadline = 0;
1515     nsecs_t compositeInterval = 0;
1516     nsecs_t compositeToPresentLatency = 0;
1517     mSurface->setNow(initialCompositorTiming.deadline - 1);
1518     int result = native_window_get_compositor_timing(mWindow.get(),
1519         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1520     EXPECT_EQ(NO_ERROR, result);
1521     EXPECT_EQ(initialCompositorTiming.deadline, compositeDeadline);
1522     EXPECT_EQ(initialCompositorTiming.interval, compositeInterval);
1523     EXPECT_EQ(initialCompositorTiming.presentLatency,
1524               compositeToPresentLatency);
1525 
1526     dequeueAndQueue(0);
1527     addFrameEvents(true, NO_FRAME_INDEX, 0);
1528 
1529     // Still get the initial values because the frame events for frame 0
1530     // didn't get a chance to piggyback on a queue or dequeue yet.
1531     result = native_window_get_compositor_timing(mWindow.get(),
1532         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1533     EXPECT_EQ(NO_ERROR, result);
1534     EXPECT_EQ(initialCompositorTiming.deadline, compositeDeadline);
1535     EXPECT_EQ(initialCompositorTiming.interval, compositeInterval);
1536     EXPECT_EQ(initialCompositorTiming.presentLatency,
1537               compositeToPresentLatency);
1538 
1539     dequeueAndQueue(1);
1540     addFrameEvents(true, 0, 1);
1541 
1542     // Now expect the composite values associated with frame 1.
1543     mSurface->setNow(mFrames[0].mRefreshes[1].kCompositorTiming.deadline);
1544     result = native_window_get_compositor_timing(mWindow.get(),
1545         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1546     EXPECT_EQ(NO_ERROR, result);
1547     EXPECT_EQ(mFrames[0].mRefreshes[1].kCompositorTiming.deadline,
1548             compositeDeadline);
1549     EXPECT_EQ(mFrames[0].mRefreshes[1].kCompositorTiming.interval,
1550             compositeInterval);
1551     EXPECT_EQ(mFrames[0].mRefreshes[1].kCompositorTiming.presentLatency,
1552             compositeToPresentLatency);
1553 
1554     dequeueAndQueue(2);
1555     addFrameEvents(true, 1, 2);
1556 
1557     // Now expect the composite values associated with frame 2.
1558     mSurface->setNow(mFrames[1].mRefreshes[1].kCompositorTiming.deadline);
1559     result = native_window_get_compositor_timing(mWindow.get(),
1560         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1561     EXPECT_EQ(NO_ERROR, result);
1562     EXPECT_EQ(mFrames[1].mRefreshes[1].kCompositorTiming.deadline,
1563             compositeDeadline);
1564     EXPECT_EQ(mFrames[1].mRefreshes[1].kCompositorTiming.interval,
1565             compositeInterval);
1566     EXPECT_EQ(mFrames[1].mRefreshes[1].kCompositorTiming.presentLatency,
1567             compositeToPresentLatency);
1568 
1569     // Re-enabling frame timestamps should get the latest values.
1570     disableFrameTimestamps();
1571     enableFrameTimestamps();
1572 
1573     // Now expect the composite values associated with frame 3.
1574     mSurface->setNow(mFrames[2].mRefreshes[1].kCompositorTiming.deadline);
1575     result = native_window_get_compositor_timing(mWindow.get(),
1576         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1577     EXPECT_EQ(NO_ERROR, result);
1578     EXPECT_EQ(mFrames[2].mRefreshes[1].kCompositorTiming.deadline,
1579             compositeDeadline);
1580     EXPECT_EQ(mFrames[2].mRefreshes[1].kCompositorTiming.interval,
1581             compositeInterval);
1582     EXPECT_EQ(mFrames[2].mRefreshes[1].kCompositorTiming.presentLatency,
1583             compositeToPresentLatency);
1584 }
1585 
1586 // This verifies the compositor deadline properly snaps to the the next
1587 // deadline based on the current time.
TEST_F(GetFrameTimestampsTest,CompositorTimingDeadlineSnaps)1588 TEST_F(GetFrameTimestampsTest, CompositorTimingDeadlineSnaps) {
1589     CompositorTiming initialCompositorTiming {
1590         1000000000, // 1s deadline
1591         16666667, // 16ms interval
1592         50000000, // 50ms present latency
1593     };
1594     mCfeh->initializeCompositorTiming(initialCompositorTiming);
1595 
1596     enableFrameTimestamps();
1597 
1598     nsecs_t compositeDeadline = 0;
1599     nsecs_t compositeInterval = 0;
1600     nsecs_t compositeToPresentLatency = 0;
1601 
1602     // A "now" just before the deadline snaps to the deadline.
1603     mSurface->setNow(initialCompositorTiming.deadline - 1);
1604     int result = native_window_get_compositor_timing(mWindow.get(),
1605         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1606     EXPECT_EQ(NO_ERROR, result);
1607     EXPECT_EQ(initialCompositorTiming.deadline, compositeDeadline);
1608     nsecs_t expectedDeadline = initialCompositorTiming.deadline;
1609     EXPECT_EQ(expectedDeadline, compositeDeadline);
1610 
1611     dequeueAndQueue(0);
1612     addFrameEvents(true, NO_FRAME_INDEX, 0);
1613 
1614     // A "now" just after the deadline snaps properly.
1615     mSurface->setNow(initialCompositorTiming.deadline + 1);
1616     result = native_window_get_compositor_timing(mWindow.get(),
1617         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1618     EXPECT_EQ(NO_ERROR, result);
1619     expectedDeadline =
1620             initialCompositorTiming.deadline +initialCompositorTiming.interval;
1621     EXPECT_EQ(expectedDeadline, compositeDeadline);
1622 
1623     dequeueAndQueue(1);
1624     addFrameEvents(true, 0, 1);
1625 
1626     // A "now" just after the next interval snaps properly.
1627     mSurface->setNow(
1628             mFrames[0].mRefreshes[1].kCompositorTiming.deadline +
1629             mFrames[0].mRefreshes[1].kCompositorTiming.interval + 1);
1630     result = native_window_get_compositor_timing(mWindow.get(),
1631         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1632     EXPECT_EQ(NO_ERROR, result);
1633     expectedDeadline =
1634             mFrames[0].mRefreshes[1].kCompositorTiming.deadline +
1635             mFrames[0].mRefreshes[1].kCompositorTiming.interval * 2;
1636     EXPECT_EQ(expectedDeadline, compositeDeadline);
1637 
1638     dequeueAndQueue(2);
1639     addFrameEvents(true, 1, 2);
1640 
1641     // A "now" over 1 interval before the deadline snaps properly.
1642     mSurface->setNow(
1643             mFrames[1].mRefreshes[1].kCompositorTiming.deadline -
1644             mFrames[1].mRefreshes[1].kCompositorTiming.interval - 1);
1645     result = native_window_get_compositor_timing(mWindow.get(),
1646         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1647     EXPECT_EQ(NO_ERROR, result);
1648     expectedDeadline =
1649             mFrames[1].mRefreshes[1].kCompositorTiming.deadline -
1650             mFrames[1].mRefreshes[1].kCompositorTiming.interval;
1651     EXPECT_EQ(expectedDeadline, compositeDeadline);
1652 
1653     // Re-enabling frame timestamps should get the latest values.
1654     disableFrameTimestamps();
1655     enableFrameTimestamps();
1656 
1657     // A "now" over 2 intervals before the deadline snaps properly.
1658     mSurface->setNow(
1659             mFrames[2].mRefreshes[1].kCompositorTiming.deadline -
1660             mFrames[2].mRefreshes[1].kCompositorTiming.interval * 2 - 1);
1661     result = native_window_get_compositor_timing(mWindow.get(),
1662         &compositeDeadline, &compositeInterval, &compositeToPresentLatency);
1663     EXPECT_EQ(NO_ERROR, result);
1664     expectedDeadline =
1665             mFrames[2].mRefreshes[1].kCompositorTiming.deadline -
1666             mFrames[2].mRefreshes[1].kCompositorTiming.interval * 2;
1667     EXPECT_EQ(expectedDeadline, compositeDeadline);
1668 }
1669 
1670 // This verifies the timestamps recorded in the consumer's
1671 // FrameTimestampsHistory are properly retrieved by the producer for the
1672 // correct frames.
TEST_F(GetFrameTimestampsTest,TimestampsAssociatedWithCorrectFrame)1673 TEST_F(GetFrameTimestampsTest, TimestampsAssociatedWithCorrectFrame) {
1674     enableFrameTimestamps();
1675 
1676     const uint64_t fId1 = getNextFrameId();
1677     dequeueAndQueue(0);
1678     mFrames[0].signalQueueFences();
1679 
1680     const uint64_t fId2 = getNextFrameId();
1681     dequeueAndQueue(1);
1682     mFrames[1].signalQueueFences();
1683 
1684     addFrameEvents(true, NO_FRAME_INDEX, 0);
1685     mFrames[0].signalRefreshFences();
1686     addFrameEvents(true, 0, 1);
1687     mFrames[0].signalReleaseFences();
1688     mFrames[1].signalRefreshFences();
1689 
1690     // Verify timestamps are correct for frame 1.
1691     resetTimestamps();
1692     int result = getAllFrameTimestamps(fId1);
1693     EXPECT_EQ(NO_ERROR, result);
1694     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1695     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1696     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1697     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1698     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1699     EXPECT_EQ(mFrames[0].mRefreshes[0].kGpuCompositionDoneTime,
1700             outGpuCompositionDoneTime);
1701     EXPECT_EQ(mFrames[0].mRefreshes[0].kPresentTime, outDisplayPresentTime);
1702     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1703     EXPECT_EQ(mFrames[0].kReleaseTime, outReleaseTime);
1704 
1705     // Verify timestamps are correct for frame 2.
1706     resetTimestamps();
1707     result = getAllFrameTimestamps(fId2);
1708     EXPECT_EQ(NO_ERROR, result);
1709     EXPECT_EQ(mFrames[1].kRequestedPresentTime, outRequestedPresentTime);
1710     EXPECT_EQ(mFrames[1].kProducerAcquireTime, outAcquireTime);
1711     EXPECT_EQ(mFrames[1].kLatchTime, outLatchTime);
1712     EXPECT_EQ(mFrames[1].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1713     EXPECT_EQ(mFrames[1].mRefreshes[1].kStartTime, outLastRefreshStartTime);
1714     EXPECT_EQ(mFrames[1].mRefreshes[0].kGpuCompositionDoneTime,
1715             outGpuCompositionDoneTime);
1716     EXPECT_EQ(mFrames[1].mRefreshes[0].kPresentTime, outDisplayPresentTime);
1717     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outDequeueReadyTime);
1718     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outReleaseTime);
1719 }
1720 
1721 // This test verifies the acquire fence recorded by the consumer is not sent
1722 // back to the producer and the producer saves its own fence.
TEST_F(GetFrameTimestampsTest,QueueTimestampsNoSync)1723 TEST_F(GetFrameTimestampsTest, QueueTimestampsNoSync) {
1724     enableFrameTimestamps();
1725 
1726     // Dequeue and queue frame 1.
1727     const uint64_t fId1 = getNextFrameId();
1728     dequeueAndQueue(0);
1729 
1730     // Verify queue-related timestamps for f1 are available immediately in the
1731     // producer without asking the consumer again, even before signaling the
1732     // acquire fence.
1733     resetTimestamps();
1734     int oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1735     int result = native_window_get_frame_timestamps(mWindow.get(), fId1,
1736             &outRequestedPresentTime, &outAcquireTime, nullptr, nullptr,
1737             nullptr, nullptr, nullptr, nullptr, nullptr);
1738     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1739     EXPECT_EQ(NO_ERROR, result);
1740     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1741     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outAcquireTime);
1742 
1743     // Signal acquire fences. Verify a sync call still isn't necessary.
1744     mFrames[0].signalQueueFences();
1745 
1746     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1747     result = native_window_get_frame_timestamps(mWindow.get(), fId1,
1748             &outRequestedPresentTime, &outAcquireTime, nullptr, nullptr,
1749             nullptr, nullptr, nullptr, nullptr, nullptr);
1750     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1751     EXPECT_EQ(NO_ERROR, result);
1752     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1753     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1754 
1755     // Dequeue and queue frame 2.
1756     const uint64_t fId2 = getNextFrameId();
1757     dequeueAndQueue(1);
1758 
1759     // Verify queue-related timestamps for f2 are available immediately in the
1760     // producer without asking the consumer again, even before signaling the
1761     // acquire fence.
1762     resetTimestamps();
1763     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1764     result = native_window_get_frame_timestamps(mWindow.get(), fId2,
1765             &outRequestedPresentTime, &outAcquireTime, nullptr, nullptr,
1766             nullptr, nullptr, nullptr, nullptr, nullptr);
1767     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1768     EXPECT_EQ(NO_ERROR, result);
1769     EXPECT_EQ(mFrames[1].kRequestedPresentTime, outRequestedPresentTime);
1770     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outAcquireTime);
1771 
1772     // Signal acquire fences. Verify a sync call still isn't necessary.
1773     mFrames[1].signalQueueFences();
1774 
1775     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1776     result = native_window_get_frame_timestamps(mWindow.get(), fId2,
1777             &outRequestedPresentTime, &outAcquireTime, nullptr, nullptr,
1778             nullptr, nullptr, nullptr, nullptr, nullptr);
1779     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1780     EXPECT_EQ(NO_ERROR, result);
1781     EXPECT_EQ(mFrames[1].kRequestedPresentTime, outRequestedPresentTime);
1782     EXPECT_EQ(mFrames[1].kProducerAcquireTime, outAcquireTime);
1783 }
1784 
TEST_F(GetFrameTimestampsTest,ZeroRequestedTimestampsNoSync)1785 TEST_F(GetFrameTimestampsTest, ZeroRequestedTimestampsNoSync) {
1786     enableFrameTimestamps();
1787 
1788     // Dequeue and queue frame 1.
1789     dequeueAndQueue(0);
1790     mFrames[0].signalQueueFences();
1791 
1792     // Dequeue and queue frame 2.
1793     const uint64_t fId2 = getNextFrameId();
1794     dequeueAndQueue(1);
1795     mFrames[1].signalQueueFences();
1796 
1797     addFrameEvents(true, NO_FRAME_INDEX, 0);
1798     mFrames[0].signalRefreshFences();
1799     addFrameEvents(true, 0, 1);
1800     mFrames[0].signalReleaseFences();
1801     mFrames[1].signalRefreshFences();
1802 
1803     // Verify a request for no timestamps doesn't result in a sync call.
1804     int oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1805     int result = native_window_get_frame_timestamps(mWindow.get(), fId2,
1806             nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1807             nullptr, nullptr);
1808     EXPECT_EQ(NO_ERROR, result);
1809     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1810 }
1811 
1812 // This test verifies that fences can signal and update timestamps producer
1813 // side without an additional sync call to the consumer.
TEST_F(GetFrameTimestampsTest,FencesInProducerNoSync)1814 TEST_F(GetFrameTimestampsTest, FencesInProducerNoSync) {
1815     enableFrameTimestamps();
1816 
1817     // Dequeue and queue frame 1.
1818     const uint64_t fId1 = getNextFrameId();
1819     dequeueAndQueue(0);
1820     mFrames[0].signalQueueFences();
1821 
1822     // Dequeue and queue frame 2.
1823     dequeueAndQueue(1);
1824     mFrames[1].signalQueueFences();
1825 
1826     addFrameEvents(true, NO_FRAME_INDEX, 0);
1827     addFrameEvents(true, 0, 1);
1828 
1829     // Verify available timestamps are correct for frame 1, before any
1830     // fence has been signaled.
1831     // Note: A sync call is necessary here since the events triggered by
1832     // addFrameEvents didn't get to piggyback on the earlier queues/dequeues.
1833     resetTimestamps();
1834     int oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1835     int result = getAllFrameTimestamps(fId1);
1836     EXPECT_EQ(oldCount + 1, mFakeConsumer->mGetFrameTimestampsCount);
1837     EXPECT_EQ(NO_ERROR, result);
1838     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1839     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1840     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1841     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1842     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1843     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outGpuCompositionDoneTime);
1844     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outDisplayPresentTime);
1845     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1846     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outReleaseTime);
1847 
1848     // Verify available timestamps are correct for frame 1 again, before any
1849     // fence has been signaled.
1850     // This time a sync call should not be necessary.
1851     resetTimestamps();
1852     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1853     result = getAllFrameTimestamps(fId1);
1854     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1855     EXPECT_EQ(NO_ERROR, result);
1856     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1857     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1858     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1859     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1860     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1861     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outGpuCompositionDoneTime);
1862     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outDisplayPresentTime);
1863     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1864     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outReleaseTime);
1865 
1866     // Signal the fences for frame 1.
1867     mFrames[0].signalRefreshFences();
1868     mFrames[0].signalReleaseFences();
1869 
1870     // Verify all timestamps are available without a sync call.
1871     resetTimestamps();
1872     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1873     result = getAllFrameTimestamps(fId1);
1874     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1875     EXPECT_EQ(NO_ERROR, result);
1876     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1877     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1878     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1879     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1880     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1881     EXPECT_EQ(mFrames[0].mRefreshes[0].kGpuCompositionDoneTime,
1882             outGpuCompositionDoneTime);
1883     EXPECT_EQ(mFrames[0].mRefreshes[0].kPresentTime, outDisplayPresentTime);
1884     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1885     EXPECT_EQ(mFrames[0].kReleaseTime, outReleaseTime);
1886 }
1887 
1888 // This test verifies that if the frame wasn't GPU composited but has a refresh
1889 // event a sync call isn't made to get the GPU composite done time since it will
1890 // never exist.
TEST_F(GetFrameTimestampsTest,NoGpuNoSync)1891 TEST_F(GetFrameTimestampsTest, NoGpuNoSync) {
1892     enableFrameTimestamps();
1893 
1894     // Dequeue and queue frame 1.
1895     const uint64_t fId1 = getNextFrameId();
1896     dequeueAndQueue(0);
1897     mFrames[0].signalQueueFences();
1898 
1899     // Dequeue and queue frame 2.
1900     dequeueAndQueue(1);
1901     mFrames[1].signalQueueFences();
1902 
1903     addFrameEvents(false, NO_FRAME_INDEX, 0);
1904     addFrameEvents(false, 0, 1);
1905 
1906     // Verify available timestamps are correct for frame 1, before any
1907     // fence has been signaled.
1908     // Note: A sync call is necessary here since the events triggered by
1909     // addFrameEvents didn't get to piggyback on the earlier queues/dequeues.
1910     resetTimestamps();
1911     int oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1912     int result = getAllFrameTimestamps(fId1);
1913     EXPECT_EQ(oldCount + 1, mFakeConsumer->mGetFrameTimestampsCount);
1914     EXPECT_EQ(NO_ERROR, result);
1915     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1916     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1917     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1918     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1919     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1920     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_INVALID, outGpuCompositionDoneTime);
1921     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outDisplayPresentTime);
1922     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1923     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outReleaseTime);
1924 
1925     // Signal the fences for frame 1.
1926     mFrames[0].signalRefreshFences();
1927     mFrames[0].signalReleaseFences();
1928 
1929     // Verify all timestamps, except GPU composition, are available without a
1930     // sync call.
1931     resetTimestamps();
1932     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1933     result = getAllFrameTimestamps(fId1);
1934     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1935     EXPECT_EQ(NO_ERROR, result);
1936     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1937     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1938     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1939     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1940     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1941     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_INVALID, outGpuCompositionDoneTime);
1942     EXPECT_EQ(mFrames[0].mRefreshes[0].kPresentTime, outDisplayPresentTime);
1943     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1944     EXPECT_EQ(mFrames[0].kReleaseTime, outReleaseTime);
1945 }
1946 
1947 // This test verifies that if the certain timestamps can't possibly exist for
1948 // the most recent frame, then a sync call is not done.
TEST_F(GetFrameTimestampsTest,NoReleaseNoSync)1949 TEST_F(GetFrameTimestampsTest, NoReleaseNoSync) {
1950     enableFrameTimestamps();
1951 
1952     // Dequeue and queue frame 1.
1953     const uint64_t fId1 = getNextFrameId();
1954     dequeueAndQueue(0);
1955     mFrames[0].signalQueueFences();
1956 
1957     // Dequeue and queue frame 2.
1958     const uint64_t fId2 = getNextFrameId();
1959     dequeueAndQueue(1);
1960     mFrames[1].signalQueueFences();
1961 
1962     addFrameEvents(false, NO_FRAME_INDEX, 0);
1963     addFrameEvents(false, 0, 1);
1964 
1965     // Verify available timestamps are correct for frame 1, before any
1966     // fence has been signaled.
1967     // Note: A sync call is necessary here since the events triggered by
1968     // addFrameEvents didn't get to piggyback on the earlier queues/dequeues.
1969     resetTimestamps();
1970     int oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1971     int result = getAllFrameTimestamps(fId1);
1972     EXPECT_EQ(oldCount + 1, mFakeConsumer->mGetFrameTimestampsCount);
1973     EXPECT_EQ(NO_ERROR, result);
1974     EXPECT_EQ(mFrames[0].kRequestedPresentTime, outRequestedPresentTime);
1975     EXPECT_EQ(mFrames[0].kProducerAcquireTime, outAcquireTime);
1976     EXPECT_EQ(mFrames[0].kLatchTime, outLatchTime);
1977     EXPECT_EQ(mFrames[0].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
1978     EXPECT_EQ(mFrames[0].mRefreshes[2].kStartTime, outLastRefreshStartTime);
1979     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_INVALID, outGpuCompositionDoneTime);
1980     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outDisplayPresentTime);
1981     EXPECT_EQ(mFrames[0].kDequeueReadyTime, outDequeueReadyTime);
1982     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outReleaseTime);
1983 
1984     mFrames[0].signalRefreshFences();
1985     mFrames[0].signalReleaseFences();
1986     mFrames[1].signalRefreshFences();
1987 
1988     // Verify querying for all timestmaps of f2 does not do a sync call. Even
1989     // though the lastRefresh, dequeueReady, and release times aren't
1990     // available, a sync call should not occur because it's not possible for f2
1991     // to encounter the final value for those events until another frame is
1992     // queued.
1993     resetTimestamps();
1994     oldCount = mFakeConsumer->mGetFrameTimestampsCount;
1995     result = getAllFrameTimestamps(fId2);
1996     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
1997     EXPECT_EQ(NO_ERROR, result);
1998     EXPECT_EQ(mFrames[1].kRequestedPresentTime, outRequestedPresentTime);
1999     EXPECT_EQ(mFrames[1].kProducerAcquireTime, outAcquireTime);
2000     EXPECT_EQ(mFrames[1].kLatchTime, outLatchTime);
2001     EXPECT_EQ(mFrames[1].mRefreshes[0].kStartTime, outFirstRefreshStartTime);
2002     EXPECT_EQ(mFrames[1].mRefreshes[1].kStartTime, outLastRefreshStartTime);
2003     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_INVALID, outGpuCompositionDoneTime);
2004     EXPECT_EQ(mFrames[1].mRefreshes[0].kPresentTime, outDisplayPresentTime);
2005     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outDequeueReadyTime);
2006     EXPECT_EQ(NATIVE_WINDOW_TIMESTAMP_PENDING, outReleaseTime);
2007 }
2008 
2009 // This test verifies there are no sync calls for present times
2010 // when they aren't supported and that an error is returned.
2011 
TEST_F(GetFrameTimestampsTest,PresentUnsupportedNoSync)2012 TEST_F(GetFrameTimestampsTest, PresentUnsupportedNoSync) {
2013     enableFrameTimestamps();
2014     mSurface->mFakeSurfaceComposer->setSupportsPresent(false);
2015 
2016     // Dequeue and queue frame 1.
2017     const uint64_t fId1 = getNextFrameId();
2018     dequeueAndQueue(0);
2019 
2020     // Verify a query for the Present times do not trigger a sync call if they
2021     // are not supported.
2022     resetTimestamps();
2023     int oldCount = mFakeConsumer->mGetFrameTimestampsCount;
2024     int result = native_window_get_frame_timestamps(mWindow.get(), fId1,
2025             nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
2026             &outDisplayPresentTime, nullptr, nullptr);
2027     EXPECT_EQ(oldCount, mFakeConsumer->mGetFrameTimestampsCount);
2028     EXPECT_EQ(BAD_VALUE, result);
2029     EXPECT_EQ(-1, outDisplayPresentTime);
2030 }
2031 
TEST_F(SurfaceTest,DequeueWithConsumerDrivenSize)2032 TEST_F(SurfaceTest, DequeueWithConsumerDrivenSize) {
2033     sp<IGraphicBufferProducer> producer;
2034     sp<IGraphicBufferConsumer> consumer;
2035     BufferQueue::createBufferQueue(&producer, &consumer);
2036 
2037     sp<MockConsumer> mockConsumer(new MockConsumer);
2038     consumer->consumerConnect(mockConsumer, false);
2039     consumer->setDefaultBufferSize(10, 10);
2040 
2041     sp<Surface> surface = new Surface(producer);
2042     sp<ANativeWindow> window(surface);
2043     native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU);
2044     native_window_set_buffers_dimensions(window.get(), 0, 0);
2045 
2046     int fence;
2047     ANativeWindowBuffer* buffer;
2048 
2049     // Buffer size is driven by the consumer
2050     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2051     EXPECT_EQ(10, buffer->width);
2052     EXPECT_EQ(10, buffer->height);
2053     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2054 
2055     // Buffer size is driven by the consumer
2056     consumer->setDefaultBufferSize(10, 20);
2057     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2058     EXPECT_EQ(10, buffer->width);
2059     EXPECT_EQ(20, buffer->height);
2060     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2061 
2062     // Transform hint isn't synced to producer before queueBuffer or connect
2063     consumer->setTransformHint(NATIVE_WINDOW_TRANSFORM_ROT_270);
2064     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2065     EXPECT_EQ(10, buffer->width);
2066     EXPECT_EQ(20, buffer->height);
2067     ASSERT_EQ(NO_ERROR, window->queueBuffer(window.get(), buffer, fence));
2068 
2069     // Transform hint is synced to producer but no auto prerotation
2070     consumer->setTransformHint(NATIVE_WINDOW_TRANSFORM_ROT_270);
2071     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2072     EXPECT_EQ(10, buffer->width);
2073     EXPECT_EQ(20, buffer->height);
2074     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2075 
2076     // Prerotation is driven by the consumer with the transform hint used by producer
2077     native_window_set_auto_prerotation(window.get(), true);
2078     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2079     EXPECT_EQ(20, buffer->width);
2080     EXPECT_EQ(10, buffer->height);
2081     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2082 
2083     // Turn off auto prerotaton
2084     native_window_set_auto_prerotation(window.get(), false);
2085     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2086     EXPECT_EQ(10, buffer->width);
2087     EXPECT_EQ(20, buffer->height);
2088     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2089 
2090     // Test auto prerotation bit is disabled after disconnect
2091     native_window_set_auto_prerotation(window.get(), true);
2092     native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_CPU);
2093     native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU);
2094     consumer->setTransformHint(NATIVE_WINDOW_TRANSFORM_ROT_270);
2095     native_window_set_buffers_dimensions(window.get(), 0, 0);
2096     ASSERT_EQ(NO_ERROR, window->dequeueBuffer(window.get(), &buffer, &fence));
2097     EXPECT_EQ(10, buffer->width);
2098     EXPECT_EQ(20, buffer->height);
2099     ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2100 }
2101 
TEST_F(SurfaceTest,DefaultMaxBufferCountSetAndUpdated)2102 TEST_F(SurfaceTest, DefaultMaxBufferCountSetAndUpdated) {
2103     sp<IGraphicBufferProducer> producer;
2104     sp<IGraphicBufferConsumer> consumer;
2105     BufferQueue::createBufferQueue(&producer, &consumer);
2106 
2107     sp<MockConsumer> mockConsumer(new MockConsumer);
2108     consumer->consumerConnect(mockConsumer, false);
2109 
2110     sp<Surface> surface = new Surface(producer);
2111     sp<ANativeWindow> window(surface);
2112 
2113     int count = -1;
2114     ASSERT_EQ(NO_ERROR, window->query(window.get(), NATIVE_WINDOW_MAX_BUFFER_COUNT, &count));
2115     EXPECT_EQ(BufferQueueDefs::NUM_BUFFER_SLOTS, count);
2116 
2117     consumer->setMaxBufferCount(10);
2118     ASSERT_EQ(NO_ERROR, native_window_api_connect(window.get(), NATIVE_WINDOW_API_CPU));
2119     EXPECT_EQ(NO_ERROR, window->query(window.get(), NATIVE_WINDOW_MAX_BUFFER_COUNT, &count));
2120     EXPECT_EQ(10, count);
2121 
2122     ASSERT_EQ(NO_ERROR, native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_CPU));
2123     ASSERT_EQ(NO_ERROR, window->query(window.get(), NATIVE_WINDOW_MAX_BUFFER_COUNT, &count));
2124     EXPECT_EQ(BufferQueueDefs::NUM_BUFFER_SLOTS, count);
2125 }
2126 
TEST_F(SurfaceTest,BatchOperations)2127 TEST_F(SurfaceTest, BatchOperations) {
2128     const int BUFFER_COUNT = 16;
2129     const int BATCH_SIZE = 8;
2130     sp<IGraphicBufferProducer> producer;
2131     sp<IGraphicBufferConsumer> consumer;
2132     BufferQueue::createBufferQueue(&producer, &consumer);
2133 
2134     sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
2135     sp<Surface> surface = new Surface(producer);
2136     sp<ANativeWindow> window(surface);
2137     sp<StubProducerListener> listener = new StubProducerListener();
2138 
2139     ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, /*listener*/listener,
2140             /*reportBufferRemoval*/false));
2141 
2142     ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(window.get(), BUFFER_COUNT));
2143 
2144     std::vector<Surface::BatchBuffer> buffers(BATCH_SIZE);
2145 
2146     // Batch dequeued buffers can be queued individually
2147     ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
2148     for (size_t i = 0; i < BATCH_SIZE; i++) {
2149         ANativeWindowBuffer* buffer = buffers[i].buffer;
2150         int fence = buffers[i].fenceFd;
2151         ASSERT_EQ(NO_ERROR, window->queueBuffer(window.get(), buffer, fence));
2152     }
2153 
2154     // Batch dequeued buffers can be canceled individually
2155     ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
2156     for (size_t i = 0; i < BATCH_SIZE; i++) {
2157         ANativeWindowBuffer* buffer = buffers[i].buffer;
2158         int fence = buffers[i].fenceFd;
2159         ASSERT_EQ(NO_ERROR, window->cancelBuffer(window.get(), buffer, fence));
2160     }
2161 
2162     // Batch dequeued buffers can be batch cancelled
2163     ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
2164     ASSERT_EQ(NO_ERROR, surface->cancelBuffers(buffers));
2165 
2166     // Batch dequeued buffers can be batch queued
2167     ASSERT_EQ(NO_ERROR, surface->dequeueBuffers(&buffers));
2168     std::vector<Surface::BatchQueuedBuffer> queuedBuffers(BATCH_SIZE);
2169     for (size_t i = 0; i < BATCH_SIZE; i++) {
2170         queuedBuffers[i].buffer = buffers[i].buffer;
2171         queuedBuffers[i].fenceFd = buffers[i].fenceFd;
2172         queuedBuffers[i].timestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
2173     }
2174     ASSERT_EQ(NO_ERROR, surface->queueBuffers(queuedBuffers));
2175 
2176     ASSERT_EQ(NO_ERROR, surface->disconnect(NATIVE_WINDOW_API_CPU));
2177 }
2178 
TEST_F(SurfaceTest,BatchIllegalOperations)2179 TEST_F(SurfaceTest, BatchIllegalOperations) {
2180     const int BUFFER_COUNT = 16;
2181     const int BATCH_SIZE = 8;
2182     sp<IGraphicBufferProducer> producer;
2183     sp<IGraphicBufferConsumer> consumer;
2184     BufferQueue::createBufferQueue(&producer, &consumer);
2185 
2186     sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
2187     sp<Surface> surface = new Surface(producer);
2188     sp<ANativeWindow> window(surface);
2189     sp<StubProducerListener> listener = new StubProducerListener();
2190 
2191     ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, /*listener*/listener,
2192             /*reportBufferRemoval*/false));
2193 
2194     ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(window.get(), BUFFER_COUNT));
2195 
2196     std::vector<Surface::BatchBuffer> buffers(BATCH_SIZE);
2197     std::vector<Surface::BatchQueuedBuffer> queuedBuffers(BATCH_SIZE);
2198 
2199     // Batch operations are invalid in shared buffer mode
2200     surface->setSharedBufferMode(true);
2201     ASSERT_EQ(INVALID_OPERATION, surface->dequeueBuffers(&buffers));
2202     ASSERT_EQ(INVALID_OPERATION, surface->cancelBuffers(buffers));
2203     ASSERT_EQ(INVALID_OPERATION, surface->queueBuffers(queuedBuffers));
2204     surface->setSharedBufferMode(false);
2205 
2206     ASSERT_EQ(NO_ERROR, surface->disconnect(NATIVE_WINDOW_API_CPU));
2207 }
2208 
2209 } // namespace android
2210