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 
16 #ifndef AUDIO_ROUTING_AVAILABLE_DEVICECHANGE_CALLBACK_NAPI_H
17 #define AUDIO_ROUTING_AVAILABLE_DEVICECHANGE_CALLBACK_NAPI_H
18 
19 #include <uv.h>
20 #include "napi/native_api.h"
21 #include "napi/native_node_api.h"
22 #include "napi_async_work.h"
23 #include "audio_system_manager.h"
24 
25 namespace OHOS {
26 namespace AudioStandard {
27 const std::string AVAILABLE_DEVICE_CHANGE_CALLBACK_NAME = "availableDeviceChange";
28 
29 class NapiAudioRountingAvailableDeviceChangeCallback : public AudioManagerAvailableDeviceChangeCallback {
30 public:
31     explicit NapiAudioRountingAvailableDeviceChangeCallback(napi_env env);
32     virtual ~NapiAudioRountingAvailableDeviceChangeCallback();
33     void SaveCallbackReference(const std::string &callbackName, napi_value callback);
34     void OnAvailableDeviceChange(const AudioDeviceUsage usage, const DeviceChangeAction &deviceChangeAction) override;
35 
36     void SaveRoutingAvailbleDeviceChangeCbRef(AudioDeviceUsage usage, napi_value callback);
37     void RemoveRoutingAvailbleDeviceChangeCbRef(napi_env env, napi_value callback);
38     void RemoveAllRoutinAvailbleDeviceChangeCb();
39     int32_t GetRoutingAvailbleDeviceChangeCbListSize();
40 
41 private:
42     struct AudioRountingJsCallback {
43         std::shared_ptr<AutoRef> callback = nullptr;
44         std::string callbackName = "unknown";
45         DeviceChangeAction deviceChangeAction;
46     };
47 
48     void OnJsCallbackAvailbleDeviceChange(std::unique_ptr<AudioRountingJsCallback> &jsCb);
49     static void WorkAvailbleDeviceChangeDone(uv_work_t *work, int status);
50 
51     std::mutex mutex_;
52     napi_env env_ = nullptr;
53     std::shared_ptr<AutoRef> deviceChangeCallback_ = nullptr;
54     std::list<std::pair<std::shared_ptr<AutoRef>, AudioDeviceUsage>> availableDeviceChangeCbList_;
55 };
56 } // namespace AudioStandard
57 } // namespace OHOS
58 #endif /* AUDIO_ROUTING_AVAILABLE_DEVICECHANGE_CALLBACK_NAPI_H */