summaryrefslogtreecommitdiff
path: root/libs/hwc2onfbadapter/HWC2OnFbAdapter.cpp
blob: 7c9e6518b76dc444ea5605d7c85f3b40977f9b9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
 * Copyright 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "HWC2OnFbAdapter"

//#define LOG_NDEBUG 0

#include "hwc2onfbadapter/HWC2OnFbAdapter.h"

#include <algorithm>
#include <type_traits>

#include <inttypes.h>
#include <time.h>
#include <sys/prctl.h>
#include <unistd.h> // for close

#include <hardware/fb.h>
#include <log/log.h>
#include <sync/sync.h>

namespace android {

namespace {

void dumpHook(hwc2_device_t* device, uint32_t* outSize, char* outBuffer) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (outBuffer) {
        *outSize = adapter.getDebugString().copy(outBuffer, *outSize);
    } else {
        adapter.updateDebugString();
        *outSize = adapter.getDebugString().size();
    }
}

int32_t registerCallbackHook(hwc2_device_t* device, int32_t descriptor,
                             hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    switch (descriptor) {
        case HWC2_CALLBACK_HOTPLUG:
            if (pointer) {
                reinterpret_cast<HWC2_PFN_HOTPLUG>(pointer)(callbackData, adapter.getDisplayId(),
                                                            HWC2_CONNECTION_CONNECTED);
            }
            break;
        case HWC2_CALLBACK_REFRESH:
            break;
        case HWC2_CALLBACK_VSYNC:
            adapter.setVsyncCallback(reinterpret_cast<HWC2_PFN_VSYNC>(pointer), callbackData);
            break;
        default:
            return HWC2_ERROR_BAD_PARAMETER;
    }

    return HWC2_ERROR_NONE;
}

uint32_t getMaxVirtualDisplayCountHook(hwc2_device_t* /*device*/) {
    return 0;
}

int32_t createVirtualDisplayHook(hwc2_device_t* /*device*/, uint32_t /*width*/, uint32_t /*height*/,
                                 int32_t* /*format*/, hwc2_display_t* /*outDisplay*/) {
    return HWC2_ERROR_NO_RESOURCES;
}

int32_t destroyVirtualDisplayHook(hwc2_device_t* /*device*/, hwc2_display_t /*display*/) {
    return HWC2_ERROR_BAD_DISPLAY;
}

int32_t setOutputBufferHook(hwc2_device_t* /*device*/, hwc2_display_t /*display*/,
                            buffer_handle_t /*buffer*/, int32_t /*releaseFence*/) {
    return HWC2_ERROR_BAD_DISPLAY;
}

int32_t getDisplayNameHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outSize,
                           char* outName) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    const auto& info = adapter.getInfo();
    if (outName) {
        *outSize = info.name.copy(outName, *outSize);
    } else {
        *outSize = info.name.size();
    }

    return HWC2_ERROR_NONE;
}

int32_t getDisplayTypeHook(hwc2_device_t* device, hwc2_display_t display, int32_t* outType) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    *outType = HWC2_DISPLAY_TYPE_PHYSICAL;
    return HWC2_ERROR_NONE;
}

int32_t getDozeSupportHook(hwc2_device_t* device, hwc2_display_t display, int32_t* outSupport) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    *outSupport = 0;
    return HWC2_ERROR_NONE;
}

