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