1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef VSYNC_ADAPTER_IMPL_H
17 #define VSYNC_ADAPTER_IMPL_H
18 
19 #include <functional>
20 #include <memory>
21 
22 #include "event_handler.h"
23 #include "graphic_adapter.h"
24 #include "vsync_receiver.h"
25 #include "foundation/graphic/graphic_2d/rosen/modules/render_service_client/core/ui/rs_frame_rate_linker.h"
26 
27 namespace OHOS::NWeb {
28 class VSyncAdapterImpl : public VSyncAdapter {
29 public:
30     VSyncAdapterImpl() = default;
31     ~VSyncAdapterImpl() override;
32     VSyncAdapterImpl(const VSyncAdapterImpl&) = delete;
33     VSyncAdapterImpl& operator=(const VSyncAdapterImpl&) = delete;
34 
35     static VSyncAdapterImpl& GetInstance();
36     VSyncErrorCode RequestVsync(void* data, NWebVSyncCb cb) override;
37     int64_t GetVSyncPeriod() override;
38     void SetFrameRateLinkerEnable(bool enabled) override;
39     void SetFramePreferredRate(int32_t preferredRate) override;
40 
41     void SetOnVsyncCallback(void (*callback)()) override;
42     void SetIsGPUProcess(bool isGPU);
43     void SetOnVsyncEndCallback(void (*onVsyncEndCallback)()) override;
44 
45     void SetScene(const std::string& sceneName, uint32_t state) override;
46 private:
47     static void OnVsync(int64_t timestamp, void* data);
48     void VsyncCallbackInner(int64_t nanoTimestamp);
49     VSyncErrorCode Init();
50 
51     std::mutex mtx_;
52     bool hasRequestedVsync_ = false;
53     bool hasReportedKeyThread_ = false;
54     std::shared_ptr<Rosen::VSyncReceiver> receiver_ = nullptr;
55     std::shared_ptr<OHOS::AppExecFwk::EventHandler> vsyncHandler_;
56     std::unordered_map<void*, NWebVSyncCb> vsyncCallbacks_;
57     Rosen::VSyncReceiver::FrameCallback frameCallback_ = {
58         .userData_ = this,
59         .callback_ = OnVsync,
60     };
61     std::shared_ptr<Rosen::RSFrameRateLinker> frameRateLinker_;
62     static void (*callback_)();
63     static void (*onVsyncEndCallback_)();
64     bool frameRateLinkerEnable_ = false;
65     bool isGPUProcess_ = false;
66 
67     std::string pkgName_ {""};
68 };
69 } // namespace OHOS::NWeb
70 
71 #endif // VSYNC_ADAPTER_IMPL_H
72