int32_t getHdrCapabilitiesHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumTypes,
                               int32_t* /*outTypes*/, float* /*outMaxLuminance*/,
                               float* /*outMaxAverageLuminance*/, float* /*outMinLuminance*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    *outNumTypes = 0;
    return HWC2_ERROR_NONE;
}

int32_t setPowerModeHook(hwc2_device_t* device, hwc2_display_t display, int32_t /*mode*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    // pretend that it works
    return HWC2_ERROR_NONE;
}

int32_t setVsyncEnabledHook(hwc2_device_t* device, hwc2_display_t display, int32_t enabled) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    adapter.enableVsync(enabled == HWC2_VSYNC_ENABLE);
    return HWC2_ERROR_NONE;
}

int32_t getColorModesHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumModes,
                          int32_t* outModes) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    if (outModes) {
        if (*outNumModes > 0) {
            outModes[0] = HAL_COLOR_MODE_NATIVE;
            *outNumModes = 1;
        }
    } else {
        *outNumModes = 1;
    }

    return HWC2_ERROR_NONE;
}

int32_t setColorModeHook(hwc2_device_t* device, hwc2_display_t display, int32_t mode) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (mode != HAL_COLOR_MODE_NATIVE) {
        return HWC2_ERROR_BAD_PARAMETER;
    }

    return HWC2_ERROR_NONE;
}

int32_t setColorTransformHook(hwc2_device_t* device, hwc2_display_t display,
                              const float* /*matrix*/, int32_t /*hint*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    // we always force client composition
    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
    return HWC2_ERROR_NONE;
}

int32_t getClientTargetSupportHook(hwc2_device_t* device, hwc2_display_t display, uint32_t width,
                                   uint32_t height, int32_t format, int32_t dataspace) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (dataspace != HAL_DATASPACE_UNKNOWN) {
        return HWC2_ERROR_UNSUPPORTED;
    }

    const auto& info = adapter.getInfo();
    return (info.width == width && info.height == height && info.format == format)
            ? HWC2_ERROR_NONE
            : HWC2_ERROR_UNSUPPORTED;
}

int32_t setClientTargetHook(hwc2_device_t* device, hwc2_display_t display, buffer_handle_t target,
                            int32_t acquireFence, int32_t dataspace, hwc_region_t /*damage*/) {
    if (acquireFence >= 0) {
        sync_wait(acquireFence, -1);
        close(acquireFence);
    }

    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (dataspace != HAL_DATASPACE_UNKNOWN) {
        return HWC2_ERROR_BAD_PARAMETER;
    }

    // no state change
    adapter.setBuffer(target);
    return HWC2_ERROR_NONE;
}

int32_t getDisplayConfigsHook(hwc2_device_t* device, hwc2_display_t display,
                              uint32_t* outNumConfigs, hwc2_config_t* outConfigs) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    if (outConfigs) {
        if (*outNumConfigs > 0) {
            outConfigs[0] = adapter.getConfigId();
            *outNumConfigs = 1;
        }
    } else {
        *outNumConfigs = 1;
    }

    return HWC2_ERROR_NONE;
}

int32_t getDisplayAttributeHook(hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config,
                                int32_t attribute, int32_t* outValue) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (adapter.getConfigId() != config) {
        return HWC2_ERROR_BAD_CONFIG;
    }

    const auto& info = adapter.getInfo();
    switch (attribute) {
        case HWC2_ATTRIBUTE_WIDTH:
            *outValue = int32_t(info.width);
            break;
        case HWC2_ATTRIBUTE_HEIGHT:
            *outValue = int32_t(info.height);
            break;
        case HWC2_ATTRIBUTE_VSYNC_PERIOD:
            *outValue = int32_t(info.vsync_period_ns);
            break;
        case HWC2_ATTRIBUTE_DPI_X:
            *outValue = int32_t(info.xdpi_scaled);
            break;
        case HWC2_ATTRIBUTE_DPI_Y:
            *outValue = int32_t(info.ydpi_scaled);
            break;
        default:
            return HWC2_ERROR_BAD_PARAMETER;
    }

    return HWC2_ERROR_NONE;
}

int32_t getActiveConfigHook(hwc2_device_t* device, hwc2_display_t display,
                            hwc2_config_t* outConfig) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    *outConfig = adapter.getConfigId();
    return HWC2_ERROR_NONE;
}

int32_t setActiveConfigHook(hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (adapter.getConfigId() != config) {
        return HWC2_ERROR_BAD_CONFIG;
    }

    return HWC2_ERROR_NONE;
}

