1 /*
2 * Copyright (c) 2021 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 #include "vsync_controller.h"
17
18 namespace OHOS {
19 namespace Rosen {
VSyncController(const sptr<VSyncGenerator> & geng,int64_t offset)20 VSyncController::VSyncController(const sptr<VSyncGenerator> &geng, int64_t offset)
21 : generator_(geng), callbackMutex_(), callback_(nullptr),
22 offsetMutex_(), phaseOffset_(offset), enabled_(false)
23 {
24 }
25
~VSyncController()26 VSyncController::~VSyncController()
27 {
28 }
29
SetEnable(bool enbale)30 VsyncError VSyncController::SetEnable(bool enbale)
31 {
32 if (generator_ == nullptr) {
33 return VSYNC_ERROR_NULLPTR;
34 }
35 const sptr<VSyncGenerator> generator = generator_.promote();
36 if (generator == nullptr) {
37 return VSYNC_ERROR_NULLPTR;
38 }
39 std::lock_guard<std::mutex> locker(offsetMutex_);
40 VsyncError ret = VSYNC_ERROR_OK;
41 if (enbale) {
42 ret = generator->AddListener(phaseOffset_, this);
43 } else {
44 ret = generator->RemoveListener(this);
45 }
46 enabled_ = enbale;
47 return ret;
48 }
49
SetCallback(Callback * cb)50 VsyncError VSyncController::SetCallback(Callback *cb)
51 {
52 if (cb == nullptr) {
53 return VSYNC_ERROR_NULLPTR;
54 }
55 std::lock_guard<std::mutex> locker(callbackMutex_);
56 callback_ = cb;
57 return VSYNC_ERROR_OK;
58 }
59
SetPhaseOffset(int64_t offset)60 VsyncError VSyncController::SetPhaseOffset(int64_t offset)
61 {
62 if (generator_ == nullptr) {
63 return VSYNC_ERROR_NULLPTR;
64 }
65 const sptr<VSyncGenerator> generator = generator_.promote();
66 if (generator == nullptr) {
67 return VSYNC_ERROR_NULLPTR;
68 }
69 std::lock_guard<std::mutex> locker(offsetMutex_);
70 phaseOffset_ = offset;
71 return generator->ChangePhaseOffset(this, phaseOffset_);
72 }
73
OnVSyncEvent(int64_t now)74 void VSyncController::OnVSyncEvent(int64_t now)
75 {
76 Callback *cb = nullptr;
77 {
78 std::lock_guard<std::mutex> locker(callbackMutex_);
79 cb = callback_;
80 }
81 if (cb != nullptr) {
82 cb->OnVSyncEvent(now);
83 }
84 }
85 }
86 }
87