1 /*
2  * Copyright (c) 2023 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 #ifndef LOG_TAG
16 #define LOG_TAG "NapiAudioRountingAvailableDeviceChangeCallback"
17 #endif
18 
19 #include "napi_audio_rounting_available_devicechange_callback.h"
20 #include "napi_audio_enum.h"
21 #include "napi_audio_error.h"
22 #include "napi_param_utils.h"
23 #include "audio_errors.h"
24 #include "audio_manager_log.h"
25 #include "napi_audio_manager_callbacks.h"
26 
27 namespace OHOS {
28 namespace AudioStandard {
NapiAudioRountingAvailableDeviceChangeCallback(napi_env env)29 NapiAudioRountingAvailableDeviceChangeCallback::NapiAudioRountingAvailableDeviceChangeCallback(napi_env env)
30 {
31     env_ = env;
32     AUDIO_DEBUG_LOG("NapiAudioRountingAvailableDeviceChangeCallback: instance create");
33 }
34 
~NapiAudioRountingAvailableDeviceChangeCallback()35 NapiAudioRountingAvailableDeviceChangeCallback::~NapiAudioRountingAvailableDeviceChangeCallback()
36 {
37     AUDIO_DEBUG_LOG("NapiAudioRountingAvailableDeviceChangeCallback: instance destroy");
38 }
39 
SaveRoutingAvailbleDeviceChangeCbRef(AudioDeviceUsage usage,napi_value callback)40 void NapiAudioRountingAvailableDeviceChangeCallback::SaveRoutingAvailbleDeviceChangeCbRef(AudioDeviceUsage usage,
41     napi_value callback)
42 {
43     std::lock_guard<std::mutex> lock(mutex_);
44     napi_ref callbackRef = nullptr;
45     const int32_t refCount = ARGS_ONE;
46 
47     for (auto it = availableDeviceChangeCbList_.begin(); it != availableDeviceChangeCbList_.end(); ++it) {
48         bool isSameCallback = NapiAudioManagerCallback::IsSameCallback(env_, callback, (*it).first->cb_);
49         CHECK_AND_RETURN_LOG(!isSameCallback,
50             "SaveRoutingAvailbleDeviceChangeCbRef: audio manager has same callback, nothing to do");
51     }
52 
53     napi_status status = napi_create_reference(env_, callback, refCount, &callbackRef);
54     CHECK_AND_RETURN_LOG(status == napi_ok && callback != nullptr,
55         "SaveCallbackReference: creating reference for callback fail");
56     std::shared_ptr<AutoRef> cb = std::make_shared<AutoRef>(env_, callbackRef);
57     availableDeviceChangeCbList_.push_back({cb, usage});
58     AUDIO_INFO_LOG("SaveRoutingAvailbleDeviceChange callback ref success, usage [%{public}d], list size [%{public}zu]",
59         usage, availableDeviceChangeCbList_.size());
60 }
61 
RemoveRoutingAvailbleDeviceChangeCbRef(napi_env env,napi_value callback)62 void NapiAudioRountingAvailableDeviceChangeCallback::RemoveRoutingAvailbleDeviceChangeCbRef(napi_env env,
63     napi_value callback)
64 {
65     std::lock_guard<std::mutex> lock(mutex_);
66 
67     for (auto it = availableDeviceChangeCbList_.begin(); it != availableDeviceChangeCbList_.end(); ++it) {
68         bool isSameCallback = NapiAudioManagerCallback::IsSameCallback(env_, callback, (*it).first->cb_);
69         if (isSameCallback) {
70             AUDIO_INFO_LOG("RemoveRoutingAvailbleDeviceChangeCbRef: find js callback, delete it");
71             napi_delete_reference(env, (*it).first->cb_);
72             (*it).first->cb_ = nullptr;
73             availableDeviceChangeCbList_.erase(it);
74             return;
75         }
76     }
77     AUDIO_INFO_LOG("RemoveRoutingAvailbleDeviceChangeCbRef: js callback no find");
78 }
79 
RemoveAllRoutinAvailbleDeviceChangeCb()80 void NapiAudioRountingAvailableDeviceChangeCallback::RemoveAllRoutinAvailbleDeviceChangeCb()
81 {
82     std::lock_guard<std::mutex> lock(mutex_);
83     for (auto it = availableDeviceChangeCbList_.begin(); it != availableDeviceChangeCbList_.end(); ++it) {
84         napi_delete_reference(env_, (*it).first->cb_);
85         (*it).first->cb_ = nullptr;
86     }
87     availableDeviceChangeCbList_.clear();
88     AUDIO_INFO_LOG("RemoveAllCallbacks: remove all js callbacks success");
89 }
90 
GetRoutingAvailbleDeviceChangeCbListSize()91 int32_t NapiAudioRountingAvailableDeviceChangeCallback::GetRoutingAvailbleDeviceChangeCbListSize()
92 {
93     std::lock_guard<std::mutex> lock(mutex_);
94     return availableDeviceChangeCbList_.size();
95 }
96 
OnAvailableDeviceChange(const AudioDeviceUsage usage,const DeviceChangeAction & deviceChangeAction)97 void NapiAudioRountingAvailableDeviceChangeCallback::OnAvailableDeviceChange(
98     const AudioDeviceUsage usage, const DeviceChangeAction &deviceChangeAction)
99 {
100     AUDIO_INFO_LOG("OnAvailableDeviceChange:DeviceChangeType: %{public}d, DeviceFlag:%{public}d",
101         deviceChangeAction.type, deviceChangeAction.flag);
102     for (auto it = availableDeviceChangeCbList_.begin(); it != availableDeviceChangeCbList_.end(); it++) {
103         if (usage == (*it).second) {
104             std::unique_ptr<AudioRountingJsCallback> cb = std::make_unique<AudioRountingJsCallback>();
105             cb->callback = (*it).first;
106             cb->callbackName = AVAILABLE_DEVICE_CHANGE_CALLBACK_NAME;
107             cb->deviceChangeAction = deviceChangeAction;
108             OnJsCallbackAvailbleDeviceChange(cb);
109         }
110     }
111 }
112 
WorkAvailbleDeviceChangeDone(uv_work_t * work,int status)113 void NapiAudioRountingAvailableDeviceChangeCallback::WorkAvailbleDeviceChangeDone(uv_work_t *work, int status)
114 {
115     // Js Thread
116     std::shared_ptr<AudioRountingJsCallback> context(
117         static_cast<AudioRountingJsCallback*>(work->data),
118         [work](AudioRountingJsCallback* ptr) {
119             delete ptr;
120             delete work;
121     });
122     CHECK_AND_RETURN_LOG(work != nullptr, "work is nullptr");
123     AudioRountingJsCallback *event = reinterpret_cast<AudioRountingJsCallback *>(work->data);
124     CHECK_AND_RETURN_LOG(event != nullptr, "event is nullptr");
125     std::string request = event->callbackName;
126     CHECK_AND_RETURN_LOG(event->callback != nullptr, "event is nullptr");
127     napi_env env = event->callback->env_;
128     napi_ref callback = event->callback->cb_;
129 
130     napi_handle_scope scope = nullptr;
131     napi_open_handle_scope(env, &scope);
132     CHECK_AND_RETURN_LOG(scope != nullptr, "scope is nullptr");
133     do {
134         CHECK_AND_BREAK_LOG(status != UV_ECANCELED, "%{public}s canceled", request.c_str());
135         napi_value jsCallback = nullptr;
136         napi_status nstatus = napi_get_reference_value(env, callback, &jsCallback);
137         CHECK_AND_BREAK_LOG(nstatus == napi_ok && jsCallback != nullptr, "%{public}s get reference value fail",
138             request.c_str());
139 
140         // Call back function
141         napi_value args[ARGS_ONE] = { nullptr };
142         NapiParamUtils::SetValueDeviceChangeAction(env, event->deviceChangeAction, args[PARAM0]);
143         CHECK_AND_BREAK_LOG(nstatus == napi_ok && args[PARAM0] != nullptr,
144             "%{public}s fail to create DeviceChange callback", request.c_str());
145 
146         const size_t argCount = ARGS_ONE;
147         napi_value result = nullptr;
148         nstatus = napi_call_function(env, nullptr, jsCallback, argCount, args, &result);
149         CHECK_AND_BREAK_LOG(nstatus == napi_ok, "%{public}s fail to call DeviceChange callback", request.c_str());
150     } while (0);
151     napi_close_handle_scope(env, scope);
152 }
153 
OnJsCallbackAvailbleDeviceChange(std::unique_ptr<AudioRountingJsCallback> & jsCb)154 void NapiAudioRountingAvailableDeviceChangeCallback::OnJsCallbackAvailbleDeviceChange(
155     std::unique_ptr<AudioRountingJsCallback> &jsCb)
156 {
157     uv_loop_s *loop = nullptr;
158     napi_get_uv_event_loop(env_, &loop);
159     CHECK_AND_RETURN_LOG(loop != nullptr, "loop is null: No memory");
160 
161     uv_work_t *work = new(std::nothrow) uv_work_t;
162     CHECK_AND_RETURN_LOG(work != nullptr, "OnJsCallbackDeviceChange: No memory");
163 
164     if (jsCb.get() == nullptr) {
165         AUDIO_ERR_LOG("AudioManagerCallbackNapi: OnJsCallbackDeviceChange: jsCb.get() is null");
166         delete work;
167         return;
168     }
169 
170     work->data = reinterpret_cast<void *>(jsCb.get());
171 
172     int ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) {},
173         WorkAvailbleDeviceChangeDone, uv_qos_default);
174     if (ret != 0) {
175         AUDIO_ERR_LOG("Failed to execute libuv work queue");
176         delete work;
177     } else {
178         jsCb.release();
179     }
180 }
181 } // namespace AudioStandard
182 } // namespace OHOS