File: test_multi_threaded_compositor.cpp

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

#include "src/server/compositor/multi_threaded_compositor.h"
#include "src/server/report/null_report_factory.h"

#include <mir/compositor/display_listener.h>
#include <mir/compositor/display_buffer_compositor.h>
#include <mir/compositor/scene.h>
#include <mir/compositor/display_buffer_compositor_factory.h>
#include <mir/scene/observer.h>
#include <mir/raii.h>

#include <mir/test/current_thread_name.h>
#include <mir/test/doubles/null_display.h>
#include <mir/test/doubles/null_display_sink.h>
#include <mir/test/doubles/mock_cursor.h>
#include <mir/test/doubles/mock_display_sink.h>
#include <mir/test/doubles/mock_compositor_report.h>
#include <mir/test/doubles/mock_scene.h>
#include <mir/test/doubles/stub_scene.h>
#include <mir/test/doubles/stub_display.h>
#include <mir/test/doubles/stub_renderable.h>
#include <mir/test/doubles/null_display_buffer_compositor_factory.h>
#include <mir/test/doubles/stub_cursor.h>

#include <boost/throw_exception.hpp>

#include <unordered_map>
#include <unordered_set>
#include <thread>
#include <mutex>
#include <chrono>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

using namespace std::literals::chrono_literals;

namespace mc = mir::compositor;
namespace mg = mir::graphics;
namespace ms = mir::scene;
namespace mr = mir::report;
namespace geom = mir::geometry;
namespace mtd = mir::test::doubles;
namespace mt = mir::test;

class StubDisplayWithMockBuffers : public mtd::NullDisplay
{
public:
    StubDisplayWithMockBuffers(unsigned int nbuffers) : buffers{nbuffers} {}

    void for_each_display_sync_group(std::function<void(mg::DisplaySyncGroup&)> const& f) override
    {
        for (auto& db : buffers)
            f(db);
    }

    void for_each_mock_buffer(std::function<void(mtd::MockDisplaySink&)> const& f)
    {
        for (auto& db : buffers)
            f(db.buffer);
    }

private:
    struct StubDisplaySyncGroup : mg::DisplaySyncGroup
    {
        void for_each_display_sink(std::function<void(mg::DisplaySink&)> const& f) override
        {
            f(buffer);
        }
        void post() override {}
        std::chrono::milliseconds recommended_sleep() const override
        {
            return std::chrono::milliseconds::zero();
        }
        testing::NiceMock<mtd::MockDisplaySink> buffer;
    };

    std::vector<StubDisplaySyncGroup> buffers;
};

class StubScene : public mtd::StubScene
{
public:
    StubScene()
        : throw_on_add_observer_{false}
    {
    }

    void add_observer(std::shared_ptr<ms::Observer> const& observer_) override
    {
        std::lock_guard lock{observer_mutex};

        if (throw_on_add_observer_)
            BOOST_THROW_EXCEPTION(std::runtime_error(""));

        assert(!observer);
        observer = observer_;
    }

    void remove_observer(std::weak_ptr<ms::Observer> const& /* observer */) override
    {
        std::lock_guard lock{observer_mutex};
        observer.reset();
    }

    void emit_change_event()
    {
        {
            std::lock_guard lock{observer_mutex};

            // Any old event will do.
            if (observer)
                observer->surfaces_reordered({});
        }
        /* Reduce run-time under valgrind */
        std::this_thread::yield();
    }

    void throw_on_add_observer(bool flag)
    {
        throw_on_add_observer_ = flag;
    }

    private:
    std::mutex observer_mutex;
    std::shared_ptr<ms::Observer> observer;
    bool throw_on_add_observer_;
};

class RecordingDisplayBufferCompositor : public mc::DisplayBufferCompositor
{
public:
    RecordingDisplayBufferCompositor(std::function<void()> const& mark_render_buffer)
        : mark_render_buffer{mark_render_buffer}
    {
    }

