1 /*
2  * Copyright 2020 HIMSA II K/S - www.himsa.com. Represented by EHIMA
3  * - www.ehima.com
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include <memory>
21 #include <utility>  // for std::pair
22 #include <vector>
23 
24 #include "audio_hal_client/audio_hal_client.h"
25 #include "bta_groups.h"
26 #include "gatt_api.h"
27 #include "le_audio_types.h"
28 #include "os/log.h"
29 #include "osi/include/alarm.h"
30 #include "raw_address.h"
31 
32 namespace bluetooth::le_audio {
33 
34 // Maps to BluetoothProfile#LE_AUDIO
35 #define LE_AUDIO_PROFILE_CONSTANT 22
36 
37 /* Enums */
38 enum class DeviceConnectState : uint8_t {
39   /* Initial state */
40   DISCONNECTED,
41   /* When ACL connected, encrypted, CCC registered and initial characteristics
42      read is completed */
43   CONNECTED,
44   /* Used when device is unbonding (RemoveDevice() API is called) */
45   REMOVING,
46   /* Disconnecting */
47   DISCONNECTING,
48   /* Disconnecting for recover - after that we want direct connect to be
49      initiated */
50   DISCONNECTING_AND_RECOVER,
51   /* 2 states below are used when user creates connection. Connect API is
52      called. */
53   CONNECTING_BY_USER,
54   /* Always used after CONNECTING_BY_USER */
55   CONNECTED_BY_USER_GETTING_READY,
56   /* 2 states are used when autoconnect was used for the connection.*/
57   CONNECTING_AUTOCONNECT,
58   /* Always used after CONNECTING_AUTOCONNECT */
59   CONNECTED_AUTOCONNECT_GETTING_READY,
60 };
61 
62 std::ostream& operator<<(std::ostream& os, const DeviceConnectState& state);
63 
64 /* Class definitions */
65 
66 /* LeAudioDevice class represents GATT server device with ASCS, PAC services as
67  * mandatory. Device may contain multiple ASEs, PACs, audio locations. ASEs from
68  * multiple devices may be formed in group.
69  *
70  * Device is created after connection or after storage restoration.
71  *
72  * Active device means that device has at least one ASE which will participate
73  * in any state transition of state machine. ASEs and devices will be activated
74  * according to requested by upper context type.
75  */
76 class LeAudioDevice {
77  public:
78   RawAddress address_;
79 
80   DeviceConnectState connection_state_;
81   bool known_service_handles_;
82   bool notify_connected_after_read_;
83   bool closing_stream_for_disconnection_;
84   bool autoconnect_flag_;
85   uint16_t conn_id_;
86   uint16_t mtu_;
87   bool encrypted_;
88   int group_id_;
89   bool csis_member_;
90   int cis_failed_to_be_established_retry_cnt_;
91   std::bitset<16> tmap_role_;
92 
93   uint8_t audio_directions_;
94   types::AudioLocations snk_audio_locations_;
95   types::AudioLocations src_audio_locations_;
96 
97   types::PublishedAudioCapabilities snk_pacs_;
98   types::PublishedAudioCapabilities src_pacs_;
99 
100   struct types::hdl_pair snk_audio_locations_hdls_;
101   struct types::hdl_pair src_audio_locations_hdls_;
102   struct types::hdl_pair audio_avail_hdls_;
103   struct types::hdl_pair audio_supp_cont_hdls_;
104   std::vector<struct types::ase> ases_;
105   struct types::hdl_pair ctp_hdls_;
106   uint16_t tmap_role_hdl_;
107   std::string model_name_;
108   bool allowlist_flag_;
109   bool acl_asymmetric_;
110   bool acl_phy_update_done_;
111 
112   alarm_t* link_quality_timer;
113   uint16_t link_quality_timer_data;
114 
115   LeAudioDevice(const RawAddress& address_, DeviceConnectState state,
116                 int group_id = bluetooth::groups::kGroupUnknown)
address_(address_)117       : address_(address_),
118         connection_state_(state),
119         known_service_handles_(false),
120         notify_connected_after_read_(false),
121         closing_stream_for_disconnection_(false),
122         autoconnect_flag_(false),
123         conn_id_(GATT_INVALID_CONN_ID),
124         mtu_(0),
125         encrypted_(false),
126         group_id_(group_id),
127         csis_member_(false),
128         cis_failed_to_be_established_retry_cnt_(0),
129         audio_directions_(0),
130         model_name_(""),
131         allowlist_flag_(false),
132         acl_asymmetric_(false),
133         acl_phy_update_done_(false),
134         link_quality_timer(nullptr),
135         dsa_({{DsaMode::DISABLED},
136               types::DataPathState::IDLE,
137               GATT_INVALID_CONN_ID}) {}
138   ~LeAudioDevice(void);
139 
140   void SetConnectionState(DeviceConnectState state);
141   DeviceConnectState GetConnectionState(void);
142   void ClearPACs(void);
143   void RegisterPACs(std::vector<struct types::acs_ac_record>* apr_db,
144                     std::vector<struct types::acs_ac_record>* apr);
145   struct types::ase* GetAseByValHandle(uint16_t val_hdl);
146   int GetAseCount(uint8_t direction);
147   struct types::ase* GetFirstActiveAse(void);
148   struct types::ase* GetFirstActiveAseByDirection(uint8_t direction);
149   struct types::ase* GetNextActiveAseWithSameDirection(
150       struct types::ase* base_ase);
151   struct types::ase* GetNextActiveAseWithDifferentDirection(
152       struct types::ase* base_ase);
153   struct types::ase* GetFirstActiveAseByCisAndDataPathState(
154       types::CisState cis_state, types::DataPathState data_path_state);
155   struct types::ase* GetFirstInactiveAse(uint8_t direction,
156                                          bool reconnect = false);
157   struct types::ase* GetFirstAseWithState(uint8_t direction,
158                                           types::AseState state);
159   struct types::ase* GetNextActiveAse(struct types::ase* ase);
160   struct types::ase* GetAseToMatchBidirectionCis(struct types::ase* ase);
161   types::BidirectionalPair<struct types::ase*> GetAsesByCisConnHdl(
162       uint16_t conn_hdl);
163   types::BidirectionalPair<struct types::ase*> GetAsesByCisId(uint8_t cis_id);
164   bool HaveActiveAse(void);
165   bool HaveAllActiveAsesSameState(types::AseState state);
166   bool HaveAllActiveAsesSameDataPathState(types::DataPathState state) const;
167   bool HaveAnyUnconfiguredAses(void);
168   bool IsReadyToCreateStream(void);
IsReadyToStream(void)169   bool IsReadyToStream(void) const {
170     return HaveAllActiveAsesCisEst() &&
171            HaveAllActiveAsesSameDataPathState(types::DataPathState::CONFIGURED);
172   }
173   bool IsReadyToSuspendStream(void);
174   bool HaveAllActiveAsesCisEst(void) const;
175   bool HaveAnyCisConnected(void);
176   uint8_t GetSupportedAudioChannelCounts(uint8_t direction) const;
177   uint8_t GetPhyBitmask(void) const;
178   uint8_t GetPreferredPhyBitmask(uint8_t preferred_phy) const;
179   bool IsAudioSetConfigurationSupported(
180       const set_configurations::AudioSetConfiguration* audio_set_conf) const;
181   bool ConfigureAses(
182       const set_configurations::AudioSetConfiguration* audio_set_conf,
183       uint8_t group_size, uint8_t direction,
184       types::LeAudioContextType context_type,
185       uint8_t* number_of_already_active_group_ase,
186       types::AudioLocations& group_audio_locations_out,
187       const types::AudioContexts& metadata_context_types,
188       const std::vector<uint8_t>& ccid_lists, bool reuse_cis_id);
189 
190   inline types::AudioContexts GetSupportedContexts(
191       int direction = types::kLeAudioDirectionBoth) const {
192     log::assert_that(direction <= (types::kLeAudioDirectionBoth),
193                      "Invalid direction used.");
194 
195     if (direction < types::kLeAudioDirectionBoth)
196       return supp_contexts_.get(direction);
197     else
198       return types::get_bidirectional(supp_contexts_);
199   }
SetSupportedContexts(types::BidirectionalPair<types::AudioContexts> contexts)200   inline void SetSupportedContexts(
201       types::BidirectionalPair<types::AudioContexts> contexts) {
202     supp_contexts_ = contexts;
203   }
204 
205   inline types::AudioContexts GetAvailableContexts(
206       int direction = types::kLeAudioDirectionBoth) const {
207     log::assert_that(direction <= (types::kLeAudioDirectionBoth),
208                      "Invalid direction used.");
209 
210     if (direction < types::kLeAudioDirectionBoth)
211       return avail_contexts_.get(direction);
212     else
213       return types::get_bidirectional(avail_contexts_);
214   }
215   void SetAvailableContexts(
216       types::BidirectionalPair<types::AudioContexts> cont_val);
217 
218   void DeactivateAllAses(void);
219   bool ActivateConfiguredAses(
220       types::LeAudioContextType context_type,
221       const types::BidirectionalPair<types::AudioContexts>&
222           metadata_context_types,
223       types::BidirectionalPair<std::vector<uint8_t>> ccid_lists);
224   void SetMetadataToAse(struct types::ase* ase,
225                         const types::AudioContexts& metadata_context_types,
226                         const std::vector<uint8_t>& ccid_lists);
227 
228   void PrintDebugState(void);
229   void DumpPacsDebugState(std::stringstream& stream);
230   void Dump(int fd);
231 
232   void DisconnectAcl(void);
233   std::vector<uint8_t> GetMetadata(types::AudioContexts context_type,
234                                    const std::vector<uint8_t>& ccid_list);
235   bool IsMetadataChanged(
236       const types::BidirectionalPair<types::AudioContexts>& context_types,
237       const types::BidirectionalPair<std::vector<uint8_t>>& ccid_lists);
238 
239   void GetDeviceModelName(void);
240   void UpdateDeviceAllowlistFlag(void);
241   DsaModes GetDsaModes(void);
242   types::DataPathState GetDsaDataPathState(void);
243   void SetDsaDataPathState(types::DataPathState state);
244   uint16_t GetDsaCisHandle(void);
245   void SetDsaCisHandle(uint16_t cis_handle);
246 
247  private:
248   types::BidirectionalPair<types::AudioContexts> avail_contexts_;
249   types::BidirectionalPair<types::AudioContexts> supp_contexts_;
250   struct {
251     DsaModes modes;
252     types::DataPathState state;
253     uint16_t cis_handle;
254   } dsa_;
255 
256   static constexpr char kLeAudioDeviceAllowListProp[] =
257       "persist.bluetooth.leaudio.allow_list";
258 
259   void DumpPacsDebugState(std::stringstream& stream,
260                           types::PublishedAudioCapabilities pacs);
261   void ParseHeadtrackingCodec(const struct types::acs_ac_record& pac);
262 };
263 
264 /* LeAudioDevices class represents a wraper helper over all devices in le audio
265  * implementation. It allows to operate on device from a list (vector container)
266  * using determinants like address, connection id etc.
267  */
268 class LeAudioDevices {
269  public:
270   void Add(const RawAddress& address,
271            bluetooth::le_audio::DeviceConnectState state,
272            int group_id = bluetooth::groups::kGroupUnknown);
273   void Remove(const RawAddress& address);
274   LeAudioDevice* FindByAddress(const RawAddress& address) const;
275   std::shared_ptr<LeAudioDevice> GetByAddress(const RawAddress& address) const;
276   LeAudioDevice* FindByConnId(uint16_t conn_id) const;
277   LeAudioDevice* FindByCisConnHdl(uint8_t cig_id, uint16_t conn_hdl) const;
278   void SetInitialGroupAutoconnectState(int group_id, int gatt_if,
279                                        tBTM_BLE_CONN_TYPE reconnection_mode,
280                                        bool current_dev_autoconnect_flag);
281   size_t Size(void) const;
282   void Dump(int fd, int group_id) const;
283   void Cleanup(tGATT_IF client_if);
284 
285  private:
286   std::vector<std::shared_ptr<LeAudioDevice>> leAudioDevices_;
287 };
288 
289 }  // namespace bluetooth::le_audio
290