1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "avrcp_service.h"
18 
19 #include <base/functional/bind.h>
20 #include <base/task/cancelable_task_tracker.h>
21 #include <base/threading/thread.h>
22 #include <bluetooth/log.h>
23 #include <com_android_bluetooth_flags.h>
24 #include <stdio.h>
25 
26 #include <cstddef>
27 #include <cstdint>
28 #include <memory>
29 #include <mutex>
30 #include <ostream>
31 #include <sstream>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 #include "bta/sys/bta_sys.h"
37 #include "btif/include/btif_av.h"
38 #include "btif/include/btif_common.h"
39 #include "hardware/avrcp/avrcp.h"
40 #include "hardware/avrcp/avrcp_common.h"
41 #include "internal_include/bt_target.h"
42 #include "osi/include/osi.h"
43 #include "profile/avrcp/avrcp_config.h"
44 #include "profile/avrcp/avrcp_internal.h"
45 #include "profile/avrcp/avrcp_sdp_records.h"
46 #include "profile/avrcp/avrcp_sdp_service.h"
47 #include "profile/avrcp/device.h"
48 #include "stack/include/a2dp_api.h"
49 #include "stack/include/avct_api.h"
50 #include "stack/include/avrc_api.h"
51 #include "stack/include/avrc_defs.h"
52 #include "stack/include/bt_hdr.h"
53 #include "stack/include/bt_uuid16.h"
54 #include "stack/include/main_thread.h"
55 #include "stack/include/sdp_api.h"
56 #include "stack/include/sdp_callback.h"
57 #include "stack/include/sdpdefs.h"
58 #include "stack/sdp/sdp_discovery_db.h"
59 #include "types/bluetooth/uuid.h"
60 #include "types/raw_address.h"
61 
62 using bluetooth::legacy::stack::sdp::get_legacy_stack_sdp_api;
63 using namespace bluetooth::avrcp;
64 
65 namespace bluetooth {
66 namespace avrcp {
67 // Static variables and interface definitions
68 AvrcpService* AvrcpService::instance_ = nullptr;
69 AvrcpService::ServiceInterfaceImpl* AvrcpService::service_interface_ = nullptr;
70 
71 class A2dpInterfaceImpl : public A2dpInterface {
active_peer()72   RawAddress active_peer() override { return btif_av_source_active_peer(); }
73 
is_peer_in_silence_mode(const RawAddress & peer_address)74   bool is_peer_in_silence_mode(const RawAddress& peer_address) override {
75     return btif_av_is_peer_silenced(peer_address);
76   }
77 
connect_audio_sink_delayed(uint8_t handle,const RawAddress & peer_address)78   void connect_audio_sink_delayed(uint8_t handle, const RawAddress& peer_address) override {
79     btif_av_connect_sink_delayed(handle, peer_address);
80   }
81 
find_audio_sink_service(const RawAddress & peer_address,tA2DP_FIND_CBACK p_cback)82   uint16_t find_audio_sink_service(const RawAddress& peer_address,
83                                    tA2DP_FIND_CBACK p_cback) override {
84     uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST,
85                             ATTR_ID_SUPPORTED_FEATURES};
86 
87     tA2DP_SDP_DB_PARAMS db_params = {
88             .db_len = BT_DEFAULT_BUFFER_SIZE,
89             .num_attr = ARRAY_SIZE(attr_list),
90             .p_attrs = attr_list,
91     };
92 
93     return A2DP_FindService(UUID_SERVCLASS_AUDIO_SINK, peer_address, &db_params, p_cback);
94   }
95 } a2dp_interface_;
96 
97 class AvrcpInterfaceImpl : public AvrcpInterface {
98 public:
GetAvrcpControlVersion()99   uint16_t GetAvrcpControlVersion() { return AVRC_GetControlProfileVersion(); }
100 
GetAvrcpVersion()101   uint16_t GetAvrcpVersion() { return AVRC_GetProfileVersion(); }
102 
AddRecord(uint16_t service_uuid,const char * p_service_name,const char * p_provider_name,uint16_t categories,uint32_t sdp_handle,bool browse_supported,uint16_t profile_version,uint16_t cover_art_psm)103   uint16_t AddRecord(uint16_t service_uuid, const char* p_service_name, const char* p_provider_name,
104                      uint16_t categories, uint32_t sdp_handle, bool browse_supported,
105                      uint16_t profile_version, uint16_t cover_art_psm) override {
106     return AVRC_AddRecord(service_uuid, p_service_name, p_provider_name, categories, sdp_handle,
107                           browse_supported, profile_version, cover_art_psm);
108   }
109 
RemoveRecord(uint32_t sdp_handle)110   uint16_t RemoveRecord(uint32_t sdp_handle) { return AVRC_RemoveRecord(sdp_handle); }
111 
FindService(uint16_t service_uuid,const RawAddress & bd_addr,tAVRC_SDP_DB_PARAMS * p_db,tAVRC_FIND_CBACK p_cback)112   uint16_t FindService(uint16_t service_uuid, const RawAddress& bd_addr, tAVRC_SDP_DB_PARAMS* p_db,
113                        tAVRC_FIND_CBACK p_cback) override {
114     return AVRC_FindService(service_uuid, bd_addr, p_db, p_cback);
115   }
116 
Open(uint8_t * p_handle,tAVRC_CONN_CB * p_ccb,const RawAddress & bd_addr)117   uint16_t Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, const RawAddress& bd_addr) override {
118     return AVRC_Open(p_handle, p_ccb, bd_addr);
119   }
120 
OpenBrowse(uint8_t handle,tAVCT_ROLE conn_role)121   uint16_t OpenBrowse(uint8_t handle, tAVCT_ROLE conn_role) override {
122     return AVRC_OpenBrowse(handle, conn_role);
123   }
124 
GetPeerMtu(uint8_t handle)125   uint16_t GetPeerMtu(uint8_t handle) override { return AVCT_GetPeerMtu(handle); }
126 
GetBrowseMtu(uint8_t handle)127   uint16_t GetBrowseMtu(uint8_t handle) override { return AVCT_GetBrowseMtu(handle); }
128 
Close(uint8_t handle)129   uint16_t Close(uint8_t handle) override { return AVRC_Close(handle); }
130 
CloseBrowse(uint8_t handle)131   uint16_t CloseBrowse(uint8_t handle) override { return AVRC_CloseBrowse(handle); }
132 
MsgReq(uint8_t handle,uint8_t label,uint8_t ctype,BT_HDR * p_pkt)133   uint16_t MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, BT_HDR* p_pkt) override {
134     return AVRC_MsgReq(handle, label, ctype, p_pkt, true);
135   }
136 
SaveControllerVersion(const RawAddress & bdaddr,uint16_t version)137   void SaveControllerVersion(const RawAddress& bdaddr, uint16_t version) override {
138     AVRC_SaveControllerVersion(bdaddr, version);
139   }
140 } avrcp_interface_;
141 
142 class SdpInterfaceImpl : public SdpInterface {
143 public:
InitDiscoveryDb(tSDP_DISCOVERY_DB * a,uint32_t b,uint16_t c,const bluetooth::Uuid * d,uint16_t e,uint16_t * f)144   bool InitDiscoveryDb(tSDP_DISCOVERY_DB* a, uint32_t b, uint16_t c, const bluetooth::Uuid* d,
145                        uint16_t e, uint16_t* f) override {
146     return get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(a, b, c, d, e, f);
147   }
148 
ServiceSearchAttributeRequest(const RawAddress & a,tSDP_DISCOVERY_DB * b,tSDP_DISC_CMPL_CB * c)149   bool ServiceSearchAttributeRequest(const RawAddress& a, tSDP_DISCOVERY_DB* b,
150                                      tSDP_DISC_CMPL_CB* c) override {
151     return get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest(a, b, c);
152   }
153 
FindServiceInDb(tSDP_DISCOVERY_DB * a,uint16_t b,t_sdp_disc_rec * c)154   tSDP_DISC_REC* FindServiceInDb(tSDP_DISCOVERY_DB* a, uint16_t b, t_sdp_disc_rec* c) override {
155     return get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(a, b, c);
156   }
157 
FindAttributeInRec(t_sdp_disc_rec * a,uint16_t b)158   tSDP_DISC_ATTR* FindAttributeInRec(t_sdp_disc_rec* a, uint16_t b) override {
159     return get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(a, b);
160   }
161 
FindProfileVersionInRec(t_sdp_disc_rec * a,uint16_t b,uint16_t * c)162   bool FindProfileVersionInRec(t_sdp_disc_rec* a, uint16_t b, uint16_t* c) override {
163     return get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(a, b, c);
164   }
165 } sdp_interface_;
166 
167 // A wrapper class for the media callbacks that handles thread
168 // switching/synchronization so the devices don't have to worry about it.
169 class MediaInterfaceWrapper : public MediaInterface {
170 public:
MediaInterfaceWrapper(MediaInterface * cb)171   explicit MediaInterfaceWrapper(MediaInterface* cb) : wrapped_(cb) {}
172 
SendKeyEvent(uint8_t key,KeyState state)173   void SendKeyEvent(uint8_t key, KeyState state) override {
174     do_in_jni_thread(
175             base::Bind(&MediaInterface::SendKeyEvent, base::Unretained(wrapped_), key, state));
176   }
177 
GetSongInfo(SongInfoCallback info_cb)178   void GetSongInfo(SongInfoCallback info_cb) override {
179     auto cb_lambda = [](SongInfoCallback cb, SongInfo data) {
180       do_in_main_thread(base::BindOnce(cb, data));
181     };
182 
183     auto bound_cb = base::Bind(cb_lambda, info_cb);
184 
185     do_in_jni_thread(
186             base::Bind(&MediaInterface::GetSongInfo, base::Unretained(wrapped_), bound_cb));
187   }
188 
GetPlayStatus(PlayStatusCallback status_cb)189   void GetPlayStatus(PlayStatusCallback status_cb) override {
190     auto cb_lambda = [](PlayStatusCallback cb, PlayStatus status) {
191       do_in_main_thread(base::BindOnce(cb, status));
192     };
193 
194     auto bound_cb = base::Bind(cb_lambda, status_cb);
195 
196     do_in_jni_thread(
197             base::Bind(&MediaInterface::GetPlayStatus, base::Unretained(wrapped_), bound_cb));
198   }
199 
GetNowPlayingList(NowPlayingCallback now_playing_cb)200   void GetNowPlayingList(NowPlayingCallback now_playing_cb) override {
201     auto cb_lambda = [](NowPlayingCallback cb, std::string curr_media_id,
202                         std::vector<SongInfo> song_list) {
203       do_in_main_thread(base::BindOnce(cb, curr_media_id, std::move(song_list)));
204     };
205 
206     auto bound_cb = base::Bind(cb_lambda, now_playing_cb);
207 
208     do_in_jni_thread(
209             base::Bind(&MediaInterface::GetNowPlayingList, base::Unretained(wrapped_), bound_cb));
210   }
211 
GetMediaPlayerList(MediaListCallback list_cb)212   void GetMediaPlayerList(MediaListCallback list_cb) override {
213     auto cb_lambda = [](MediaListCallback cb, uint16_t curr_player,
214                         std::vector<MediaPlayerInfo> player_list) {
215       do_in_main_thread(base::BindOnce(cb, curr_player, std::move(player_list)));
216     };
217 
218     auto bound_cb = base::Bind(cb_lambda, list_cb);
219 
220     do_in_jni_thread(
221             base::Bind(&MediaInterface::GetMediaPlayerList, base::Unretained(wrapped_), bound_cb));
222   }
223 
GetFolderItems(uint16_t player_id,std::string media_id,FolderItemsCallback folder_cb)224   void GetFolderItems(uint16_t player_id, std::string media_id,
225                       FolderItemsCallback folder_cb) override {
226     auto cb_lambda = [](FolderItemsCallback cb, std::vector<ListItem> item_list) {
227       do_in_main_thread(base::BindOnce(cb, std::move(item_list)));
228     };
229 
230     auto bound_cb = base::Bind(cb_lambda, folder_cb);
231 
232     do_in_jni_thread(base::Bind(&MediaInterface::GetFolderItems, base::Unretained(wrapped_),
233                                 player_id, media_id, bound_cb));
234   }
235 
GetAddressedPlayer(GetAddressedPlayerCallback addressed_cb)236   void GetAddressedPlayer(GetAddressedPlayerCallback addressed_cb) override {
237     auto cb_lambda = [](GetAddressedPlayerCallback cb, uint16_t addressed_player) {
238       do_in_main_thread(base::BindOnce(cb, addressed_player));
239     };
240 
241     auto bound_cb = base::Bind(cb_lambda, addressed_cb);
242 
243     do_in_jni_thread(
244             base::Bind(&MediaInterface::GetAddressedPlayer, base::Unretained(wrapped_), bound_cb));
245   }
246 
SetBrowsedPlayer(uint16_t player_id,SetBrowsedPlayerCallback browse_cb)247   void SetBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCallback browse_cb) override {
248     auto cb_lambda = [](SetBrowsedPlayerCallback cb, bool success, std::string root_id,
249                         uint32_t num_items) {
250       do_in_main_thread(base::BindOnce(cb, success, root_id, num_items));
251     };
252 
253     auto bound_cb = base::Bind(cb_lambda, browse_cb);
254 
255     do_in_jni_thread(base::Bind(&MediaInterface::SetBrowsedPlayer, base::Unretained(wrapped_),
256                                 player_id, bound_cb));
257   }
258 
SetAddressedPlayer(uint16_t player_id,SetAddressedPlayerCallback addressed_cb)259   void SetAddressedPlayer(uint16_t player_id, SetAddressedPlayerCallback addressed_cb) override {
260     auto cb_lambda = [](SetAddressedPlayerCallback cb, uint16_t new_player) {
261       do_in_main_thread(base::BindOnce(cb, new_player));
262     };
263 
264     auto bound_cb = base::Bind(cb_lambda, addressed_cb);
265 
266     do_in_jni_thread(base::Bind(&MediaInterface::SetAddressedPlayer, base::Unretained(wrapped_),
267                                 player_id, bound_cb));
268   }
269 
PlayItem(uint16_t player_id,bool now_playing,std::string media_id)270   void PlayItem(uint16_t player_id, bool now_playing, std::string media_id) override {
271     do_in_jni_thread(base::Bind(&MediaInterface::PlayItem, base::Unretained(wrapped_), player_id,
272                                 now_playing, media_id));
273   }
274 
SetActiveDevice(const RawAddress & address)275   void SetActiveDevice(const RawAddress& address) override {
276     do_in_jni_thread(
277             base::Bind(&MediaInterface::SetActiveDevice, base::Unretained(wrapped_), address));
278   }
279 
RegisterUpdateCallback(MediaCallbacks * callback)280   void RegisterUpdateCallback(MediaCallbacks* callback) override {
281     wrapped_->RegisterUpdateCallback(callback);
282   }
283 
UnregisterUpdateCallback(MediaCallbacks * callback)284   void UnregisterUpdateCallback(MediaCallbacks* callback) override {
285     wrapped_->UnregisterUpdateCallback(callback);
286   }
287 
288 private:
289   MediaInterface* wrapped_;
290 };
291 
292 // A wrapper class for the media callbacks that handles thread
293 // switching/synchronization so the devices don't have to worry about it.
294 class VolumeInterfaceWrapper : public VolumeInterface {
295 public:
VolumeInterfaceWrapper(VolumeInterface * interface)296   explicit VolumeInterfaceWrapper(VolumeInterface* interface) : wrapped_(interface) {}
297 
DeviceConnected(const RawAddress & bdaddr)298   void DeviceConnected(const RawAddress& bdaddr) override {
299     do_in_jni_thread(base::Bind(static_cast<void (VolumeInterface::*)(const RawAddress&)>(
300                                         &VolumeInterface::DeviceConnected),
301                                 base::Unretained(wrapped_), bdaddr));
302   }
303 
DeviceConnected(const RawAddress & bdaddr,VolumeChangedCb cb)304   void DeviceConnected(const RawAddress& bdaddr, VolumeChangedCb cb) override {
305     auto cb_lambda = [](VolumeChangedCb cb, int8_t volume) {
306       do_in_main_thread(base::BindOnce(cb, volume));
307     };
308 
309     auto bound_cb = base::Bind(cb_lambda, cb);
310 
311     do_in_jni_thread(
312             base::Bind(static_cast<void (VolumeInterface::*)(const RawAddress&, VolumeChangedCb)>(
313                                &VolumeInterface::DeviceConnected),
314                        base::Unretained(wrapped_), bdaddr, bound_cb));
315   }
316 
DeviceDisconnected(const RawAddress & bdaddr)317   void DeviceDisconnected(const RawAddress& bdaddr) override {
318     do_in_jni_thread(
319             base::Bind(&VolumeInterface::DeviceDisconnected, base::Unretained(wrapped_), bdaddr));
320   }
321 
SetVolume(int8_t volume)322   void SetVolume(int8_t volume) override {
323     do_in_jni_thread(base::Bind(&VolumeInterface::SetVolume, base::Unretained(wrapped_), volume));
324   }
325 
326 private:
327   VolumeInterface* wrapped_;
328 };
329 
330 // A wrapper class for the media callbacks that handles thread
331 // switching/synchronization so the devices don't have to worry about it.
332 class PlayerSettingsInterfaceWrapper : public PlayerSettingsInterface {
333 public:
PlayerSettingsInterfaceWrapper(PlayerSettingsInterface * interface)334   explicit PlayerSettingsInterfaceWrapper(PlayerSettingsInterface* interface)
335       : wrapped_(interface) {}
336 
ListPlayerSettings(ListPlayerSettingsCallback cb)337   void ListPlayerSettings(ListPlayerSettingsCallback cb) override {
338     auto cb_lambda = [](const ListPlayerSettingsCallback& cb,
339                         std::vector<PlayerAttribute> attributes) {
340       do_in_main_thread(base::BindOnce(cb, std::move(attributes)));
341     };
342 
343     auto bound_cb = base::Bind(cb_lambda, cb);
344 
345     do_in_jni_thread(base::Bind(&PlayerSettingsInterface::ListPlayerSettings,
346                                 base::Unretained(wrapped_), bound_cb));
347   }
348 
ListPlayerSettingValues(PlayerAttribute setting,ListPlayerSettingValuesCallback cb)349   void ListPlayerSettingValues(PlayerAttribute setting,
350                                ListPlayerSettingValuesCallback cb) override {
351     auto cb_lambda = [](const ListPlayerSettingValuesCallback& cb, PlayerAttribute setting,
352                         std::vector<uint8_t> values) {
353       do_in_main_thread(base::BindOnce(cb, setting, std::move(values)));
354     };
355 
356     auto bound_cb = base::Bind(cb_lambda, cb);
357 
358     do_in_jni_thread(base::Bind(&PlayerSettingsInterface::ListPlayerSettingValues,
359                                 base::Unretained(wrapped_), setting, bound_cb));
360   }
361 
GetCurrentPlayerSettingValue(std::vector<PlayerAttribute> attributes,GetCurrentPlayerSettingValueCallback cb)362   void GetCurrentPlayerSettingValue(std::vector<PlayerAttribute> attributes,
363                                     GetCurrentPlayerSettingValueCallback cb) override {
364     auto cb_lambda = [](const GetCurrentPlayerSettingValueCallback& cb,
365                         std::vector<PlayerAttribute> attributes, std::vector<uint8_t> values) {
366       do_in_main_thread(base::BindOnce(cb, std::move(attributes), std::move(values)));
367     };
368 
369     auto bound_cb = base::Bind(cb_lambda, cb);
370 
371     do_in_jni_thread(base::Bind(&PlayerSettingsInterface::GetCurrentPlayerSettingValue,
372                                 base::Unretained(wrapped_), std::move(attributes), bound_cb));
373   }
374 
SetPlayerSettings(std::vector<PlayerAttribute> attributes,std::vector<uint8_t> values,SetPlayerSettingValueCallback cb)375   void SetPlayerSettings(std::vector<PlayerAttribute> attributes, std::vector<uint8_t> values,
376                          SetPlayerSettingValueCallback cb) override {
377     auto cb_lambda = [](const SetPlayerSettingValueCallback& cb, bool success) {
378       do_in_main_thread(base::BindOnce(cb, success));
379     };
380 
381     auto bound_cb = base::Bind(cb_lambda, cb);
382 
383     do_in_jni_thread(base::Bind(&PlayerSettingsInterface::SetPlayerSettings,
384                                 base::Unretained(wrapped_), std::move(attributes),
385                                 std::move(values), bound_cb));
386   }
387 
388 private:
389   PlayerSettingsInterface* wrapped_;
390 };
391 
Init(MediaInterface * media_interface,VolumeInterface * volume_interface,PlayerSettingsInterface * player_settings_interface)392 void AvrcpService::Init(MediaInterface* media_interface, VolumeInterface* volume_interface,
393                         PlayerSettingsInterface* player_settings_interface) {
394   log::info("AVRCP Target Service started");
395 
396   profile_version = avrcp_interface_.GetAvrcpVersion();
397 
398   uint16_t supported_features = GetSupportedFeatures(profile_version);
399   if (com::android::bluetooth::flags::avrcp_sdp_records()) {
400     const std::shared_ptr<AvrcpSdpService>& avrcp_sdp_service = AvrcpSdpService::Get();
401     AvrcpSdpRecord target_add_record_request = {UUID_SERVCLASS_AV_REM_CTRL_TARGET,
402                                                 "AV Remote Control Target",
403                                                 "",
404                                                 supported_features,
405                                                 true,
406                                                 profile_version,
407                                                 0};
408     avrcp_sdp_service->AddRecord(target_add_record_request, target_sdp_request_id_);
409     log::verbose("Target request id {}", target_sdp_request_id_);
410     AvrcpSdpRecord control_add_record_request = {UUID_SERVCLASS_AV_REMOTE_CONTROL,
411                                                  "AV Remote Control",
412                                                  "",
413                                                  AVRCP_SUPF_TG_CT,
414                                                  false,
415                                                  avrcp_interface_.GetAvrcpControlVersion(),
416                                                  0};
417     avrcp_sdp_service->AddRecord(control_add_record_request, control_sdp_request_id_);
418     log::verbose("Control request id {}", control_sdp_request_id_);
419   } else {
420     sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
421 
422     avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL,
423                                supported_features, sdp_record_handle, true, profile_version, 0);
424     bta_sys_add_uuid(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
425 
426     ct_sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
427 
428     avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REMOTE_CONTROL, "AV Remote Control", NULL,
429                                AVRCP_SUPF_TG_CT, ct_sdp_record_handle, false,
430                                avrcp_interface_.GetAvrcpControlVersion(), 0);
431     bta_sys_add_uuid(UUID_SERVCLASS_AV_REMOTE_CONTROL);
432   }
433 
434   media_interface_ = new MediaInterfaceWrapper(media_interface);
435   media_interface->RegisterUpdateCallback(instance_);
436 
437   VolumeInterfaceWrapper* wrapped_volume_interface = nullptr;
438   if (volume_interface != nullptr) {
439     wrapped_volume_interface = new VolumeInterfaceWrapper(volume_interface);
440   }
441 
442   volume_interface_ = wrapped_volume_interface;
443 
444   PlayerSettingsInterfaceWrapper* wrapped_player_settings_interface = nullptr;
445   if (player_settings_interface != nullptr) {
446     wrapped_player_settings_interface =
447             new PlayerSettingsInterfaceWrapper(player_settings_interface);
448   }
449 
450   player_settings_interface_ = wrapped_player_settings_interface;
451 
452   ConnectionHandler::Initialize(
453           base::BindRepeating(&AvrcpService::DeviceCallback, base::Unretained(instance_)),
454           &avrcp_interface_, &sdp_interface_, wrapped_volume_interface);
455   connection_handler_ = ConnectionHandler::Get();
456 }
457 
GetSupportedFeatures(uint16_t profile_version)458 uint16_t AvrcpService::GetSupportedFeatures(uint16_t profile_version) {
459   switch (profile_version) {
460     case AVRC_REV_1_6:
461       return AVRCP_SUPF_TG_1_6;
462     case AVRC_REV_1_5:
463       return AVRCP_SUPF_TG_1_5;
464     case AVRC_REV_1_4:
465       return AVRCP_SUPF_TG_1_4;
466     case AVRC_REV_1_3:
467       return AVRCP_SUPF_TG_1_3;
468   }
469   return AVRCP_SUPF_TG_DEFAULT;
470 }
471 
Cleanup()472 void AvrcpService::Cleanup() {
473   log::info("AVRCP Target Service stopped");
474   if (com::android::bluetooth::flags::avrcp_sdp_records()) {
475     const std::shared_ptr<AvrcpSdpService>& avrcp_sdp_service = AvrcpSdpService::Get();
476     avrcp_sdp_service->RemoveRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, target_sdp_request_id_);
477     target_sdp_request_id_ = UNASSIGNED_REQUEST_ID;
478     avrcp_sdp_service->RemoveRecord(UUID_SERVCLASS_AV_REMOTE_CONTROL, control_sdp_request_id_);
479     control_sdp_request_id_ = UNASSIGNED_REQUEST_ID;
480   } else {
481     avrcp_interface_.RemoveRecord(sdp_record_handle);
482     bta_sys_remove_uuid(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
483     sdp_record_handle = -1;
484     avrcp_interface_.RemoveRecord(ct_sdp_record_handle);
485     bta_sys_remove_uuid(UUID_SERVCLASS_AV_REMOTE_CONTROL);
486     ct_sdp_record_handle = -1;
487   }
488   connection_handler_->CleanUp();
489   connection_handler_ = nullptr;
490   if (player_settings_interface_ != nullptr) {
491     delete player_settings_interface_;
492   }
493   if (volume_interface_ != nullptr) {
494     delete volume_interface_;
495   }
496   delete media_interface_;
497 }
498 
RegisterBipServer(int psm)499 void AvrcpService::RegisterBipServer(int psm) {
500   log::info("AVRCP Target Service has registered a BIP OBEX server, psm={}", psm);
501   if (com::android::bluetooth::flags::avrcp_sdp_records()) {
502     const std::shared_ptr<AvrcpSdpService>& avrcp_sdp_service = AvrcpSdpService::Get();
503     avrcp_sdp_service->EnableCovertArt(UUID_SERVCLASS_AV_REM_CTRL_TARGET, psm,
504                                        target_sdp_request_id_);
505   } else {
506     avrcp_interface_.RemoveRecord(sdp_record_handle);
507     uint16_t supported_features =
508             GetSupportedFeatures(profile_version) | AVRC_SUPF_TG_PLAYER_COVER_ART;
509     sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
510     avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL,
511                                supported_features, sdp_record_handle, true, profile_version, psm);
512   }
513 }
514 
UnregisterBipServer()515 void AvrcpService::UnregisterBipServer() {
516   log::info("AVRCP Target Service has unregistered a BIP OBEX server");
517   if (com::android::bluetooth::flags::avrcp_sdp_records()) {
518     const std::shared_ptr<AvrcpSdpService>& avrcp_sdp_service = AvrcpSdpService::Get();
519     avrcp_sdp_service->DisableCovertArt(UUID_SERVCLASS_AV_REM_CTRL_TARGET, target_sdp_request_id_);
520   } else {
521     avrcp_interface_.RemoveRecord(sdp_record_handle);
522     uint16_t supported_features = GetSupportedFeatures(profile_version);
523     sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
524     avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL,
525                                supported_features, sdp_record_handle, true, profile_version, 0);
526   }
527   avrcp_interface_.RemoveRecord(sdp_record_handle);
528   uint16_t supported_features = GetSupportedFeatures(profile_version);
529   sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
530   avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL,
531                              supported_features, sdp_record_handle, true, profile_version, 0);
532 }
533 
Get()534 AvrcpService* AvrcpService::Get() {
535   log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr");
536   return instance_;
537 }
538 
GetServiceInterface()539 ServiceInterface* AvrcpService::GetServiceInterface() {
540   if (service_interface_ == nullptr) {
541     service_interface_ = new ServiceInterfaceImpl();
542   }
543 
544   return service_interface_;
545 }
546 
ConnectDevice(const RawAddress & bdaddr)547 void AvrcpService::ConnectDevice(const RawAddress& bdaddr) {
548   log::info("address={}", bdaddr);
549   if (connection_handler_ == nullptr) {
550     return;
551   }
552   connection_handler_->ConnectDevice(bdaddr);
553 }
554 
DisconnectDevice(const RawAddress & bdaddr)555 void AvrcpService::DisconnectDevice(const RawAddress& bdaddr) {
556   log::info("address={}", bdaddr);
557   if (connection_handler_ == nullptr) {
558     return;
559   }
560   connection_handler_->DisconnectDevice(bdaddr);
561 }
562 
SetBipClientStatus(const RawAddress & bdaddr,bool connected)563 void AvrcpService::SetBipClientStatus(const RawAddress& bdaddr, bool connected) {
564   log::info("address={}, connected={}", bdaddr, connected);
565   if (connection_handler_ == nullptr) {
566     return;
567   }
568   connection_handler_->SetBipClientStatus(bdaddr, connected);
569 }
570 
SendMediaUpdate(bool track_changed,bool play_state,bool queue)571 void AvrcpService::SendMediaUpdate(bool track_changed, bool play_state, bool queue) {
572   log::info("track_changed={} :  play_state={} :  queue={}", track_changed, play_state, queue);
573 
574   if (instance_ == nullptr || instance_->connection_handler_ == nullptr) {
575     return;
576   }
577   // This function may be called on any thread, we need to make sure that the
578   // device update happens on the main thread.
579   for (const auto& device : instance_->connection_handler_->GetListOfDevices()) {
580     do_in_main_thread(base::BindOnce(&Device::SendMediaUpdate, device.get()->Get(), track_changed,
581                                      play_state, queue));
582   }
583 }
584 
SendFolderUpdate(bool available_players,bool addressed_players,bool uids)585 void AvrcpService::SendFolderUpdate(bool available_players, bool addressed_players, bool uids) {
586   log::info("available_players={} :  addressed_players={} :  uids={}", available_players,
587             addressed_players, uids);
588 
589   if (instance_ == nullptr || instance_->connection_handler_ == nullptr) {
590     return;
591   }
592   // Ensure that the update is posted to the correct thread
593   for (const auto& device : instance_->connection_handler_->GetListOfDevices()) {
594     do_in_main_thread(base::BindOnce(&Device::SendFolderUpdate, device.get()->Get(),
595                                      available_players, addressed_players, uids));
596   }
597 }
598 
SendPlayerSettingsChanged(std::vector<PlayerAttribute> attributes,std::vector<uint8_t> values)599 void AvrcpService::SendPlayerSettingsChanged(std::vector<PlayerAttribute> attributes,
600                                              std::vector<uint8_t> values) {
601   if (attributes.size() != values.size()) {
602     log::error("Attributes size {} doesn't match values size {}", attributes.size(), values.size());
603     return;
604   }
605   std::stringstream ss;
606   for (size_t i = 0; i < attributes.size(); i++) {
607     ss << "{attribute=" << attributes.at(i) << " : ";
608     if (attributes.at(i) == PlayerAttribute::REPEAT) {
609       ss << "value=" << (PlayerRepeatValue)values.at(i);
610     } else if (attributes.at(i) == PlayerAttribute::SHUFFLE) {
611       ss << "value=" << (PlayerShuffleValue)values.at(i);
612     } else {
613       ss << "value=" << std::to_string(values.at(i));
614     }
615     ss << ((i + 1 < attributes.size()) ? "}, " : "}");
616   }
617 
618   log::info("{}", ss.str());
619 
620   // Ensure that the update is posted to the correct thread
621   for (const auto& device : instance_->connection_handler_->GetListOfDevices()) {
622     do_in_main_thread(base::BindOnce(&Device::HandlePlayerSettingChanged, device.get()->Get(),
623                                      attributes, values));
624   }
625 }
626 
DeviceCallback(std::shared_ptr<Device> new_device)627 void AvrcpService::DeviceCallback(std::shared_ptr<Device> new_device) {
628   if (new_device == nullptr) {
629     return;
630   }
631 
632   // TODO(apanicke): Pass the interfaces into the connection handler
633   // so that the devices can be created with any interfaces they need.
634   new_device->RegisterInterfaces(media_interface_, &a2dp_interface_, volume_interface_,
635                                  player_settings_interface_);
636 }
637 
638 // Service Interface
Init(MediaInterface * media_interface,VolumeInterface * volume_interface,PlayerSettingsInterface * player_settings_interface)639 void AvrcpService::ServiceInterfaceImpl::Init(MediaInterface* media_interface,
640                                               VolumeInterface* volume_interface,
641                                               PlayerSettingsInterface* player_settings_interface) {
642   std::lock_guard<std::mutex> lock(service_interface_lock_);
643 
644   // TODO(apanicke): This function should block until the service is completely up so
645   // that its possible to call Get() on the service immediately after calling
646   // init without issues.
647 
648   log::assert_that(instance_ == nullptr, "assert failed: instance_ == nullptr");
649   instance_ = new AvrcpService();
650 
651   do_in_main_thread(base::BindOnce(&AvrcpService::Init, base::Unretained(instance_),
652                                    media_interface, volume_interface, player_settings_interface));
653 }
654 
RegisterBipServer(int psm)655 void AvrcpService::ServiceInterfaceImpl::RegisterBipServer(int psm) {
656   std::lock_guard<std::mutex> lock(service_interface_lock_);
657   log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr");
658   do_in_main_thread(
659           base::BindOnce(&AvrcpService::RegisterBipServer, base::Unretained(instance_), psm));
660 }
661 
UnregisterBipServer()662 void AvrcpService::ServiceInterfaceImpl::UnregisterBipServer() {
663   std::lock_guard<std::mutex> lock(service_interface_lock_);
664   log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr");
665   do_in_main_thread(
666           base::BindOnce(&AvrcpService::UnregisterBipServer, base::Unretained(instance_)));
667 }
668 
ConnectDevice(const RawAddress & bdaddr)669 bool AvrcpService::ServiceInterfaceImpl::ConnectDevice(const RawAddress& bdaddr) {
670   std::lock_guard<std::mutex> lock(service_interface_lock_);
671   log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr");
672   do_in_main_thread(
673           base::BindOnce(&AvrcpService::ConnectDevice, base::Unretained(instance_), bdaddr));
674   return true;
675 }
676 
DisconnectDevice(const RawAddress & bdaddr)677 bool AvrcpService::ServiceInterfaceImpl::DisconnectDevice(const RawAddress& bdaddr) {
678   std::lock_guard<std::mutex> lock(service_interface_lock_);
679   log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr");
680   do_in_main_thread(
681           base::BindOnce(&AvrcpService::DisconnectDevice, base::Unretained(instance_), bdaddr));
682   return true;
683 }
684 
IsDeviceConnected(const RawAddress & bdaddr)685 bool AvrcpService::IsDeviceConnected(const RawAddress& bdaddr) {
686   if (instance_ == nullptr) {
687     log::warn("AVRCP Target Service not started");
688     return false;
689   }
690 
691   auto handler = instance_->connection_handler_;
692   if (handler == nullptr) {
693     log::warn("AVRCP connection handler is null");
694     return false;
695   }
696 
697   for (const auto& device : handler->GetListOfDevices()) {
698     if (bdaddr == device->GetAddress()) {
699       return true;
700     }
701   }
702 
703   return false;
704 }
705 
SetBipClientStatus(const RawAddress & bdaddr,bool connected)706 void AvrcpService::ServiceInterfaceImpl::SetBipClientStatus(const RawAddress& bdaddr,
707                                                             bool connected) {
708   std::lock_guard<std::mutex> lock(service_interface_lock_);
709   log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr");
710   do_in_main_thread(base::BindOnce(&AvrcpService::SetBipClientStatus, base::Unretained(instance_),
711                                    bdaddr, connected));
712 }
713 
Cleanup()714 bool AvrcpService::ServiceInterfaceImpl::Cleanup() {
715   std::lock_guard<std::mutex> lock(service_interface_lock_);
716 
717   if (instance_ == nullptr) {
718     return false;
719   }
720 
721   do_in_main_thread(base::BindOnce(&AvrcpService::Cleanup, base::Owned(instance_)));
722 
723   // Setting instance to nullptr here is fine since it will be deleted on the
724   // other thread.
725   instance_ = nullptr;
726 
727   return true;
728 }
729 
DebugDump(int fd)730 void AvrcpService::DebugDump(int fd) {
731   if (instance_ == nullptr) {
732     dprintf(fd, "\nAVRCP Target Service not started\n");
733     return;
734   }
735 
736   auto handler = instance_->connection_handler_;
737   if (handler == nullptr) {
738     dprintf(fd, "\nAVRCP connection handler is null\n");
739     return;
740   }
741 
742   auto device_list = handler->GetListOfDevices();
743   dprintf(fd, "\nAVRCP Target Native Service: %zu devices\n", device_list.size());
744 
745   std::stringstream stream;
746   for (const auto& device : device_list) {
747     stream << "  " << *device << std::endl;
748   }
749 
750   dprintf(fd, "%s", stream.str().c_str());
751 }
752 
753 /** when a2dp connected, btif will start register vol changed, so we need a
754  * interface for it. */
RegisterVolChanged(const RawAddress & bdaddr)755 void AvrcpService::RegisterVolChanged(const RawAddress& bdaddr) {
756   log::info(": address={}", bdaddr);
757 
758   connection_handler_->RegisterVolChanged(bdaddr);
759 }
760 
761 }  // namespace avrcp
762 }  // namespace bluetooth
763