    bool composite(mc::SceneElementSequence&&)
    {
        mark_render_buffer();
        /* Reduce run-time under valgrind */
        std::this_thread::yield();
        return true;
    }

private:
    std::function<void()> const mark_render_buffer;
};


class RecordingDisplayBufferCompositorFactory : public mc::DisplayBufferCompositorFactory
{
public:
    std::unique_ptr<mc::DisplayBufferCompositor> create_compositor_for(mg::DisplaySink& display_sink)
    {
        auto raw = new RecordingDisplayBufferCompositor{
            [&display_sink,this]()
            {
                mark_render_buffer(display_sink);
            }};
        return std::unique_ptr<RecordingDisplayBufferCompositor>(raw);
    }

    void mark_render_buffer(mg::DisplaySink& sink)
    {
        std::lock_guard lk{m};

        if (records.find(&sink) == records.end())
            records[&sink] = Record(0, std::unordered_set<std::thread::id>());

        ++records[&sink].first;
        records[&sink].second.insert(std::this_thread::get_id());
    }

    bool enough_records_gathered(unsigned int nbuffers, unsigned int min_record_count = 1000)
    {
        std::lock_guard lk{m};

        if (records.size() < nbuffers)
            return false;

        for (auto const& e : records)
        {
            Record const& r = e.second;
            if (r.first < min_record_count)
                return false;
        }

        return true;
    }

    bool each_buffer_rendered_in_single_thread()
    {
        for (auto const& e : records)
        {
            Record const& r = e.second;
            if (r.second.size() != 1)
                return false;
        }

        return true;
    }

    bool buffers_rendered_in_different_threads()
    {
        std::unordered_set<std::thread::id> seen;
        seen.insert(std::this_thread::get_id());

        for (auto const& e : records)
        {
            Record const& r = e.second;
            auto iter = r.second.begin();
            if (seen.find(*iter) != seen.end())
                return false;
            seen.insert(*iter);
        }

        return true;
    }

    bool check_record_count_for_each_buffer(
            unsigned int nbuffers,
            unsigned int min,
            unsigned int max = ~0u)
    {
        std::lock_guard lk{m};

        if (records.size() < nbuffers)
            return (min == 0 && max == 0);

        for (auto const& e : records)
        {
            Record const& r = e.second;
            if (r.first < min || r.first > max)
                return false;
        }

        return true;
    }

private:
    std::mutex m;
    typedef std::pair<unsigned int, std::unordered_set<std::thread::id>> Record;
    std::unordered_map<mg::DisplaySink*,Record> records;
};

class SurfaceUpdatingDisplayBufferCompositor : public mc::DisplayBufferCompositor
{
public:
    SurfaceUpdatingDisplayBufferCompositor(std::function<void()> const& fake_surface_update)
        : fake_surface_update{fake_surface_update}
    {
    }

    bool composite(mc::SceneElementSequence&&) override
    {
        fake_surface_update();
        /* Reduce run-time under valgrind */
        std::this_thread::yield();
        return true;
    }

private:
    std::function<void()> const fake_surface_update;
};

class SurfaceUpdatingDisplayBufferCompositorFactory : public mc::DisplayBufferCompositorFactory
{
public:
    SurfaceUpdatingDisplayBufferCompositorFactory(std::shared_ptr<StubScene> const& scene)
        : scene{scene},
          render_count{0}
    {
    }

    std::unique_ptr<mc::DisplayBufferCompositor> create_compositor_for(mg::DisplaySink&)
    {
        auto raw = new SurfaceUpdatingDisplayBufferCompositor{[this]{fake_surface_update();}};
        return std::unique_ptr<SurfaceUpdatingDisplayBufferCompositor>(raw);
    }

    void fake_surface_update()
    {
        scene->emit_change_event();
        ++render_count;
    }