int32_t validateDisplayHook(hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumTypes,
                            uint32_t* outNumRequests) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    const auto& dirtyLayers = adapter.getDirtyLayers();
    *outNumTypes = dirtyLayers.size();
    *outNumRequests = 0;

    if (*outNumTypes > 0) {
        adapter.setState(HWC2OnFbAdapter::State::VALIDATED_WITH_CHANGES);
        return HWC2_ERROR_HAS_CHANGES;
    } else {
        adapter.setState(HWC2OnFbAdapter::State::VALIDATED);
        return HWC2_ERROR_NONE;
    }
}

int32_t getChangedCompositionTypesHook(hwc2_device_t* device, hwc2_display_t display,
                                       uint32_t* outNumElements, hwc2_layer_t* outLayers,
                                       int32_t* outTypes) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (adapter.getState() == HWC2OnFbAdapter::State::MODIFIED) {
        return HWC2_ERROR_NOT_VALIDATED;
    }

    // request client composition for all layers
    const auto& dirtyLayers = adapter.getDirtyLayers();
    if (outLayers && outTypes) {
        *outNumElements = std::min(*outNumElements, uint32_t(dirtyLayers.size()));
        auto iter = dirtyLayers.cbegin();
        for (uint32_t i = 0; i < *outNumElements; i++) {
            outLayers[i] = *iter++;
            outTypes[i] = HWC2_COMPOSITION_CLIENT;
        }
    } else {
        *outNumElements = dirtyLayers.size();
    }

    return HWC2_ERROR_NONE;
}

int32_t getDisplayRequestsHook(hwc2_device_t* device, hwc2_display_t display,
                               int32_t* outDisplayRequests, uint32_t* outNumElements,
                               hwc2_layer_t* /*outLayers*/, int32_t* /*outLayerRequests*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (adapter.getState() == HWC2OnFbAdapter::State::MODIFIED) {
        return HWC2_ERROR_NOT_VALIDATED;
    }

    *outDisplayRequests = 0;
    *outNumElements = 0;
    return HWC2_ERROR_NONE;
}

int32_t acceptDisplayChangesHook(hwc2_device_t* device, hwc2_display_t display) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (adapter.getState() == HWC2OnFbAdapter::State::MODIFIED) {
        return HWC2_ERROR_NOT_VALIDATED;
    }

    adapter.clearDirtyLayers();
    adapter.setState(HWC2OnFbAdapter::State::VALIDATED);
    return HWC2_ERROR_NONE;
}

int32_t presentDisplayHook(hwc2_device_t* device, hwc2_display_t display,
                           int32_t* outPresentFence) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (adapter.getState() != HWC2OnFbAdapter::State::VALIDATED) {
        return HWC2_ERROR_NOT_VALIDATED;
    }

    adapter.postBuffer();
    *outPresentFence = -1;

    return HWC2_ERROR_NONE;
}

int32_t getReleaseFencesHook(hwc2_device_t* device, hwc2_display_t display,
                             uint32_t* outNumElements, hwc2_layer_t* /*outLayers*/,
                             int32_t* /*outFences*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    *outNumElements = 0;
    return HWC2_ERROR_NONE;
}

int32_t createLayerHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t* outLayer) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    *outLayer = adapter.addLayer();
    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
    return HWC2_ERROR_NONE;
}

int32_t destroyLayerHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    if (adapter.removeLayer(layer)) {
        adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
        return HWC2_ERROR_NONE;
    } else {
        return HWC2_ERROR_BAD_LAYER;
    }
}

int32_t setCursorPositionHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t /*layer*/,
                              int32_t /*x*/, int32_t /*y*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }

    // always an error
    return HWC2_ERROR_BAD_LAYER;
}

int32_t setLayerBufferHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
                           buffer_handle_t /*buffer*/, int32_t acquireFence) {
    if (acquireFence >= 0) {
        sync_wait(acquireFence, -1);
        close(acquireFence);
    }

    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (!adapter.hasLayer(layer)) {
        return HWC2_ERROR_BAD_LAYER;
    }

    // no state change
    return HWC2_ERROR_NONE;
}

int32_t setLayerSurfaceDamageHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
                                  hwc_region_t /*damage*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (!adapter.hasLayer(layer)) {
        return HWC2_ERROR_BAD_LAYER;
    }

    // no state change
    return HWC2_ERROR_NONE;
}

int32_t setLayerCompositionTypeHook(hwc2_device_t* device, hwc2_display_t display,
                                    hwc2_layer_t layer, int32_t type) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (!adapter.markLayerDirty(layer, type != HWC2_COMPOSITION_CLIENT)) {
        return HWC2_ERROR_BAD_LAYER;
    }

    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
    return HWC2_ERROR_NONE;
}

template <typename... Args>
int32_t setLayerStateHook(hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
                          Args... /*args*/) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    if (adapter.getDisplayId() != display) {
        return HWC2_ERROR_BAD_DISPLAY;
    }
    if (!adapter.hasLayer(layer)) {
        return HWC2_ERROR_BAD_LAYER;
    }

    adapter.setState(HWC2OnFbAdapter::State::MODIFIED);
    return HWC2_ERROR_NONE;
}

template <typename PFN, typename T>
static hwc2_function_pointer_t asFP(T function) {
    static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer");
    return reinterpret_cast<hwc2_function_pointer_t>(function);
}

hwc2_function_pointer_t getFunctionHook(hwc2_device_t* /*device*/, int32_t descriptor) {
    switch (descriptor) {
        // global functions
        case HWC2_FUNCTION_DUMP:
            return asFP<HWC2_PFN_DUMP>(dumpHook);
        case HWC2_FUNCTION_REGISTER_CALLBACK:
            return asFP<HWC2_PFN_REGISTER_CALLBACK>(registerCallbackHook);

        // virtual display functions
        case HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT:
            return asFP<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(getMaxVirtualDisplayCountHook);
        case HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY:
            return asFP<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(createVirtualDisplayHook);
        case HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY:
            return asFP<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(destroyVirtualDisplayHook);
        case HWC2_FUNCTION_SET_OUTPUT_BUFFER:
            return asFP<HWC2_PFN_SET_OUTPUT_BUFFER>(setOutputBufferHook);

        // display functions
        case HWC2_FUNCTION_GET_DISPLAY_NAME:
            return asFP<HWC2_PFN_GET_DISPLAY_NAME>(getDisplayNameHook);
        case HWC2_FUNCTION_GET_DISPLAY_TYPE:
            return asFP<HWC2_PFN_GET_DISPLAY_TYPE>(getDisplayTypeHook);
        case HWC2_FUNCTION_GET_DOZE_SUPPORT:
            return asFP<HWC2_PFN_GET_DOZE_SUPPORT>(getDozeSupportHook);
        case HWC2_FUNCTION_GET_HDR_CAPABILITIES:
            return asFP<HWC2_PFN_GET_HDR_CAPABILITIES>(getHdrCapabilitiesHook);
        case HWC2_FUNCTION_SET_POWER_MODE:
            return asFP<HWC2_PFN_SET_POWER_MODE>(setPowerModeHook);
        case HWC2_FUNCTION_SET_VSYNC_ENABLED:
            return asFP<HWC2_PFN_SET_VSYNC_ENABLED>(setVsyncEnabledHook);
        case HWC2_FUNCTION_GET_COLOR_MODES:
            return asFP<HWC2_PFN_GET_COLOR_MODES>(getColorModesHook);
        case HWC2_FUNCTION_SET_COLOR_MODE:
            return asFP<HWC2_PFN_SET_COLOR_MODE>(setColorModeHook);
        case HWC2_FUNCTION_SET_COLOR_TRANSFORM:
            return asFP<HWC2_PFN_SET_COLOR_TRANSFORM>(setColorTransformHook);
        case HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT:
            return asFP<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>(getClientTargetSupportHook);
        case HWC2_FUNCTION_SET_CLIENT_TARGET:
            return asFP<HWC2_PFN_SET_CLIENT_TARGET>(setClientTargetHook);

        // config functions
        case HWC2_FUNCTION_GET_DISPLAY_CONFIGS:
            return asFP<HWC2_PFN_GET_DISPLAY_CONFIGS>(getDisplayConfigsHook);
        case HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE:
            return asFP<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(getDisplayAttributeHook);
        case HWC2_FUNCTION_GET_ACTIVE_CONFIG:
            return asFP<HWC2_PFN_GET_ACTIVE_CONFIG>(getActiveConfigHook);
        case HWC2_FUNCTION_SET_ACTIVE_CONFIG:
            return asFP<HWC2_PFN_SET_ACTIVE_CONFIG>(setActiveConfigHook);

        // validate/present functions
        case HWC2_FUNCTION_VALIDATE_DISPLAY:
            return asFP<HWC2_PFN_VALIDATE_DISPLAY>(validateDisplayHook);
        case HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES:
            return asFP<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(getChangedCompositionTypesHook);
        case HWC2_FUNCTION_GET_DISPLAY_REQUESTS:
            return asFP<HWC2_PFN_GET_DISPLAY_REQUESTS>(getDisplayRequestsHook);
        case HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES:
            return asFP<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(acceptDisplayChangesHook);
        case HWC2_FUNCTION_PRESENT_DISPLAY:
            return asFP<HWC2_PFN_PRESENT_DISPLAY>(presentDisplayHook);
        case HWC2_FUNCTION_GET_RELEASE_FENCES:
            return asFP<HWC2_PFN_GET_RELEASE_FENCES>(getReleaseFencesHook);

        // layer create/destroy
        case HWC2_FUNCTION_CREATE_LAYER:
            return asFP<HWC2_PFN_CREATE_LAYER>(createLayerHook);
        case HWC2_FUNCTION_DESTROY_LAYER:
            return asFP<HWC2_PFN_DESTROY_LAYER>(destroyLayerHook);

        // layer functions; validateDisplay not required
        case HWC2_FUNCTION_SET_CURSOR_POSITION:
            return asFP<HWC2_PFN_SET_CURSOR_POSITION>(setCursorPositionHook);
        case HWC2_FUNCTION_SET_LAYER_BUFFER:
            return asFP<HWC2_PFN_SET_LAYER_BUFFER>(setLayerBufferHook);
        case HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE:
            return asFP<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(setLayerSurfaceDamageHook);

        // layer state functions; validateDisplay required
        case HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE:
            return asFP<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(setLayerCompositionTypeHook);
        case HWC2_FUNCTION_SET_LAYER_BLEND_MODE:
            return asFP<HWC2_PFN_SET_LAYER_BLEND_MODE>(setLayerStateHook<int32_t>);
        case HWC2_FUNCTION_SET_LAYER_COLOR:
            return asFP<HWC2_PFN_SET_LAYER_COLOR>(setLayerStateHook<hwc_color_t>);
        case HWC2_FUNCTION_SET_LAYER_DATASPACE:
            return asFP<HWC2_PFN_SET_LAYER_DATASPACE>(setLayerStateHook<int32_t>);
        case HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME:
            return asFP<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(setLayerStateHook<hwc_rect_t>);
        case HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA:
            return asFP<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(setLayerStateHook<float>);
        case HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM:
            return asFP<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(setLayerStateHook<buffer_handle_t>);
        case HWC2_FUNCTION_SET_LAYER_SOURCE_CROP:
            return asFP<HWC2_PFN_SET_LAYER_SOURCE_CROP>(setLayerStateHook<hwc_frect_t>);
        case HWC2_FUNCTION_SET_LAYER_TRANSFORM:
            return asFP<HWC2_PFN_SET_LAYER_TRANSFORM>(setLayerStateHook<int32_t>);
        case HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION:
            return asFP<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(setLayerStateHook<hwc_region_t>);
        case HWC2_FUNCTION_SET_LAYER_Z_ORDER:
            return asFP<HWC2_PFN_SET_LAYER_Z_ORDER>(setLayerStateHook<uint32_t>);

        default:
            ALOGE("unknown function descriptor %d", descriptor);
            return nullptr;
    }
}

