1 /*
2  * Copyright 2022 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 #ifndef ANDROID_HWC_VSYNCTHREAD_H
18 #define ANDROID_HWC_VSYNCTHREAD_H
19 
20 #include <aidl/android/hardware/graphics/composer3/VsyncPeriodChangeConstraints.h>
21 #include <aidl/android/hardware/graphics/composer3/VsyncPeriodChangeTimeline.h>
22 #include <android/hardware/graphics/common/1.0/types.h>
23 
24 #include <chrono>
25 #include <mutex>
26 #include <optional>
27 #include <thread>
28 
29 #include "Common.h"
30 
31 namespace aidl::android::hardware::graphics::composer3::impl {
32 
33 // Generates Vsync signals in software.
34 class VsyncThread {
35    public:
36     VsyncThread(int64_t id);
37     virtual ~VsyncThread();
38 
39     VsyncThread(const VsyncThread&) = delete;
40     VsyncThread& operator=(const VsyncThread&) = delete;
41 
42     VsyncThread(VsyncThread&&) = delete;
43     VsyncThread& operator=(VsyncThread&&) = delete;
44 
45     HWC3::Error start(int32_t periodNanos);
46 
47     HWC3::Error setCallbacks(const std::shared_ptr<IComposerCallback>& callback);
48 
49     HWC3::Error setVsyncEnabled(bool enabled);
50 
51     HWC3::Error scheduleVsyncUpdate(
52         int32_t newVsyncPeriod, const VsyncPeriodChangeConstraints& newVsyncPeriodChangeConstraints,
53         VsyncPeriodChangeTimeline* timeline);
54 
55    private:
56     HWC3::Error stop();
57 
58     void threadLoop();
59 
60     std::chrono::nanoseconds updateVsyncPeriodLocked(
61         std::chrono::time_point<std::chrono::steady_clock> now);
62 
63     const int64_t mDisplayId;
64 
65     std::thread mThread;
66 
67     std::mutex mStateMutex;
68 
69     std::atomic<bool> mShuttingDown{false};
70 
71     std::shared_ptr<IComposerCallback> mCallbacks;
72 
73     bool mVsyncEnabled = false;
74     std::chrono::nanoseconds mVsyncPeriod;
75     std::chrono::time_point<std::chrono::steady_clock> mPreviousVsync;
76 
77     struct PendingUpdate {
78         std::chrono::nanoseconds period;
79         std::chrono::time_point<std::chrono::steady_clock> updateAfter;
80     };
81     std::optional<PendingUpdate> mPendingUpdate;
82 };
83 
84 }  // namespace aidl::android::hardware::graphics::composer3::impl
85 
86 #endif
87