    bool enough_renders_happened()
    {
        unsigned int const enough_renders{1000};
        return render_count > enough_renders;
    }

private:
    std::shared_ptr<StubScene> const scene;
    std::atomic<unsigned int> render_count;
};

class ThreadNameDisplayBufferCompositorFactory : public mc::DisplayBufferCompositorFactory
{
public:
    std::unique_ptr<mc::DisplayBufferCompositor> create_compositor_for(mg::DisplaySink&)
    {
        auto raw = new RecordingDisplayBufferCompositor{
            [this]()
            {
                std::lock_guard lock{thread_names_mutex};
                thread_names.emplace_back(mt::current_thread_name());
            }};
        return std::unique_ptr<RecordingDisplayBufferCompositor>(raw);
    }

    size_t num_thread_names_gathered()
    {
        std::lock_guard lock{thread_names_mutex};
        return thread_names.size();
    }

    std::mutex thread_names_mutex;
    std::vector<std::string> thread_names;
};

namespace
{
struct StubDisplayListener : mc::DisplayListener
{
    virtual void add_display(geom::Rectangle const& /*area*/) override {}
    virtual void remove_display(geom::Rectangle const& /*area*/) override {}
};

struct MockDisplayListener : mc::DisplayListener
{
    MOCK_METHOD(void, add_display, (geom::Rectangle const& /*area*/), (override));
    MOCK_METHOD(void, remove_display, (geom::Rectangle const& /*area*/), (override));
};

auto const null_report = mr::null_compositor_report();
auto const stub_cursor = std::make_shared<mtd::StubCursor>();
unsigned int const composites_per_update{1};
auto const null_display_listener = std::make_shared<StubDisplayListener>();
std::chrono::milliseconds const default_delay{-1};

}

TEST(MultiThreadedCompositor, compositing_happens_in_different_threads)
{
    using namespace testing;

    unsigned int const nbuffers{3};

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, true};

    compositor.start();

    while (!db_compositor_factory->enough_records_gathered(nbuffers))
        scene->emit_change_event();

    compositor.stop();

    EXPECT_TRUE(db_compositor_factory->each_buffer_rendered_in_single_thread());
    EXPECT_TRUE(db_compositor_factory->buffers_rendered_in_different_threads());
}

TEST(MultiThreadedCompositor, does_not_deadlock_itself)
{   // Regression test for LP: #1471909
    auto scene = std::make_shared<StubScene>();

    class ReentrantDisplayListener : public mc::DisplayListener
    {
    public:
        ReentrantDisplayListener(std::shared_ptr<StubScene> const& scene)
            : scene{scene}
        {
        }
        void add_display(geom::Rectangle const&) override
        {
            scene->emit_change_event();
        }
        void remove_display(geom::Rectangle const&) override
        {
        }
    private:
        std::shared_ptr<StubScene> const scene;
    };

    mc::MultiThreadedCompositor compositor{
        std::make_shared<mtd::StubDisplay>(3),
        std::make_shared<mtd::NullDisplayBufferCompositorFactory>(),
        scene,
        std::make_shared<ReentrantDisplayListener>(scene),
        null_report,
        stub_cursor,
        default_delay,
        true
    };

    for (int i = 0; i < 1000; ++i)
    {
        compositor.start();
        compositor.stop();
        std::this_thread::yield();
    }
}