void getCapabilitiesHook(hwc2_device_t* /*device*/, uint32_t* outCount,
                         int32_t* /*outCapabilities*/) {
    *outCount = 0;
}

int closeHook(hw_device_t* device) {
    auto& adapter = HWC2OnFbAdapter::cast(device);
    adapter.close();
    return 0;
}

} // anonymous namespace

HWC2OnFbAdapter::HWC2OnFbAdapter(framebuffer_device_t* fbDevice)
      : hwc2_device_t(), mFbDevice(fbDevice) {
    common.close = closeHook;
    hwc2_device::getCapabilities = getCapabilitiesHook;
    hwc2_device::getFunction = getFunctionHook;

    mFbInfo.name = "fbdev";
    mFbInfo.width = mFbDevice->width;
    mFbInfo.height = mFbDevice->height;
    mFbInfo.format = mFbDevice->format;
    mFbInfo.vsync_period_ns = int(1e9 / mFbDevice->fps);
    mFbInfo.xdpi_scaled = int(mFbDevice->xdpi * 1000.0f);
    mFbInfo.ydpi_scaled = int(mFbDevice->ydpi * 1000.0f);

    mVsyncThread.start(0, mFbInfo.vsync_period_ns);
}

HWC2OnFbAdapter& HWC2OnFbAdapter::cast(hw_device_t* device) {
    return *reinterpret_cast<HWC2OnFbAdapter*>(device);
}

