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 #pragma once
18 
19 #include <android-base/thread_annotations.h>
20 #include <future>
21 #include <optional>
22 #include <thread>
23 
24 #include "DisplayHardware/HWComposer.h"
25 
26 namespace android::compositionengine::impl {
27 
28 // HWC Validate call may take multiple milliseconds to complete and can account for
29 // a signification amount of time in the display hotpath. This helper class allows
30 // us to run the hwc validate function on a real time thread if we can predict what
31 // the composition strategy will be and if composition includes client composition.
32 // While the hwc validate runs, client composition is kicked off with the prediction.
33 // When the worker returns with a value, the composition continues if the prediction
34 // was successful otherwise the client composition is re-executed.
35 //
36 // Note: This does not alter the sequence between HWC and surfaceflinger.
37 class HwcAsyncWorker final {
38 public:
39     HwcAsyncWorker();
40     ~HwcAsyncWorker();
41     // Runs the provided function which calls hwc validate and returns the requested
42     // device changes as a future.
43     std::future<bool> send(std::function<bool()>);
44 
45 private:
46     std::mutex mMutex;
47     std::condition_variable mCv GUARDED_BY(mMutex);
48     bool mDone GUARDED_BY(mMutex) = false;
49     bool mTaskRequested GUARDED_BY(mMutex) = false;
50     std::packaged_task<bool()> mTask GUARDED_BY(mMutex);
51     std::thread mThread;
52     void run();
53 };
54 
55 } // namespace android::compositionengine::impl
56