TEST(MultiThreadedCompositor, reports_in_the_right_places)
{
    using namespace testing;

    auto display = std::make_shared<StubDisplayWithMockBuffers>(1);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory =
        std::make_shared<RecordingDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<mtd::MockCompositorReport>();
    mc::MultiThreadedCompositor compositor{display,
                                           db_compositor_factory,
                                           scene,
                                           null_display_listener,
                                           mock_report,
                                           stub_cursor,
                                           default_delay,
                                           true};

    EXPECT_CALL(*mock_report, started())
        .Times(1);

    display->for_each_mock_buffer([](mtd::MockDisplaySink& mock_buf)
    {
        EXPECT_CALL(mock_buf, view_area()).Times(AtLeast(1))
            .WillRepeatedly(Return(geom::Rectangle()));
    });

    EXPECT_CALL(*mock_report, added_display(_,_,_,_,_))
        .Times(1);
    EXPECT_CALL(*mock_report, scheduled())
        .Times(2);

    EXPECT_CALL(*mock_report, stopped())
        .Times(AtLeast(1));

    compositor.start();
    scene->emit_change_event();
    while (!db_compositor_factory->check_record_count_for_each_buffer(1, composites_per_update))
        std::this_thread::yield();
    compositor.stop();
}

/*
 * It's difficult to test that a render won't happen, without some further
 * introspective capabilities that would complicate the code. This test will
 * catch a problem if it occurs, but can't ensure that a problem, even if
 * present, will occur in a determinstic manner.
 *
 * Nonetheless, the test is useful since it's very likely to fail if a problem
 * is present (and don't forget that it's usually run multiple times per day).
 */
TEST(MultiThreadedCompositor, composites_only_on_demand)
{
    using namespace testing;

    unsigned int const nbuffers = 3;

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, true};

    // Verify we're actually starting at zero frames
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 0, 0));

    compositor.start();

    // Initial render: initial_composites frames should be composited at least
    while (!db_compositor_factory->check_record_count_for_each_buffer(nbuffers, composites_per_update))
        std::this_thread::sleep_for(std::chrono::milliseconds(10));

    // Now we have initial_composites redraws, pause for a while
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    // ... and make sure the number is still only 3
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, composites_per_update, composites_per_update));

    // Trigger more surface changes
    scene->emit_change_event();

    // Display buffers should be forced to render another 3, so that's 6
    while (!db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 2*composites_per_update))
        std::this_thread::sleep_for(std::chrono::milliseconds(10));

    // Now pause without any further surface changes
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    // Verify we never triggered more than 2*initial_composites compositions
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 2*composites_per_update, 2*composites_per_update));

    compositor.stop();  // Pause the compositor so we don't race

    // Now trigger many surfaces changes close together
    for (int i = 0; i < 10; i++)
        scene->emit_change_event();

    compositor.start();

    // Display buffers should be forced to render another 3, so that's 9
    while (!db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 3*composites_per_update))
        std::this_thread::sleep_for(std::chrono::milliseconds(10));

    // Now pause without any further surface changes
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    // Verify we never triggered more than 9 compositions
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 3*composites_per_update, 3*composites_per_update));

    compositor.stop();
}

TEST(MultiThreadedCompositor, recommended_sleep_throttles_compositor_loop)
{
    using namespace testing;
    using namespace std::chrono;

    unsigned int const nbuffers = 3;
    milliseconds const recommendation(10);

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, factory, scene,
                                           null_display_listener, null_report, stub_cursor,
                                           recommendation, false};

    EXPECT_TRUE(factory->check_record_count_for_each_buffer(nbuffers, 0, 0));

    compositor.start();

    int const max_retries = 100;
    int const nframes = 10;
    auto start = system_clock::now();

    for (int frame = 1; frame <= nframes; ++frame)
    {
        scene->emit_change_event();

        int retry = 0;
        while (retry < max_retries &&
               !factory->check_record_count_for_each_buffer(nbuffers, frame))
        {
            std::this_thread::sleep_for(milliseconds(1));
            ++retry;
        }
        ASSERT_LT(retry, max_retries);
    }

    /*
     * Detecting the throttling from outside the compositor thread is actually
     * trickier than you think. Because the display buffer counter won't be
     * delayed by the sleep; only the subsequent frame will be delayed. So
     * that's why we measure overall duration here...
     */
    auto duration = system_clock::now() - start;
    // Minus 2 because the first won't be throttled, and the last not detected.
    int minimum = recommendation.count() * (nframes - 2);
    ASSERT_THAT(duration_cast<milliseconds>(duration).count(),
                Ge(minimum));

    compositor.stop();
}

