1 /*
2  * Copyright (c) 2024-2024 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 "camera_napi_worker_queue_keeper.h"
17 
18 #include <algorithm>
19 #include <chrono>
20 #include <condition_variable>
21 #include <cstdint>
22 #include <memory>
23 #include <mutex>
24 #include <new>
25 
26 #include "camera_log.h"
27 #include "camera_napi_const.h"
28 #include "camera_napi_utils.h"
29 namespace OHOS {
30 namespace CameraStandard {
31 constexpr uint64_t WORKER_TIMEOUT = 2000L;
32 constexpr int32_t WORKER_TASK_WAIT_COUNT_MAX = 1;
33 static std::mutex g_WorkerQueueKeeperMutex;
34 static std::shared_ptr<CameraNapiWorkerQueueKeeper> g_WorkerQueueKeeper = nullptr;
35 
WorkerQueueTasksResetCreateTimeNoLock(NapiWorkerQueueTaskTimePoint timePoint)36 void CameraNapiWorkerQueueKeeper::WorkerQueueTasksResetCreateTimeNoLock(NapiWorkerQueueTaskTimePoint timePoint)
37 {
38     for (auto& task : workerQueueTasks_) {
39         task->createTimePoint = timePoint;
40         task->waitCount = 0;
41     }
42 }
43 
GetInstance()44 std::shared_ptr<CameraNapiWorkerQueueKeeper> CameraNapiWorkerQueueKeeper::GetInstance()
45 {
46     if (g_WorkerQueueKeeper != nullptr) {
47         return g_WorkerQueueKeeper;
48     }
49     std::lock_guard<std::mutex> lock(g_WorkerQueueKeeperMutex);
50     if (g_WorkerQueueKeeper != nullptr) {
51         return g_WorkerQueueKeeper;
52     }
53 
54     g_WorkerQueueKeeper = std::make_shared<CameraNapiWorkerQueueKeeper>();
55     return g_WorkerQueueKeeper;
56 }
57 
AcquireWorkerQueueTask(const std::string & taskName)58 std::shared_ptr<NapiWorkerQueueTask> CameraNapiWorkerQueueKeeper::AcquireWorkerQueueTask(const std::string& taskName)
59 {
60     auto queueTask = std::make_shared<NapiWorkerQueueTask>(taskName);
61     std::lock_guard<std::mutex> lock(workerQueueTaskMutex_);
62     workerQueueTasks_.push_back(queueTask);
63     return queueTask;
64 }
65 
WorkerLockCondition(std::shared_ptr<NapiWorkerQueueTask> queueTask,bool & isError)66 bool CameraNapiWorkerQueueKeeper::WorkerLockCondition(std::shared_ptr<NapiWorkerQueueTask> queueTask, bool& isError)
67 {
68     std::lock_guard<std::mutex> lock(workerQueueTaskMutex_);
69     if (std::find(workerQueueTasks_.begin(), workerQueueTasks_.end(), queueTask) == workerQueueTasks_.end()) {
70         MEDIA_ERR_LOG("CameraNapiWorkerQueueKeeper::WorkerLockCondition current task %{public}s not in queue",
71             queueTask->taskName.c_str());
72         isError = true;
73         return true;
74     }
75     auto firstTask = workerQueueTasks_.front();
76     if (firstTask == queueTask) {
77         return true;
78     }
79     if (firstTask->queueStatus == RUNNING) {
80         return false;
81     }
82     auto now = std::chrono::steady_clock::now();
83     auto diffTime = std::chrono::duration_cast<std::chrono::milliseconds>(now - firstTask->createTimePoint);
84     if (diffTime < std::chrono::milliseconds(WORKER_TIMEOUT)) {
85         return false;
86     }
87     if (queueTask->waitCount < WORKER_TASK_WAIT_COUNT_MAX) {
88         queueTask->waitCount++;
89         return false;
90     }
91     MEDIA_ERR_LOG("CameraNapiWorkerQueueKeeper::WorkerLockCondition current task %{public}s wait queue task %{public}s "
92                   "timeout, waitTime:%{public}lld",
93         queueTask->taskName.c_str(), firstTask->taskName.c_str(), diffTime.count());
94     workerQueueTasks_.pop_front();
95     auto frontTask = workerQueueTasks_.front();
96     if (frontTask == queueTask) {
97         return true;
98     }
99     MEDIA_INFO_LOG("CameraNapiWorkerQueueKeeper::WorkerLockCondition current task not equal front task,%{public}s "
100                    "vs %{public}s, continue wait.",
101         queueTask->taskName.c_str(), frontTask->taskName.c_str());
102     WorkerQueueTasksResetCreateTimeNoLock(now);
103     workerCond_.notify_all();
104     return false;
105 }
106 
ConsumeWorkerQueueTask(std::shared_ptr<NapiWorkerQueueTask> queueTask,std::function<void (void)> func)107 bool CameraNapiWorkerQueueKeeper::ConsumeWorkerQueueTask(
108     std::shared_ptr<NapiWorkerQueueTask> queueTask, std::function<void(void)> func)
109 {
110     if (queueTask == nullptr) {
111         return false;
112     }
113     std::unique_lock<std::mutex> lock(workerQueueMutex_);
114     {
115         std::lock_guard<std::mutex> lock(workerQueueTaskMutex_);
116         CHECK_ERROR_RETURN_RET(workerQueueTasks_.empty(), false);
117         CHECK_ERROR_RETURN_RET(
118             std::find(workerQueueTasks_.begin(), workerQueueTasks_.end(), queueTask) == workerQueueTasks_.end(), false);
119     }
120     bool isMatchCondition = false;
121     bool isError = false;
122     while (!isMatchCondition) {
123         isMatchCondition = workerCond_.wait_for(lock, std::chrono::milliseconds(WORKER_TIMEOUT),
124             [this, &queueTask, &isError]() { return WorkerLockCondition(queueTask, isError); });
125     }
126     if (isError) {
127         MEDIA_ERR_LOG("CameraNapiWorkerQueueKeeper::ConsumeWorkerQueueTask wait task %{public}s occur error",
128             queueTask->taskName.c_str());
129         workerCond_.notify_all();
130         return false;
131     }
132     queueTask->queueStatus = RUNNING;
133     func();
134     queueTask->queueStatus = DONE;
135     {
136         auto now = std::chrono::steady_clock::now();
137         std::lock_guard<std::mutex> lock(workerQueueTaskMutex_);
138         workerQueueTasks_.pop_front();
139         WorkerQueueTasksResetCreateTimeNoLock(now);
140     }
141 
142     workerCond_.notify_all();
143     return true;
144 }
145 } // namespace CameraStandard
146 } // namespace OHOS