• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2020 The Android Open Source Project
2 //
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 #pragma once
16 
17 #include <atomic>
18 #include <mutex>
19 #include <vector>
20 
21 // clang-format off
22 #include PATH(device/google/atv/audio_proxy/AUDIO_PROXY_FILE_VERSION/IBusDevice.h)
23 // clang-format on
24 
25 #include <utils/RefBase.h>
26 
27 namespace audio_proxy {
28 namespace service {
29 
30 using ::android::sp;
31 using ::android::hardware::hidl_death_recipient;
32 using ::android::hardware::hidl_string;
33 using ::device::google::atv::audio_proxy::AUDIO_PROXY_CPP_VERSION::IBusDevice;
34 
35 class BusDeviceProvider {
36  public:
37   class Handle : public ::android::RefBase {
38    public:
39     Handle(sp<IBusDevice> device,
40            const hidl_string& address,
41            uint64_t token);
42     ~Handle() override;
43 
44     const sp<IBusDevice>& getDevice() const;
45     const hidl_string& getAddress() const;
46     uint64_t getToken() const;
47     int getStreamCount() const;
48 
49     void onStreamOpen();
50     void onStreamClose();
51 
52    private:
53     const sp<IBusDevice> mDevice;
54     const hidl_string mAddress;
55     const uint64_t mToken;
56     std::atomic<int> mStreamCount = 0;
57   };
58 
59   BusDeviceProvider();
60   ~BusDeviceProvider();
61 
62   // Register bus device under `address`. The device is unregistered when its
63   // process exits.
64   bool add(const hidl_string& address, sp<IBusDevice> device);
65 
66   // Get IBusDevice handle with `address`. Caller should only keep the strong
67   // pointer shortly, a.k.a caller should release the strong pointer as soon as
68   // its function scope exits.
69   sp<Handle> get(const hidl_string& address);
70 
71   // Remove all the added devices.
72   void removeAll();
73 
74  private:
75   class DeathRecipient;
76 
77   friend class DeathRecipient;
78 
79   // Called by DeathRecipient to remove device when the host process exits.
80   sp<Handle> removeByToken(uint64_t token);
81 
82   sp<hidl_death_recipient> mDeathRecipient;
83 
84   std::mutex mDevicesLock;
85 
86   // Use a vector since we don't have too much registered devices.
87   std::vector<sp<Handle>> mBusDevices;
88   uint64_t mNextToken = 0;
89 };
90 
91 }  // namespace service
92 }  // namespace audio_proxy
93