TEST(MultiThreadedCompositor, when_no_initial_composite_is_needed_there_is_none)
{
    using namespace testing;

    unsigned int const nbuffers = 3;

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, false};

    // Verify we're actually starting at zero frames
    ASSERT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 0, 0));

    compositor.start();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    // Verify we're still at zero frames
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 0, 0));

    compositor.stop();
}

TEST(MultiThreadedCompositor, initial_composite_is_requested_we_composite_exactly_once_on_start)
{
    using namespace testing;
    using namespace std::literals::chrono_literals;

    unsigned int const nbuffers = 3;

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, true};

    // Verify we're actually starting at zero frames
    ASSERT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 0, 0));

    compositor.start();
    std::this_thread::sleep_for(100ms);

    // Verify we've composited exactly once
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 1, 1));

    compositor.stop();
}

TEST(MultiThreadedCompositor, when_no_initial_composite_is_needed_we_still_composite_on_restart)
{
    using namespace testing;

    unsigned int const nbuffers = 3;

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, false};

    compositor.start();

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    // Verify we're actually starting at zero frames
    ASSERT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, 0, 0));

    compositor.stop();
    compositor.start();

    for (int countdown = 100;
        countdown != 0 &&
        !db_compositor_factory->check_record_count_for_each_buffer(nbuffers, composites_per_update, composites_per_update);
        --countdown)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    // Verify we composited the expected frame
    EXPECT_TRUE(db_compositor_factory->check_record_count_for_each_buffer(nbuffers, composites_per_update, composites_per_update));

    compositor.stop();
}

TEST(MultiThreadedCompositor, surface_update_from_render_doesnt_deadlock)
{
    using namespace testing;

    unsigned int const nbuffers{3};

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<SurfaceUpdatingDisplayBufferCompositorFactory>(scene);
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, true};

    compositor.start();

    while (!db_compositor_factory->enough_renders_happened())
        std::this_thread::sleep_for(std::chrono::milliseconds(10));

    compositor.stop();
}

TEST(MultiThreadedCompositor, double_start_or_stop_ignored)
{
    using namespace testing;

    unsigned int const nbuffers{3};
    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto mock_scene = std::make_shared<NiceMock<mtd::MockScene>>();
    auto db_compositor_factory = std::make_shared<mtd::NullDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<testing::NiceMock<mtd::MockCompositorReport>>();

    EXPECT_CALL(*mock_report, started())
        .Times(1);
    EXPECT_CALL(*mock_report, stopped())
        .Times(1);
    EXPECT_CALL(*mock_scene, add_observer(_))
        .Times(1);
    EXPECT_CALL(*mock_scene, remove_observer(_))
        .Times(1);
    EXPECT_CALL(*mock_scene, scene_elements_for(_))
        .Times(AtLeast(0))
        .WillRepeatedly(Return(mc::SceneElementSequence{}));

    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, mock_scene, null_display_listener, mock_report, stub_cursor, default_delay, true};

    compositor.start();
    compositor.start();
    compositor.stop();
    compositor.stop();
}

