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