HWC2OnFbAdapter& HWC2OnFbAdapter::cast(hwc2_device_t* device) {
    return *reinterpret_cast<HWC2OnFbAdapter*>(device);
}

hwc2_display_t HWC2OnFbAdapter::getDisplayId() {
    return 0;
}

hwc2_config_t HWC2OnFbAdapter::getConfigId() {
    return 0;
}

void HWC2OnFbAdapter::close() {
    mVsyncThread.stop();
    framebuffer_close(mFbDevice);
}

const HWC2OnFbAdapter::Info& HWC2OnFbAdapter::getInfo() const {
    return mFbInfo;
}

void HWC2OnFbAdapter::updateDebugString() {
    if (mFbDevice->common.version >= 1 && mFbDevice->dump) {
        char buffer[4096];
        mFbDevice->dump(mFbDevice, buffer, sizeof(buffer));
        buffer[sizeof(buffer) - 1] = '\0';

        mDebugString = buffer;
    }
}

const std::string& HWC2OnFbAdapter::getDebugString() const {
    return mDebugString;
}

void HWC2OnFbAdapter::setState(State state) {
    mState = state;
}

HWC2OnFbAdapter::State HWC2OnFbAdapter::getState() const {
    return mState;
}

hwc2_layer_t HWC2OnFbAdapter::addLayer() {
    hwc2_layer_t id = ++mNextLayerId;

    mLayers.insert(id);
    mDirtyLayers.insert(id);

    return id;
}

bool HWC2OnFbAdapter::removeLayer(hwc2_layer_t layer) {
    mDirtyLayers.erase(layer);
    return mLayers.erase(layer);
}

bool HWC2OnFbAdapter::hasLayer(hwc2_layer_t layer) const {
    return mLayers.count(layer) > 0;
}

bool HWC2OnFbAdapter::markLayerDirty(hwc2_layer_t layer, bool dirty) {
    if (mLayers.count(layer) == 0) {
        return false;
    }

    if (dirty) {
        mDirtyLayers.insert(layer);
    } else {
        mDirtyLayers.erase(layer);
    }

    return true;
}

const std::unordered_set<hwc2_layer_t>& HWC2OnFbAdapter::getDirtyLayers() const {
    return mDirtyLayers;
}

void HWC2OnFbAdapter::clearDirtyLayers() {
    mDirtyLayers.clear();
}