TEST(MultiThreadedCompositor, cleans_up_after_throw_in_start)
{
    unsigned int const nbuffers{3};

    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, true};

    scene->throw_on_add_observer(true);

    EXPECT_THROW(compositor.start(), std::runtime_error);

    scene->throw_on_add_observer(false);

    /* No point in running the rest of the test if it throws again */
    ASSERT_NO_THROW(compositor.start());

    /* The minimum number of records here should be nbuffers *2, since we are checking for
     * presence of at least one additional rogue compositor thread per display buffer
     * However to avoid timing considerations like one good thread compositing the display buffer
     * twice before the rogue thread gets a chance to, an arbitrary number of records are gathered
     */
    unsigned int min_number_of_records = 100;

    /* Timeout here in case the exception from setting the scene callback put the compositor
     * in a bad state that did not allow it to composite (hence no records gathered)
     */
    auto time_out = std::chrono::steady_clock::now() + std::chrono::seconds(5);
    while (!db_compositor_factory->enough_records_gathered(nbuffers, min_number_of_records) &&
           std::chrono::steady_clock::now() <= time_out)
    {
        scene->emit_change_event();
        std::this_thread::yield();
    }

    /* Check expectation in case a timeout happened */
    EXPECT_TRUE(db_compositor_factory->enough_records_gathered(nbuffers, min_number_of_records));

    compositor.stop();

    /* Only one thread should be rendering each display buffer
     * If the compositor failed to cleanup correctly more than one thread could be
     * compositing the same display buffer
     */
    EXPECT_TRUE(db_compositor_factory->each_buffer_rendered_in_single_thread());
}

#ifndef MIR_DONT_USE_PTHREAD_GETNAME_NP
TEST(MultiThreadedCompositor, names_compositor_threads)
#else
TEST(MultiThreadedCompositor, DISABLED_names_compositor_threads)
#endif
{
    using namespace testing;

    unsigned int const nbuffers{3};

    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<ThreadNameDisplayBufferCompositorFactory>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, stub_cursor, default_delay, true};

    compositor.start();

    unsigned int const min_number_of_thread_names = 10;

    while (db_compositor_factory->num_thread_names_gathered() < min_number_of_thread_names)
        scene->emit_change_event();

    compositor.stop();

    auto const& thread_names = db_compositor_factory->thread_names;

    for (size_t i = 0; i < thread_names.size(); ++i)
        EXPECT_THAT(thread_names[i], Eq("Mir/Comp")) << "i=" << i;
}

TEST(MultiThreadedCompositor, registers_and_unregisters_with_scene)
{
    using namespace testing;
    unsigned int const nbuffers{3};
    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto mock_scene = std::make_shared<NiceMock<mtd::MockScene>>();
    auto db_compositor_factory = std::make_shared<mtd::NullDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<testing::NiceMock<mtd::MockCompositorReport>>();

    EXPECT_CALL(*mock_scene, register_compositor(_))
        .Times(nbuffers);
    mc::MultiThreadedCompositor compositor{
        display, db_compositor_factory, mock_scene, null_display_listener, mock_report, stub_cursor, default_delay, true};

    compositor.start();

    Mock::VerifyAndClearExpectations(mock_scene.get());

    EXPECT_CALL(*mock_scene, unregister_compositor(_))
        .Times(nbuffers);

    compositor.stop();
}

TEST(MultiThreadedCompositor, notifies_about_display_additions_and_removals)
{
    using namespace testing;
    unsigned int const nbuffers{3};
    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto stub_scene = std::make_shared<NiceMock<StubScene>>();
    auto mock_display_listener = std::make_shared<MockDisplayListener>();
    auto db_compositor_factory = std::make_shared<mtd::NullDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<testing::NiceMock<mtd::MockCompositorReport>>();

    mc::MultiThreadedCompositor compositor{
        display, db_compositor_factory, stub_scene, mock_display_listener, mock_report, stub_cursor, default_delay, true};

    EXPECT_CALL(*mock_display_listener, add_display(_)).Times(nbuffers);

    compositor.start();
    Mock::VerifyAndClearExpectations(mock_display_listener.get());

    EXPECT_CALL(*mock_display_listener, remove_display(_)).Times(nbuffers);
    compositor.stop();
}

TEST(MultiThreadedCompositor, when_compositor_thread_fails_start_reports_error)
{
    using namespace testing;
    unsigned int const nbuffers{3};
    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto stub_scene = std::make_shared<NiceMock<StubScene>>();
    auto mock_display_listener = std::make_shared<MockDisplayListener>();
    auto db_compositor_factory = std::make_shared<mtd::NullDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<testing::NiceMock<mtd::MockCompositorReport>>();

    mc::MultiThreadedCompositor compositor{
        display, db_compositor_factory, stub_scene, mock_display_listener, mock_report, stub_cursor, default_delay, true};

    EXPECT_CALL(*mock_display_listener, add_display(_))
        .WillRepeatedly(Throw(std::runtime_error("Failed to add display")));

    EXPECT_THROW(compositor.start(), std::runtime_error);
}

//LP: 1481418
TEST(MultiThreadedCompositor, can_schedule_from_display_observer_when_adding_display)
{
    using namespace testing;
    unsigned int const nbuffers{3};
    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto stub_scene = std::make_shared<NiceMock<StubScene>>();
    auto mock_display_listener = std::make_shared<NiceMock<MockDisplayListener>>();
    auto db_compositor_factory = std::make_shared<mtd::NullDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<testing::NiceMock<mtd::MockCompositorReport>>();

    ON_CALL(*mock_display_listener, add_display(_))
        .WillByDefault(InvokeWithoutArgs([&]{ stub_scene->emit_change_event(); }));

    mc::MultiThreadedCompositor compositor{
        display, db_compositor_factory, stub_scene, mock_display_listener, mock_report, stub_cursor, default_delay, true};
    compositor.start();
}

TEST(MultiThreadedCompositor, can_schedule_from_display_observer_when_removing_display)
{
    using namespace testing;
    unsigned int const nbuffers{3};
    auto display = std::make_shared<StubDisplayWithMockBuffers>(nbuffers);
    auto stub_scene = std::make_shared<NiceMock<StubScene>>();
    auto mock_display_listener = std::make_shared<NiceMock<MockDisplayListener>>();
    auto db_compositor_factory = std::make_shared<mtd::NullDisplayBufferCompositorFactory>();
    auto mock_report = std::make_shared<testing::NiceMock<mtd::MockCompositorReport>>();

    ON_CALL(*mock_display_listener, remove_display(_))
        .WillByDefault(InvokeWithoutArgs([&]{ stub_scene->emit_change_event(); }));

    mc::MultiThreadedCompositor compositor{
        display, db_compositor_factory, stub_scene, mock_display_listener, mock_report, stub_cursor, default_delay, true};
    compositor.start();
}

TEST(MultiThreadedCompositor, checks_if_cursor_needs_compositing)
{
    using namespace testing;
    using namespace std::literals::chrono_literals;

    unsigned int const nbuffers = 1;

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    auto const mock_cursor = std::make_shared<mtd::MockCursor>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, mock_cursor, default_delay, true};

    EXPECT_CALL(*mock_cursor, needs_compositing()).Times(1).WillOnce(Return(false));
    compositor.start();
    std::this_thread::sleep_for(100ms);

    compositor.stop();
}

TEST(MultiThreadedCompositor, gets_renderable_if_cursor_needs_compositing)
{
    using namespace testing;
    using namespace std::literals::chrono_literals;

    unsigned int const nbuffers = 1;

    auto display = std::make_shared<mtd::StubDisplay>(nbuffers);
    auto scene = std::make_shared<StubScene>();
    auto db_compositor_factory = std::make_shared<RecordingDisplayBufferCompositorFactory>();
    auto const mock_cursor = std::make_shared<mtd::MockCursor>();
    mc::MultiThreadedCompositor compositor{display, db_compositor_factory, scene, null_display_listener, null_report, mock_cursor, default_delay, true};

    EXPECT_CALL(*mock_cursor, needs_compositing()).Times(1).WillOnce(Return(true));
    EXPECT_CALL(*mock_cursor, renderable()).Times(1).WillOnce(Return(std::make_shared<mtd::StubRenderable>()));
    compositor.start();
    std::this_thread::sleep_for(100ms);

    compositor.stop();
}