/*
 * For each frame, SurfaceFlinger
 *
 *  - peforms GLES composition
 *  - calls eglSwapBuffers
 *  - calls setClientTarget, which maps to setBuffer below
 *  - calls presentDisplay, which maps to postBuffer below
 *
 * setBuffer should be a good place to call compositionComplete.
 *
 * As for post, it
 *
 *  - schedules the buffer for presentation on the next vsync
 *  - locks the buffer and blocks all other users trying to lock it
 *
 * It does not give us a way to return a present fence, and we need to live
 * with that.  The implication is that, when we are double-buffered,
 * SurfaceFlinger assumes the front buffer is available for rendering again
 * immediately after the back buffer is posted.  The locking semantics
 * hopefully are strong enough that the rendering will be blocked.
 */
void HWC2OnFbAdapter::setBuffer(buffer_handle_t buffer) {
    if (mFbDevice->compositionComplete) {
        mFbDevice->compositionComplete(mFbDevice);
    }
    mBuffer = buffer;
}

bool HWC2OnFbAdapter::postBuffer() {
    int error = 0;
    if (mBuffer) {
        error = mFbDevice->post(mFbDevice, mBuffer);
    }

    return error == 0;
}

void HWC2OnFbAdapter::setVsyncCallback(HWC2_PFN_VSYNC callback, hwc2_callback_data_t data) {
    mVsyncThread.setCallback(callback, data);
}

void HWC2OnFbAdapter::enableVsync(bool enable) {
    mVsyncThread.enableCallback(enable);
}

int64_t HWC2OnFbAdapter::VsyncThread::now() {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);

    return int64_t(ts.tv_sec) * 1'000'000'000 + ts.tv_nsec;
}

bool HWC2OnFbAdapter::VsyncThread::sleepUntil(int64_t t) {
    struct timespec ts;
    ts.tv_sec = t / 1'000'000'000;
    ts.tv_nsec = t % 1'000'000'000;

    while (true) {
        int error = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, nullptr);
        if (error) {
            if (error == EINTR) {
                continue;
            }
            return false;
        } else {
            return true;
        }
    }
}

void HWC2OnFbAdapter::VsyncThread::start(int64_t firstVsync, int64_t period) {
    mNextVsync = firstVsync;
    mPeriod = period;
    mStarted = true;
    mThread = std::thread(&VsyncThread::vsyncLoop, this);
}

void HWC2OnFbAdapter::VsyncThread::stop() {
    {
        std::lock_guard<std::mutex> lock(mMutex);
        mStarted = false;
    }
    mCondition.notify_all();
    mThread.join();
}

void HWC2OnFbAdapter::VsyncThread::setCallback(HWC2_PFN_VSYNC callback, hwc2_callback_data_t data) {
    std::lock_guard<std::mutex> lock(mMutex);
    mCallback = callback;
    mCallbackData = data;
}

void HWC2OnFbAdapter::VsyncThread::enableCallback(bool enable) {
    {
        std::lock_guard<std::mutex> lock(mMutex);
        mCallbackEnabled = enable;
    }
    mCondition.notify_all();
}

void HWC2OnFbAdapter::VsyncThread::vsyncLoop() {
    prctl(PR_SET_NAME, "VsyncThread", 0, 0, 0);

    std::unique_lock<std::mutex> lock(mMutex);
    if (!mStarted) {
        return;
    }

    while (true) {
        if (!mCallbackEnabled) {
            mCondition.wait(lock, [this] { return mCallbackEnabled || !mStarted; });
            if (!mStarted) {
                break;
            }
        }

        lock.unlock();

        // adjust mNextVsync if necessary
        int64_t t = now();
        if (mNextVsync < t) {
            int64_t n = (t - mNextVsync + mPeriod - 1) / mPeriod;
            mNextVsync += mPeriod * n;
        }
        bool fire = sleepUntil(mNextVsync);

        lock.lock();

        if (fire) {
            ALOGV("VsyncThread(%" PRId64 ")", mNextVsync);
            if (mCallback) {
                mCallback(mCallbackData, getDisplayId(), mNextVsync);
            }
            mNextVsync += mPeriod;
        }
    }
}

} // namespace android