1 /******************************************************************************
2 *
3 * Copyright 2009-2016 Broadcom Corporation
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
19 #define LOG_TAG "bluetooth-a2dp"
20
21 #include "btif/include/btif_av.h"
22
23 #include <android_bluetooth_sysprop.h>
24 #include <base/functional/bind.h>
25 #include <base/strings/stringprintf.h>
26 #include <bluetooth/log.h>
27 #include <com_android_bluetooth_flags.h>
28 #include <frameworks/proto_logging/stats/enums/bluetooth/a2dp/enums.pb.h>
29 #include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
30
31 #include <chrono>
32 #include <cstdint>
33 #include <future>
34 #include <string>
35 #include <vector>
36
37 #include "audio_hal_interface/a2dp_encoding.h"
38 #include "btif/avrcp/avrcp_service.h"
39 #include "btif/include/btif_a2dp.h"
40 #include "btif/include/btif_a2dp_control.h"
41 #include "btif/include/btif_a2dp_sink.h"
42 #include "btif/include/btif_a2dp_source.h"
43 #include "btif/include/btif_av_co.h"
44 #include "btif/include/btif_common.h"
45 #include "btif/include/btif_metrics_logging.h"
46 #include "btif/include/btif_profile_queue.h"
47 #include "btif/include/btif_rc.h"
48 #include "btif/include/btif_util.h"
49 #include "btif/include/stack_manager_t.h"
50 #include "btif_metrics_logging.h"
51 #include "common/state_machine.h"
52 #include "device/include/device_iot_config.h"
53 #include "hardware/bt_av.h"
54 #include "include/hardware/bt_rc.h"
55 #include "internal_include/bt_trace.h"
56 #include "osi/include/alarm.h"
57 #include "osi/include/allocator.h"
58 #include "stack/include/avrc_api.h"
59 #include "stack/include/bt_hdr.h"
60 #include "stack/include/bt_uuid16.h"
61 #include "stack/include/btm_ble_api.h"
62 #include "stack/include/btm_log_history.h"
63 #include "stack/include/main_thread.h"
64 #include "types/raw_address.h"
65
66 #ifdef __ANDROID__
67 #include <android/sysprop/BluetoothProperties.sysprop.h>
68 #endif
69
70 using namespace bluetooth;
71
72 /*****************************************************************************
73 * Constants & Macros
74 *****************************************************************************/
75 static const std::string kBtifAvSourceServiceName = "Advanced Audio Source";
76 static const std::string kBtifAvSinkServiceName = "Advanced Audio Sink";
77 static constexpr int kDefaultMaxConnectedAudioDevices = 1;
78 static constexpr tBTA_AV_HNDL kBtaHandleUnknown = 0;
79
80 namespace {
81 constexpr char kBtmLogHistoryTag[] = "A2DP";
82 }
83
84 /*****************************************************************************
85 * Local type definitions
86 *****************************************************************************/
87
88 typedef struct {
89 int sample_rate;
90 int channel_count;
91 RawAddress peer_address;
92 } btif_av_sink_config_req_t;
93
94 typedef struct {
95 bool use_latency_mode;
96 } btif_av_start_stream_req_t;
97
98 typedef struct {
99 bool is_low_latency;
100 } btif_av_set_latency_req_t;
101
102 /**
103 * BTIF AV events
104 */
105 typedef enum {
106 /* Reuse BTA_AV_XXX_EVT - No need to redefine them here */
107 BTIF_AV_CONNECT_REQ_EVT = BTA_AV_MAX_EVT,
108 BTIF_AV_DISCONNECT_REQ_EVT,
109 BTIF_AV_START_STREAM_REQ_EVT,
110 BTIF_AV_STOP_STREAM_REQ_EVT,
111 BTIF_AV_SUSPEND_STREAM_REQ_EVT,
112 BTIF_AV_SINK_CONFIG_REQ_EVT,
113 BTIF_AV_ACL_DISCONNECTED,
114 BTIF_AV_OFFLOAD_START_REQ_EVT,
115 BTIF_AV_AVRCP_OPEN_EVT,
116 BTIF_AV_AVRCP_CLOSE_EVT,
117 BTIF_AV_AVRCP_REMOTE_PLAY_EVT,
118 BTIF_AV_SET_LATENCY_REQ_EVT,
119 } btif_av_sm_event_t;
120
121 class BtifAvEvent {
122 public:
123 BtifAvEvent(uint32_t event, const void* p_data, size_t data_length);
124 BtifAvEvent(const BtifAvEvent& other);
125 BtifAvEvent() = delete;
126 ~BtifAvEvent();
127 BtifAvEvent& operator=(const BtifAvEvent& other);
128
Event() const129 uint32_t Event() const { return event_; }
Data() const130 void* Data() const { return data_; }
DataLength() const131 size_t DataLength() const { return data_length_; }
132 std::string ToString() const;
133 static std::string EventName(uint32_t event);
134
135 private:
136 void DeepCopy(uint32_t event, const void* p_data, size_t data_length);
137 void DeepFree();
138
139 uint32_t event_;
140 void* data_;
141 size_t data_length_;
142 };
143
144 class BtifAvPeer;
145 static bt_status_t sink_set_active_device(const RawAddress& peer_address);
146
147 static void btif_av_sink_delete_active_peer(void);
148 static void btif_av_source_delete_active_peer(void);
149
150 // Should not need dedicated Suspend state as actual actions are no
151 // different than Open state. Suspend flags are needed however to prevent
152 // media task from trying to restart stream during remote Suspend or while
153 // we are in the process of a local Suspend.
154 class BtifAvStateMachine : public bluetooth::common::StateMachine {
155 public:
156 enum {
157 kStateIdle, // AVDTP disconnected
158 kStateOpening, // Opening AVDTP connection
159 kStateOpened, // AVDTP is in OPEN state
160 kStateStarted, // A2DP stream started
161 kStateClosing, // Closing AVDTP connection
162 };
163
164 class StateIdle : public State {
165 public:
StateIdle(BtifAvStateMachine & sm)166 StateIdle(BtifAvStateMachine& sm)
167 : State(sm, kStateIdle), peer_(sm.Peer()) {}
168 void OnEnter() override;
169 void OnExit() override;
170 bool ProcessEvent(uint32_t event, void* p_data) override;
171
172 private:
173 BtifAvPeer& peer_;
174 };
175
176 class StateOpening : public State {
177 public:
StateOpening(BtifAvStateMachine & sm)178 StateOpening(BtifAvStateMachine& sm)
179 : State(sm, kStateOpening), peer_(sm.Peer()) {}
180 void OnEnter() override;
181 void OnExit() override;
182 bool ProcessEvent(uint32_t event, void* p_data) override;
183
184 private:
185 BtifAvPeer& peer_;
186 };
187
188 class StateOpened : public State {
189 public:
StateOpened(BtifAvStateMachine & sm)190 StateOpened(BtifAvStateMachine& sm)
191 : State(sm, kStateOpened), peer_(sm.Peer()) {}
192 void OnEnter() override;
193 void OnExit() override;
194 bool ProcessEvent(uint32_t event, void* p_data) override;
195
196 private:
197 BtifAvPeer& peer_;
198 };
199
200 class StateStarted : public State {
201 public:
StateStarted(BtifAvStateMachine & sm)202 StateStarted(BtifAvStateMachine& sm)
203 : State(sm, kStateStarted), peer_(sm.Peer()) {}
204 void OnEnter() override;
205 void OnExit() override;
206 bool ProcessEvent(uint32_t event, void* p_data) override;
207
208 private:
209 BtifAvPeer& peer_;
210 };
211
212 class StateClosing : public State {
213 public:
StateClosing(BtifAvStateMachine & sm)214 StateClosing(BtifAvStateMachine& sm)
215 : State(sm, kStateClosing), peer_(sm.Peer()) {}
216 void OnEnter() override;
217 void OnExit() override;
218 bool ProcessEvent(uint32_t event, void* p_data) override;
219
220 private:
221 BtifAvPeer& peer_;
222 };
223
BtifAvStateMachine(BtifAvPeer & btif_av_peer)224 BtifAvStateMachine(BtifAvPeer& btif_av_peer) : peer_(btif_av_peer) {
225 state_idle_ = new StateIdle(*this);
226 state_opening_ = new StateOpening(*this);
227 state_opened_ = new StateOpened(*this);
228 state_started_ = new StateStarted(*this);
229 state_closing_ = new StateClosing(*this);
230
231 AddState(state_idle_);
232 AddState(state_opening_);
233 AddState(state_opened_);
234 AddState(state_started_);
235 AddState(state_closing_);
236 SetInitialState(state_idle_);
237 }
238
Peer()239 BtifAvPeer& Peer() { return peer_; }
240
241 private:
242 BtifAvPeer& peer_;
243 StateIdle* state_idle_;
244 StateOpening* state_opening_;
245 StateOpened* state_opened_;
246 StateStarted* state_started_;
247 StateClosing* state_closing_;
248 };
249
250 class BtifAvPeer {
251 public:
252 enum {
253 kFlagLocalSuspendPending = 0x1,
254 kFlagRemoteSuspend = 0x2,
255 kFlagPendingStart = 0x4,
256 kFlagPendingStop = 0x8,
257 };
258 static constexpr uint64_t kTimeoutAvOpenOnRcMs = 2 * 1000; // 2s
259
260 BtifAvPeer(const RawAddress& peer_address, uint8_t peer_sep,
261 tBTA_AV_HNDL bta_handle, uint8_t peer_id);
262 ~BtifAvPeer();
263
264 bt_status_t Init();
265 void Cleanup();
266
267 /**
268 * Check whether the peer can be deleted.
269 *
270 * @return true if the pair can be deleted, otherwise false
271 */
272 bool CanBeDeleted() const;
273
274 /**
275 * Check whether the peer is the active one.
276 *
277 * @return true if this peer is the active one
278 */
IsActivePeer() const279 bool IsActivePeer() const { return (PeerAddress() == ActivePeerAddress()); }
280
281 /**
282 * Get the address of the active peer.
283 *
284 * @return the address of the active peer
285 */
286 const RawAddress& ActivePeerAddress() const;
287
PeerAddress() const288 const RawAddress& PeerAddress() const { return peer_address_; }
IsSource() const289 bool IsSource() const { return (peer_sep_ == AVDT_TSEP_SRC); }
IsSink() const290 bool IsSink() const { return (peer_sep_ == AVDT_TSEP_SNK); }
PeerSep() const291 uint8_t PeerSep() const { return peer_sep_; }
SetSep(uint8_t sep_type)292 void SetSep(uint8_t sep_type) { peer_sep_ = sep_type; }
293 /**
294 * Get the local device's Service Class UUID
295 *
296 * @return the local device's Service Class UUID: UUID_SERVCLASS_AUDIO_SOURCE
297 * or UUID_SERVCLASS_AUDIO_SINK
298 */
LocalUuidServiceClass() const299 uint16_t LocalUuidServiceClass() const {
300 return (IsSink() ? UUID_SERVCLASS_AUDIO_SOURCE : UUID_SERVCLASS_AUDIO_SINK);
301 }
BtaHandle() const302 tBTA_AV_HNDL BtaHandle() const { return bta_handle_; }
SetBtaHandle(tBTA_AV_HNDL bta_handle)303 void SetBtaHandle(tBTA_AV_HNDL bta_handle) { bta_handle_ = bta_handle; }
PeerId() const304 uint8_t PeerId() const { return peer_id_; }
305
StateMachine()306 BtifAvStateMachine& StateMachine() { return state_machine_; }
StateMachine() const307 const BtifAvStateMachine& StateMachine() const { return state_machine_; }
AvOpenOnRcTimer()308 alarm_t* AvOpenOnRcTimer() { return av_open_on_rc_timer_; }
AvOpenOnRcTimer() const309 const alarm_t* AvOpenOnRcTimer() const { return av_open_on_rc_timer_; }
310
SetEdr(tBTA_AV_EDR edr)311 void SetEdr(tBTA_AV_EDR edr) { edr_ = edr; }
IsEdr() const312 bool IsEdr() const { return (edr_ != 0); }
Is3Mbps() const313 bool Is3Mbps() const { return ((edr_ & BTA_AV_EDR_3MBPS) != 0); }
314
315 bool IsConnected() const;
316 bool IsStreaming() const;
IsInSilenceMode() const317 bool IsInSilenceMode() const { return is_silenced_; }
318
SetSilence(bool silence)319 void SetSilence(bool silence) { is_silenced_ = silence; }
320
321 // AVDTP delay reporting in 1/10 milliseconds
SetDelayReport(uint16_t delay)322 void SetDelayReport(uint16_t delay) { delay_report_ = delay; }
GetDelayReport() const323 uint16_t GetDelayReport() const { return delay_report_; }
324
SetMandatoryCodecPreferred(bool preferred)325 void SetMandatoryCodecPreferred(bool preferred) {
326 mandatory_codec_preferred_ = preferred;
327 }
IsMandatoryCodecPreferred() const328 bool IsMandatoryCodecPreferred() const { return mandatory_codec_preferred_; }
329
330 /**
331 * Check whether any of the flags specified by the bitlags mask is set.
332 *
333 * @param bitflags_mask the bitflags to check
334 * @return true if any of the flags to check is set, otherwise false.
335 */
CheckFlags(uint8_t bitflags_mask) const336 bool CheckFlags(uint8_t bitflags_mask) const {
337 return ((flags_ & bitflags_mask) != 0);
338 }
339
340 /**
341 * Set only the flags as specified by the bitflags mask.
342 *
343 * @param bitflags_mask the bitflags to set
344 */
SetFlags(uint8_t bitflags_mask)345 void SetFlags(uint8_t bitflags_mask) { flags_ |= bitflags_mask; }
346
347 /**
348 * Clear only the flags as specified by the bitflags mask.
349 *
350 * @param bitflags_mask the bitflags to clear
351 */
ClearFlags(uint8_t bitflags_mask)352 void ClearFlags(uint8_t bitflags_mask) { flags_ &= ~bitflags_mask; }
353
354 /**
355 * Clear all flags.
356 */
ClearAllFlags()357 void ClearAllFlags() { flags_ = 0; }
358
359 /**
360 * Get a string representation of the flags that are set.
361 */
362 std::string FlagsToString() const;
363
SelfInitiatedConnection() const364 bool SelfInitiatedConnection() const { return self_initiated_connection_; }
SetSelfInitiatedConnection(bool v)365 void SetSelfInitiatedConnection(bool v) { self_initiated_connection_ = v; }
366
UseLatencyMode() const367 bool UseLatencyMode() const { return use_latency_mode_; }
SetUseLatencyMode(bool use_latency_mode)368 void SetUseLatencyMode(bool use_latency_mode) {
369 use_latency_mode_ = use_latency_mode;
370 }
371
372 private:
373 const RawAddress peer_address_;
374 uint8_t peer_sep_; // SEP type of peer device
375 tBTA_AV_HNDL bta_handle_;
376 const uint8_t peer_id_;
377 BtifAvStateMachine state_machine_;
378 alarm_t* av_open_on_rc_timer_;
379 tBTA_AV_EDR edr_;
380 uint8_t flags_;
381 bool self_initiated_connection_;
382 bool is_silenced_;
383 uint16_t delay_report_;
384 bool mandatory_codec_preferred_ = false;
385 bool use_latency_mode_ = false;
386 };
387
388 class BtifAvSource {
389 public:
390 // The PeerId is used as AppId for BTA_AvRegister() purpose
391 static constexpr uint8_t kPeerIdMin = 0;
392 static constexpr uint8_t kPeerIdMax = BTA_AV_NUM_STRS;
393
BtifAvSource()394 BtifAvSource()
395 : callbacks_(nullptr),
396 enabled_(false),
397 a2dp_offload_enabled_(false),
398 invalid_peer_check_(false),
399 max_connected_peers_(kDefaultMaxConnectedAudioDevices) {}
400 ~BtifAvSource();
401
402 bt_status_t Init(
403 btav_source_callbacks_t* callbacks, int max_connected_audio_devices,
404 const std::vector<btav_a2dp_codec_config_t>& codec_priorities,
405 const std::vector<btav_a2dp_codec_config_t>& offloading_preference,
406 std::vector<btav_a2dp_codec_info_t>* supported_codecs);
407 void Cleanup();
408
Callbacks()409 btav_source_callbacks_t* Callbacks() { return callbacks_; }
Enabled() const410 bool Enabled() const { return enabled_; }
A2dpOffloadEnabled() const411 bool A2dpOffloadEnabled() const { return a2dp_offload_enabled_; }
412 // TODO: b/321806163: Remove this method as part of flag cleanup
SetInvalidPeerCheck(bool invalid_peer_check)413 void SetInvalidPeerCheck(bool invalid_peer_check) {
414 invalid_peer_check_ = invalid_peer_check;
415 }
416 BtifAvPeer* FindPeer(const RawAddress& peer_address);
417 BtifAvPeer* FindPeerByHandle(tBTA_AV_HNDL bta_handle);
418 BtifAvPeer* FindPeerByPeerId(uint8_t peer_id);
419 BtifAvPeer* FindOrCreatePeer(const RawAddress& peer_address,
420 tBTA_AV_HNDL bta_handle);
421
422 /**
423 * Check whether a connection to a peer is allowed.
424 * The check considers the maximum number of connected peers.
425 *
426 * @param peer_address the peer address to connect to
427 * @return true if connection is allowed, otherwise false
428 */
429 bool AllowedToConnect(const RawAddress& peer_address) const;
430
431 /**
432 * Delete all peers that have transitioned to Idle state and can be deleted.
433 * If a peer was just created/initialized, then it cannot be deleted yet.
434 */
435 void DeleteIdlePeers();
436
437 /**
438 * Get the active peer.
439 *
440 * @return the active peer
441 */
ActivePeer() const442 const RawAddress& ActivePeer() const { return active_peer_; }
443
444 /**
445 * Check whether peer is silenced
446 *
447 * @param peer_address the peer to check
448 * @return true on silence mode enabled, otherwise false
449 */
IsPeerSilenced(const RawAddress & peer_address)450 bool IsPeerSilenced(const RawAddress& peer_address) {
451 if (peer_address.IsEmpty()) {
452 return false;
453 }
454 BtifAvPeer* peer = FindPeer(peer_address);
455 if (peer == nullptr) {
456 log::warn("peer is null");
457 return false;
458 }
459 if (!peer->IsConnected()) {
460 log::warn("peer is not connected");
461 return false;
462 }
463 return peer->IsInSilenceMode();
464 }
465
466 /**
467 * Set peer silence mode
468 *
469 * @param peer_address the peer to set
470 * @param silence true on enable silence mode, false on disable
471 * @return true on success, otherwise false
472 */
SetSilencePeer(const RawAddress & peer_address,const bool silence)473 bool SetSilencePeer(const RawAddress& peer_address, const bool silence) {
474 if (peer_address.IsEmpty()) {
475 return false;
476 }
477 log::info("peer: {}", peer_address);
478 BtifAvPeer* peer = FindPeer(peer_address);
479 if (peer == nullptr) {
480 log::warn("peer is null");
481 return false;
482 }
483 if (!peer->IsConnected()) {
484 log::warn("peer is not connected");
485 return false;
486 }
487 peer->SetSilence(silence);
488 return true;
489 }
490
491 /**
492 * Set the active peer.
493 *
494 * @param peer_address the active peer address or RawAddress::kEmpty to
495 * reset the active peer
496 * @return true on success, otherwise false
497 */
SetActivePeer(const RawAddress & peer_address,std::promise<void> peer_ready_promise)498 bool SetActivePeer(const RawAddress& peer_address,
499 std::promise<void> peer_ready_promise) {
500 log::info("peer={} active_peer={}", peer_address, active_peer_);
501
502 if (active_peer_ == peer_address) {
503 peer_ready_promise.set_value();
504 return true; // Nothing has changed
505 }
506 if (peer_address.IsEmpty()) {
507 log::info("peer address is empty, shutdown the Audio source");
508 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
509 if (!bta_av_co_set_active_source_peer(peer_address)) {
510 log::warn("unable to set active peer to empty in BtaAvCo");
511 }
512 } else {
513 if (!btif_av_src_sink_coexist_enabled() ||
514 (btif_av_src_sink_coexist_enabled() &&
515 btif_av_sink_active_peer().IsEmpty())) {
516 if (!bta_av_co_set_active_peer(peer_address)) {
517 log::warn("unable to set active peer to empty in BtaAvCo");
518 }
519 }
520 }
521
522 btif_a2dp_source_end_session(active_peer_);
523 std::promise<void> shutdown_complete_promise;
524 std::future<void> shutdown_complete_future =
525 shutdown_complete_promise.get_future();
526 btif_a2dp_source_shutdown(std::move(shutdown_complete_promise));
527 using namespace std::chrono_literals;
528 if (shutdown_complete_future.wait_for(1s) ==
529 std::future_status::timeout) {
530 log::error("Timed out waiting for A2DP source shutdown to complete.");
531 }
532 active_peer_ = peer_address;
533 peer_ready_promise.set_value();
534 return true;
535 }
536
537 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
538 btif_av_src_sink_coexist_enabled()) {
539 btif_av_sink_delete_active_peer();
540 }
541 BtifAvPeer* peer = FindPeer(peer_address);
542 if (peer == nullptr || !peer->IsConnected()) {
543 log::error("Error setting {} as active Source peer", peer_address);
544 peer_ready_promise.set_value();
545 return false;
546 }
547
548 if (!btif_a2dp_source_restart_session(active_peer_, peer_address,
549 std::move(peer_ready_promise))) {
550 // cannot set promise but need to be handled within restart_session
551 return false;
552 }
553 active_peer_ = peer_address;
554 return true;
555 }
556
DeleteActivePeer(void)557 void DeleteActivePeer(void) {
558 log::info("active_peer={}", active_peer_);
559
560 std::promise<void> shutdown_complete_promise;
561 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
562 if (!bta_av_co_set_active_source_peer(RawAddress::kEmpty)) {
563 log::warn("unable to set active peer to empty in BtaAvCo");
564 }
565 } else {
566 if (btif_av_sink_active_peer().IsEmpty()) {
567 if (!bta_av_co_set_active_peer(RawAddress::kEmpty)) {
568 log::warn("unable to set active peer to empty in BtaAvCo");
569 }
570 } else {
571 log::warn("there is an active peer as source role");
572 }
573 }
574 btif_a2dp_source_end_session(active_peer_);
575 btif_a2dp_source_shutdown(std::move(shutdown_complete_promise));
576 active_peer_ = RawAddress::kEmpty;
577 }
578
579 /**
580 * Update source codec configuration for a peer.
581 *
582 * @param peer_address the address of the peer to update
583 * @param codec_preferences the updated codec preferences
584 */
UpdateCodecConfig(const RawAddress & peer_address,const std::vector<btav_a2dp_codec_config_t> & codec_preferences,std::promise<void> peer_ready_promise)585 void UpdateCodecConfig(
586 const RawAddress& peer_address,
587 const std::vector<btav_a2dp_codec_config_t>& codec_preferences,
588 std::promise<void> peer_ready_promise) {
589 // Restart the session if the codec for the active peer is updated
590 if (!peer_address.IsEmpty() && active_peer_ == peer_address) {
591 btif_a2dp_source_end_session(active_peer_);
592 }
593
594 btif_a2dp_source_encoder_user_config_update_req(
595 peer_address, codec_preferences, std::move(peer_ready_promise));
596 }
597
Peers() const598 const std::map<RawAddress, BtifAvPeer*>& Peers() const { return peers_; }
599
600 void RegisterAllBtaHandles();
601 void DeregisterAllBtaHandles();
602 void BtaHandleRegistered(uint8_t peer_id, tBTA_AV_HNDL bta_handle);
603 BtifAvPeer* popPeer(const RawAddress& peer_address);
604 void AddPeer(BtifAvPeer* peer);
605
606 private:
607 void CleanupAllPeers();
608
609 btav_source_callbacks_t* callbacks_;
610 bool enabled_;
611 bool a2dp_offload_enabled_;
612 bool invalid_peer_check_; // pending to check at BTA_AV_OPEN_EVT
613 int max_connected_peers_;
614 std::map<RawAddress, BtifAvPeer*> peers_;
615 std::set<RawAddress> silenced_peers_;
616 RawAddress active_peer_;
617 std::map<uint8_t, tBTA_AV_HNDL> peer_id2bta_handle_;
618 std::mutex mutex_;
619 // protect for BtifAvSource::peers_
620 std::recursive_mutex btifavsource_peer_lock_;
621 };
622
623 class BtifAvSink {
624 public:
625 // The PeerId is used as AppId for BTA_AvRegister() purpose
626 static constexpr uint8_t kPeerIdMin = 0;
627 static constexpr uint8_t kPeerIdMax = BTA_AV_NUM_STRS;
628
BtifAvSink()629 BtifAvSink()
630 : callbacks_(nullptr),
631 enabled_(false),
632 invalid_peer_check_(false),
633 max_connected_peers_(kDefaultMaxConnectedAudioDevices) {}
634 ~BtifAvSink();
635
636 bt_status_t Init(btav_sink_callbacks_t* callbacks,
637 int max_connected_audio_devices);
638 void Cleanup();
639
Callbacks()640 btav_sink_callbacks_t* Callbacks() { return callbacks_; }
Enabled() const641 bool Enabled() const { return enabled_; }
642
643 // TODO: b/321806163: Remove this method as part of flag cleanup
SetInvalidPeerCheck(bool invalid_peer_check)644 void SetInvalidPeerCheck(bool invalid_peer_check) {
645 invalid_peer_check_ = invalid_peer_check;
646 }
647 BtifAvPeer* FindPeer(const RawAddress& peer_address);
648 BtifAvPeer* FindPeerByHandle(tBTA_AV_HNDL bta_handle);
649 BtifAvPeer* FindPeerByPeerId(uint8_t peer_id);
650 BtifAvPeer* FindOrCreatePeer(const RawAddress& peer_address,
651 tBTA_AV_HNDL bta_handle);
652
653 /**
654 * Check whether a connection to a peer is allowed.
655 * The check considers the maximum number of connected peers.
656 *
657 * @param peer_address the peer address to connect to
658 * @return true if connection is allowed, otherwise false
659 */
660 bool AllowedToConnect(const RawAddress& peer_address) const;
661
662 /**
663 * Delete all peers that have transitioned to Idle state and can be deleted.
664 * If a peer was just created/initialized, then it cannot be deleted yet.
665 */
666 void DeleteIdlePeers();
667
668 /**
669 * Get the active peer.
670 *
671 * @return the active peer
672 */
ActivePeer() const673 const RawAddress& ActivePeer() const { return active_peer_; }
674
675 /**
676 * Set the active peer.
677 *
678 * @param peer_address the active peer address or RawAddress::kEmpty to
679 * reset the active peer
680 * @return true on success, otherwise false
681 */
SetActivePeer(const RawAddress & peer_address,std::promise<void> peer_ready_promise)682 bool SetActivePeer(const RawAddress& peer_address,
683 std::promise<void> peer_ready_promise) {
684 log::info("peer={} active_peer={}", peer_address, active_peer_);
685
686 if (active_peer_ == peer_address) {
687 peer_ready_promise.set_value();
688 return true; // Nothing has changed
689 }
690 if (peer_address.IsEmpty()) {
691 log::verbose("peer address is empty, shutdown the Audio sink");
692 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
693 if (!bta_av_co_set_active_sink_peer(peer_address)) {
694 log::warn("unable to set active peer to empty in BtaAvCo");
695 }
696 } else {
697 if (!btif_av_src_sink_coexist_enabled() ||
698 (btif_av_src_sink_coexist_enabled() &&
699 btif_av_source_active_peer().IsEmpty())) {
700 if (!bta_av_co_set_active_peer(peer_address)) {
701 log::warn("unable to set active peer to empty in BtaAvCo");
702 }
703 }
704 }
705
706 btif_a2dp_sink_end_session(active_peer_);
707 btif_a2dp_sink_shutdown();
708 active_peer_ = peer_address;
709 peer_ready_promise.set_value();
710 return true;
711 }
712
713 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
714 btif_av_src_sink_coexist_enabled()) {
715 btif_av_source_delete_active_peer();
716 }
717 BtifAvPeer* peer = FindPeer(peer_address);
718 if (peer == nullptr || !peer->IsConnected()) {
719 log::error("Error setting {} as active Sink peer", peer_address);
720 peer_ready_promise.set_value();
721 return false;
722 }
723
724 if (!btif_a2dp_sink_restart_session(active_peer_, peer_address,
725 std::move(peer_ready_promise))) {
726 // cannot set promise but need to be handled within restart_session
727 return false;
728 }
729 log::info("Setting the active peer to peer address {}", peer_address);
730 active_peer_ = peer_address;
731 return true;
732 }
733
DeleteActivePeer(void)734 void DeleteActivePeer(void) {
735 log::info("active_peer={}", active_peer_);
736
737 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
738 if (!bta_av_co_set_active_sink_peer(RawAddress::kEmpty)) {
739 log::warn("unable to set active peer to empty in BtaAvCo");
740 }
741 } else {
742 if (btif_av_source_active_peer().IsEmpty()) {
743 if (!bta_av_co_set_active_peer(RawAddress::kEmpty)) {
744 log::warn("unable to set active peer to empty in BtaAvCo");
745 }
746 } else {
747 log::warn("there is an active peer as sink role");
748 }
749 }
750 btif_a2dp_sink_end_session(active_peer_);
751 btif_a2dp_sink_shutdown();
752 active_peer_ = RawAddress::kEmpty;
753 }
754
Peers() const755 const std::map<RawAddress, BtifAvPeer*>& Peers() const { return peers_; }
756
757 void RegisterAllBtaHandles();
758 void DeregisterAllBtaHandles();
759 void BtaHandleRegistered(uint8_t peer_id, tBTA_AV_HNDL bta_handle);
760 BtifAvPeer* popPeer(const RawAddress& peer_address);
761 void AddPeer(BtifAvPeer* peer);
762
763 private:
764 void CleanupAllPeers();
765
766 btav_sink_callbacks_t* callbacks_;
767 bool enabled_;
768 bool invalid_peer_check_; // pending to check at BTA_AV_OPEN_EVT
769 int max_connected_peers_;
770 std::map<RawAddress, BtifAvPeer*> peers_;
771 RawAddress active_peer_;
772 std::map<uint8_t, tBTA_AV_HNDL> peer_id2bta_handle_;
773 };
774
775 /*****************************************************************************
776 * Static variables
777 *****************************************************************************/
778 static BtifAvSource btif_av_source;
779 static BtifAvSink btif_av_sink;
780
781 /* Helper macro to avoid code duplication in the state machine handlers */
782 #define CHECK_RC_EVENT(e, d) \
783 case BTA_AV_RC_OPEN_EVT: \
784 case BTA_AV_RC_BROWSE_OPEN_EVT: \
785 case BTA_AV_RC_CLOSE_EVT: \
786 case BTA_AV_RC_BROWSE_CLOSE_EVT: \
787 case BTA_AV_REMOTE_CMD_EVT: \
788 case BTA_AV_VENDOR_CMD_EVT: \
789 case BTA_AV_META_MSG_EVT: \
790 case BTA_AV_RC_FEAT_EVT: \
791 case BTA_AV_RC_PSM_EVT: \
792 case BTA_AV_REMOTE_RSP_EVT: { \
793 btif_rc_handler(e, d); \
794 } break;
795
796 static bt_status_t src_disconnect_sink(const RawAddress& peer_address);
797 static bt_status_t sink_disconnect_src(const RawAddress& peer_address);
798 static void btif_av_source_dispatch_sm_event(const RawAddress& peer_address,
799 btif_av_sm_event_t event);
800 static void btif_av_sink_dispatch_sm_event(const RawAddress& peer_address,
801 btif_av_sm_event_t event);
802 static void btif_av_handle_event(uint8_t peer_sep,
803 const RawAddress& peer_address,
804 tBTA_AV_HNDL bta_handle,
805 const BtifAvEvent& btif_av_event);
806 static void btif_report_connection_state(const RawAddress& peer_address,
807 btav_connection_state_t state,
808 const bt_status_t status,
809 uint8_t error_code,
810 const A2dpType local_a2dp_type);
811 static void btif_report_audio_state(const RawAddress& peer_address,
812 btav_audio_state_t state,
813 const A2dpType local_a2dp_type);
814 static void btif_av_report_sink_audio_config_state(
815 const RawAddress& peer_address, int sample_rate, int channel_count);
816 static void btif_av_query_mandatory_codec_priority(
817 const RawAddress& peer_address);
818 static void btif_av_source_initiate_av_open_timer_timeout(void* data);
819 static void btif_av_sink_initiate_av_open_timer_timeout(void* data);
820 static void bta_av_sink_media_callback(const RawAddress& peer_address,
821 tBTA_AV_EVT event,
822 tBTA_AV_MEDIA* p_data);
823 extern bool btif_av_both_enable(void);
824 extern bool btif_av_is_connected_addr(const RawAddress& peer_address,
825 const A2dpType local_a2dp_type);
826 extern bool btif_av_peer_is_sink(const RawAddress& peer_address);
827 extern void btif_rc_check_pending_cmd(const RawAddress& peer_address);
828 extern void btif_rc_get_addr_by_handle(uint8_t handle, RawAddress& rc_addr);
829
btif_av_source_find_peer(const RawAddress & peer_address)830 static BtifAvPeer* btif_av_source_find_peer(const RawAddress& peer_address) {
831 return btif_av_source.FindPeer(peer_address);
832 }
btif_av_sink_find_peer(const RawAddress & peer_address)833 static BtifAvPeer* btif_av_sink_find_peer(const RawAddress& peer_address) {
834 return btif_av_sink.FindPeer(peer_address);
835 }
btif_av_find_peer(const RawAddress & peer_address,const A2dpType local_a2dp_type)836 static BtifAvPeer* btif_av_find_peer(const RawAddress& peer_address,
837 const A2dpType local_a2dp_type) {
838 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
839 if (btif_av_source.Enabled() && local_a2dp_type == A2dpType::kSource) {
840 BtifAvPeer* sourcePeer = btif_av_source_find_peer(peer_address);
841 if (sourcePeer != nullptr) {
842 return sourcePeer;
843 }
844 }
845 if (btif_av_sink.Enabled() && local_a2dp_type == A2dpType::kSink) {
846 BtifAvPeer* sinkPeer = btif_av_sink_find_peer(peer_address);
847 if (sinkPeer != nullptr) {
848 return sinkPeer;
849 }
850 }
851 if (btif_av_source.Enabled()) {
852 BtifAvPeer* sourcePeer = btif_av_source_find_peer(peer_address);
853 if (sourcePeer != nullptr) {
854 return sourcePeer;
855 }
856 }
857 if (btif_av_sink.Enabled()) {
858 BtifAvPeer* sinkPeer = btif_av_sink_find_peer(peer_address);
859 if (sinkPeer != nullptr) {
860 return sinkPeer;
861 }
862 }
863 log::info("Unable to find the peer {}", peer_address);
864 return nullptr;
865 }
866 if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
867 BtifAvPeer* peer = nullptr;
868 peer = btif_av_source_find_peer(peer_address);
869 if (nullptr == peer) {
870 return btif_av_sink_find_peer(peer_address);
871 }
872 return peer;
873 }
874 if (btif_av_source.Enabled()) return btif_av_source_find_peer(peer_address);
875 if (btif_av_sink.Enabled()) return btif_av_sink_find_peer(peer_address);
876 return nullptr;
877 }
btif_av_find_active_peer(const A2dpType local_a2dp_type)878 static BtifAvPeer* btif_av_find_active_peer(const A2dpType local_a2dp_type) {
879 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
880 if (btif_av_source.Enabled() && local_a2dp_type == A2dpType::kSource)
881 return btif_av_source_find_peer(btif_av_source.ActivePeer());
882 if (btif_av_sink.Enabled() && local_a2dp_type == A2dpType::kSink)
883 return btif_av_sink_find_peer(btif_av_sink.ActivePeer());
884 return nullptr;
885 }
886
887 if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
888 BtifAvPeer* peer = nullptr;
889 peer = btif_av_source_find_peer(btif_av_source.ActivePeer());
890 if (nullptr == peer) {
891 return btif_av_sink_find_peer(btif_av_sink.ActivePeer());
892 }
893 return peer;
894 }
895 if (btif_av_source.Enabled())
896 return btif_av_source_find_peer(btif_av_source.ActivePeer());
897 if (btif_av_sink.Enabled())
898 return btif_av_sink_find_peer(btif_av_sink.ActivePeer());
899 return nullptr;
900 }
901
btif_av_find_by_handle(tBTA_AV_HNDL bta_handle)902 const RawAddress& btif_av_find_by_handle(tBTA_AV_HNDL bta_handle) {
903 BtifAvPeer* peer = nullptr;
904 if (btif_av_both_enable()) {
905 peer = btif_av_source.FindPeerByHandle(bta_handle);
906 if (peer == nullptr) {
907 peer = btif_av_sink.FindPeerByHandle(bta_handle);
908 }
909 if (peer == nullptr) return RawAddress::kEmpty;
910
911 return peer->PeerAddress();
912 }
913 if (btif_av_source.Enabled())
914 peer = btif_av_source.FindPeerByHandle(bta_handle);
915 if (btif_av_sink.Enabled()) peer = btif_av_sink.FindPeerByHandle(bta_handle);
916
917 if (peer == nullptr) return RawAddress::kEmpty;
918
919 return peer->PeerAddress();
920 }
921
922 /*****************************************************************************
923 * Local helper functions
924 *****************************************************************************/
925
dump_av_sm_event_name(btif_av_sm_event_t event)926 const char* dump_av_sm_event_name(btif_av_sm_event_t event) {
927 switch ((int)event) {
928 CASE_RETURN_STR(BTA_AV_ENABLE_EVT)
929 CASE_RETURN_STR(BTA_AV_REGISTER_EVT)
930 CASE_RETURN_STR(BTA_AV_OPEN_EVT)
931 CASE_RETURN_STR(BTA_AV_CLOSE_EVT)
932 CASE_RETURN_STR(BTA_AV_START_EVT)
933 CASE_RETURN_STR(BTA_AV_STOP_EVT)
934 CASE_RETURN_STR(BTA_AV_PROTECT_REQ_EVT)
935 CASE_RETURN_STR(BTA_AV_PROTECT_RSP_EVT)
936 CASE_RETURN_STR(BTA_AV_RC_OPEN_EVT)
937 CASE_RETURN_STR(BTA_AV_RC_CLOSE_EVT)
938 CASE_RETURN_STR(BTA_AV_RC_BROWSE_OPEN_EVT)
939 CASE_RETURN_STR(BTA_AV_RC_BROWSE_CLOSE_EVT)
940 CASE_RETURN_STR(BTA_AV_REMOTE_CMD_EVT)
941 CASE_RETURN_STR(BTA_AV_REMOTE_RSP_EVT)
942 CASE_RETURN_STR(BTA_AV_VENDOR_CMD_EVT)
943 CASE_RETURN_STR(BTA_AV_VENDOR_RSP_EVT)
944 CASE_RETURN_STR(BTA_AV_RECONFIG_EVT)
945 CASE_RETURN_STR(BTA_AV_SUSPEND_EVT)
946 CASE_RETURN_STR(BTA_AV_PENDING_EVT)
947 CASE_RETURN_STR(BTA_AV_META_MSG_EVT)
948 CASE_RETURN_STR(BTA_AV_REJECT_EVT)
949 CASE_RETURN_STR(BTA_AV_RC_FEAT_EVT)
950 CASE_RETURN_STR(BTA_AV_RC_PSM_EVT)
951 CASE_RETURN_STR(BTA_AV_OFFLOAD_START_RSP_EVT)
952 CASE_RETURN_STR(BTIF_AV_CONNECT_REQ_EVT)
953 CASE_RETURN_STR(BTIF_AV_DISCONNECT_REQ_EVT)
954 CASE_RETURN_STR(BTIF_AV_START_STREAM_REQ_EVT)
955 CASE_RETURN_STR(BTIF_AV_STOP_STREAM_REQ_EVT)
956 CASE_RETURN_STR(BTIF_AV_SUSPEND_STREAM_REQ_EVT)
957 CASE_RETURN_STR(BTIF_AV_SINK_CONFIG_REQ_EVT)
958 CASE_RETURN_STR(BTIF_AV_ACL_DISCONNECTED)
959 CASE_RETURN_STR(BTIF_AV_OFFLOAD_START_REQ_EVT)
960 CASE_RETURN_STR(BTIF_AV_AVRCP_OPEN_EVT)
961 CASE_RETURN_STR(BTIF_AV_AVRCP_CLOSE_EVT)
962 CASE_RETURN_STR(BTIF_AV_AVRCP_REMOTE_PLAY_EVT)
963 CASE_RETURN_STR(BTIF_AV_SET_LATENCY_REQ_EVT)
964 default:
965 return "UNKNOWN_EVENT";
966 }
967 }
968
dump_av_sm_event_name(int event)969 const char* dump_av_sm_event_name(int event) {
970 return dump_av_sm_event_name(static_cast<btif_av_sm_event_t>(event));
971 }
972
BtifAvEvent(uint32_t event,const void * p_data,size_t data_length)973 BtifAvEvent::BtifAvEvent(uint32_t event, const void* p_data, size_t data_length)
974 : event_(event), data_(nullptr), data_length_(0) {
975 DeepCopy(event, p_data, data_length);
976 }
977
BtifAvEvent(const BtifAvEvent & other)978 BtifAvEvent::BtifAvEvent(const BtifAvEvent& other)
979 : event_(0), data_(nullptr), data_length_(0) {
980 *this = other;
981 }
982
operator =(const BtifAvEvent & other)983 BtifAvEvent& BtifAvEvent::operator=(const BtifAvEvent& other) {
984 DeepFree();
985 DeepCopy(other.Event(), other.Data(), other.DataLength());
986 return *this;
987 }
988
~BtifAvEvent()989 BtifAvEvent::~BtifAvEvent() { DeepFree(); }
990
ToString() const991 std::string BtifAvEvent::ToString() const {
992 return BtifAvEvent::EventName(event_);
993 }
994
EventName(uint32_t event)995 std::string BtifAvEvent::EventName(uint32_t event) {
996 std::string name = dump_av_sm_event_name((btif_av_sm_event_t)event);
997 std::stringstream ss_value;
998 ss_value << "(0x" << std::hex << event << ")";
999 return name + ss_value.str();
1000 }
1001
DeepCopy(uint32_t event,const void * p_data,size_t data_length)1002 void BtifAvEvent::DeepCopy(uint32_t event, const void* p_data,
1003 size_t data_length) {
1004 event_ = event;
1005 data_length_ = data_length;
1006 if (data_length == 0) {
1007 data_ = nullptr;
1008 } else {
1009 data_ = osi_malloc(data_length_);
1010 memcpy(data_, p_data, data_length);
1011 }
1012
1013 switch (event) {
1014 case BTA_AV_META_MSG_EVT: {
1015 log::assert_that(data_length >= sizeof(tBTA_AV),
1016 "assert failed: data_length >= sizeof(tBTA_AV)");
1017 const tBTA_AV* av_src = (const tBTA_AV*)p_data;
1018 tBTA_AV* av_dest = (tBTA_AV*)data_;
1019 if (av_src->meta_msg.p_data && av_src->meta_msg.len) {
1020 av_dest->meta_msg.p_data = (uint8_t*)osi_calloc(av_src->meta_msg.len);
1021 memcpy(av_dest->meta_msg.p_data, av_src->meta_msg.p_data,
1022 av_src->meta_msg.len);
1023 }
1024
1025 if (av_src->meta_msg.p_msg) {
1026 av_dest->meta_msg.p_msg = (tAVRC_MSG*)osi_calloc(sizeof(tAVRC_MSG));
1027 memcpy(av_dest->meta_msg.p_msg, av_src->meta_msg.p_msg,
1028 sizeof(tAVRC_MSG));
1029
1030 tAVRC_MSG* p_msg_src = av_src->meta_msg.p_msg;
1031 tAVRC_MSG* p_msg_dest = av_dest->meta_msg.p_msg;
1032
1033 if ((p_msg_src->hdr.opcode == AVRC_OP_VENDOR) &&
1034 (p_msg_src->vendor.p_vendor_data && p_msg_src->vendor.vendor_len)) {
1035 p_msg_dest->vendor.p_vendor_data =
1036 (uint8_t*)osi_calloc(p_msg_src->vendor.vendor_len);
1037 memcpy(p_msg_dest->vendor.p_vendor_data,
1038 p_msg_src->vendor.p_vendor_data, p_msg_src->vendor.vendor_len);
1039 }
1040 if ((p_msg_src->hdr.opcode == AVRC_OP_BROWSE) &&
1041 p_msg_src->browse.p_browse_data && p_msg_src->browse.browse_len) {
1042 p_msg_dest->browse.p_browse_data =
1043 (uint8_t*)osi_calloc(p_msg_src->browse.browse_len);
1044 memcpy(p_msg_dest->browse.p_browse_data,
1045 p_msg_src->browse.p_browse_data, p_msg_src->browse.browse_len);
1046 }
1047 }
1048 } break;
1049
1050 default:
1051 break;
1052 }
1053 }
1054
DeepFree()1055 void BtifAvEvent::DeepFree() {
1056 switch (event_) {
1057 case BTA_AV_META_MSG_EVT: {
1058 tBTA_AV* av = (tBTA_AV*)data_;
1059 osi_free_and_reset((void**)&av->meta_msg.p_data);
1060
1061 if (av->meta_msg.p_msg) {
1062 if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) {
1063 osi_free(av->meta_msg.p_msg->vendor.p_vendor_data);
1064 }
1065 if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_BROWSE) {
1066 osi_free(av->meta_msg.p_msg->browse.p_browse_data);
1067 }
1068 osi_free_and_reset((void**)&av->meta_msg.p_msg);
1069 }
1070 } break;
1071
1072 default:
1073 break;
1074 }
1075
1076 osi_free_and_reset((void**)&data_);
1077 data_length_ = 0;
1078 }
1079
BtifAvPeer(const RawAddress & peer_address,uint8_t peer_sep,tBTA_AV_HNDL bta_handle,uint8_t peer_id)1080 BtifAvPeer::BtifAvPeer(const RawAddress& peer_address, uint8_t peer_sep,
1081 tBTA_AV_HNDL bta_handle, uint8_t peer_id)
1082 : peer_address_(peer_address),
1083 peer_sep_(peer_sep),
1084 bta_handle_(bta_handle),
1085 peer_id_(peer_id),
1086 state_machine_(*this),
1087 av_open_on_rc_timer_(nullptr),
1088 edr_(0),
1089 flags_(0),
1090 self_initiated_connection_(false),
1091 delay_report_(0) {}
1092
~BtifAvPeer()1093 BtifAvPeer::~BtifAvPeer() { alarm_free(av_open_on_rc_timer_); }
1094
FlagsToString() const1095 std::string BtifAvPeer::FlagsToString() const {
1096 std::string result;
1097
1098 if (flags_ & BtifAvPeer::kFlagLocalSuspendPending) {
1099 if (!result.empty()) result += "|";
1100 result += "LOCAL_SUSPEND_PENDING";
1101 }
1102 if (flags_ & BtifAvPeer::kFlagRemoteSuspend) {
1103 if (!result.empty()) result += "|";
1104 result += "REMOTE_SUSPEND";
1105 }
1106 if (flags_ & BtifAvPeer::kFlagPendingStart) {
1107 if (!result.empty()) result += "|";
1108 result += "PENDING_START";
1109 }
1110 if (flags_ & BtifAvPeer::kFlagPendingStop) {
1111 if (!result.empty()) result += "|";
1112 result += "PENDING_STOP";
1113 }
1114 if (result.empty()) result = "None";
1115
1116 return base::StringPrintf("0x%x(%s)", flags_, result.c_str());
1117 }
1118
Init()1119 bt_status_t BtifAvPeer::Init() {
1120 alarm_free(av_open_on_rc_timer_);
1121 av_open_on_rc_timer_ = alarm_new("btif_av_peer.av_open_on_rc_timer");
1122 is_silenced_ = false;
1123
1124 state_machine_.Start();
1125 return BT_STATUS_SUCCESS;
1126 }
1127
Cleanup()1128 void BtifAvPeer::Cleanup() {
1129 state_machine_.Quit();
1130 alarm_free(av_open_on_rc_timer_);
1131 av_open_on_rc_timer_ = nullptr;
1132 }
1133
CanBeDeleted() const1134 bool BtifAvPeer::CanBeDeleted() const {
1135 return (
1136 (state_machine_.StateId() == BtifAvStateMachine::kStateIdle) &&
1137 (state_machine_.PreviousStateId() != BtifAvStateMachine::kStateInvalid));
1138 }
1139
ActivePeerAddress() const1140 const RawAddress& BtifAvPeer::ActivePeerAddress() const {
1141 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
1142 if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
1143 RawAddress addr = btif_av_sink.ActivePeer();
1144 if (RawAddress::kEmpty == addr) {
1145 log::warn("A2DP peer {} is Sink", btif_av_source.ActivePeer());
1146 return btif_av_source.ActivePeer();
1147 }
1148 log::warn("A2DP peer {} is Source", btif_av_sink.ActivePeer());
1149 return btif_av_sink.ActivePeer();
1150 }
1151 }
1152 if (IsSource()) {
1153 return btif_av_sink.ActivePeer();
1154 }
1155 if (IsSink()) {
1156 return btif_av_source.ActivePeer();
1157 }
1158
1159 log::fatal("A2DP peer {} is neither Source nor Sink", PeerAddress());
1160 return RawAddress::kEmpty;
1161 }
1162
IsConnected() const1163 bool BtifAvPeer::IsConnected() const {
1164 int state = state_machine_.StateId();
1165 return ((state == BtifAvStateMachine::kStateOpened) ||
1166 (state == BtifAvStateMachine::kStateStarted));
1167 }
1168
IsStreaming() const1169 bool BtifAvPeer::IsStreaming() const {
1170 int state = state_machine_.StateId();
1171 return (state == BtifAvStateMachine::kStateStarted);
1172 }
1173
~BtifAvSource()1174 BtifAvSource::~BtifAvSource() { CleanupAllPeers(); }
1175
Init(btav_source_callbacks_t * callbacks,int max_connected_audio_devices,const std::vector<btav_a2dp_codec_config_t> & codec_priorities,const std::vector<btav_a2dp_codec_config_t> & offloading_preference,std::vector<btav_a2dp_codec_info_t> * supported_codecs)1176 bt_status_t BtifAvSource::Init(
1177 btav_source_callbacks_t* callbacks, int max_connected_audio_devices,
1178 const std::vector<btav_a2dp_codec_config_t>& codec_priorities,
1179 const std::vector<btav_a2dp_codec_config_t>& offloading_preference,
1180 std::vector<btav_a2dp_codec_info_t>* supported_codecs) {
1181 log::info("max_connected_audio_devices={}", max_connected_audio_devices);
1182 if (enabled_) return BT_STATUS_SUCCESS;
1183 CleanupAllPeers();
1184 max_connected_peers_ = max_connected_audio_devices;
1185
1186 /* A2DP OFFLOAD */
1187 a2dp_offload_enabled_ =
1188 GetInterfaceToProfiles()->config->isA2DPOffloadEnabled();
1189 log::verbose("a2dp_offload.enable = {}", a2dp_offload_enabled_);
1190
1191 callbacks_ = callbacks;
1192 if (a2dp_offload_enabled_) {
1193 tBTM_BLE_VSC_CB vsc_cb = {};
1194 BTM_BleGetVendorCapabilities(&vsc_cb);
1195 bool supports_a2dp_hw_offload_v2 =
1196 vsc_cb.version_supported >= 0x0104 && vsc_cb.a2dp_offload_v2_support;
1197 bluetooth::audio::a2dp::update_codec_offloading_capabilities(
1198 offloading_preference, supports_a2dp_hw_offload_v2);
1199 }
1200 bta_av_co_init(codec_priorities, supported_codecs);
1201
1202 if (!btif_a2dp_source_init()) {
1203 return BT_STATUS_FAIL;
1204 }
1205 enabled_ = true;
1206 btif_enable_service(BTA_A2DP_SOURCE_SERVICE_ID);
1207 return BT_STATUS_SUCCESS;
1208 }
1209
Cleanup()1210 void BtifAvSource::Cleanup() {
1211 log::info("");
1212 if (!enabled_) return;
1213 enabled_ = false;
1214
1215 btif_queue_cleanup(UUID_SERVCLASS_AUDIO_SOURCE);
1216
1217 std::promise<void> peer_ready_promise;
1218 do_in_main_thread(
1219 FROM_HERE,
1220 base::BindOnce(base::IgnoreResult(&BtifAvSource::SetActivePeer),
1221 base::Unretained(&btif_av_source), RawAddress::kEmpty,
1222 std::move(peer_ready_promise)));
1223 do_in_main_thread(FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup));
1224
1225 btif_disable_service(BTA_A2DP_SOURCE_SERVICE_ID);
1226 CleanupAllPeers();
1227
1228 callbacks_ = nullptr;
1229 }
1230
FindPeer(const RawAddress & peer_address)1231 BtifAvPeer* BtifAvSource::FindPeer(const RawAddress& peer_address) {
1232 auto it = peers_.find(peer_address);
1233 if (it != peers_.end()) return it->second;
1234 return nullptr;
1235 }
1236
FindPeerByHandle(tBTA_AV_HNDL bta_handle)1237 BtifAvPeer* BtifAvSource::FindPeerByHandle(tBTA_AV_HNDL bta_handle) {
1238 for (auto it : peers_) {
1239 BtifAvPeer* peer = it.second;
1240 if (peer->BtaHandle() == bta_handle) {
1241 return peer;
1242 }
1243 }
1244 return nullptr;
1245 }
1246
FindPeerByPeerId(uint8_t peer_id)1247 BtifAvPeer* BtifAvSource::FindPeerByPeerId(uint8_t peer_id) {
1248 for (auto it : peers_) {
1249 BtifAvPeer* peer = it.second;
1250 if (peer->PeerId() == peer_id) {
1251 return peer;
1252 }
1253 }
1254 return nullptr;
1255 }
1256
FindOrCreatePeer(const RawAddress & peer_address,tBTA_AV_HNDL bta_handle)1257 BtifAvPeer* BtifAvSource::FindOrCreatePeer(const RawAddress& peer_address,
1258 tBTA_AV_HNDL bta_handle) {
1259 std::unique_lock<std::mutex> lock1(mutex_);
1260 log::verbose("peer={} bta_handle=0x{:x}", peer_address, bta_handle);
1261
1262 BtifAvPeer* peer = FindPeer(peer_address);
1263 if (peer != nullptr) return peer;
1264
1265 // Find next availabie Peer ID to use
1266 uint8_t peer_id;
1267 for (peer_id = kPeerIdMin; peer_id < kPeerIdMax; peer_id++) {
1268 /* because the peer id may be in source cb and we cannot use it */
1269 if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
1270 if (FindPeerByPeerId(peer_id) == nullptr &&
1271 btif_av_sink.FindPeerByPeerId(peer_id) == nullptr)
1272 break;
1273 } else {
1274 if (FindPeerByPeerId(peer_id) == nullptr) break;
1275 }
1276 }
1277 if (peer_id == kPeerIdMax) {
1278 log::error(
1279 "Cannot create peer for peer={} : cannot allocate unique Peer "
1280 "ID",
1281 peer_address);
1282 return nullptr;
1283 }
1284
1285 // Get the BTA Handle (if known)
1286 if (bta_handle == kBtaHandleUnknown) {
1287 auto it = peer_id2bta_handle_.find(peer_id);
1288 if (it == peer_id2bta_handle_.end() || it->second == kBtaHandleUnknown) {
1289 log::error(
1290 "Cannot create peer for peer={} : cannot convert Peer ID={} "
1291 "to unique BTA Handle",
1292 peer_address, peer_id);
1293 return nullptr;
1294 }
1295 bta_handle = it->second;
1296 }
1297
1298 log::info("Create peer: peer={} bta_handle=0x{:x} peer_id={}",
1299 peer_address, bta_handle, peer_id);
1300 peer = new BtifAvPeer(peer_address, AVDT_TSEP_SNK, bta_handle, peer_id);
1301 peers_.insert(std::make_pair(peer_address, peer));
1302 peer->Init();
1303 return peer;
1304 }
1305
AllowedToConnect(const RawAddress & peer_address) const1306 bool BtifAvSource::AllowedToConnect(const RawAddress& peer_address) const {
1307 int connected = 0;
1308
1309 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
1310 btif_av_src_sink_coexist_enabled() && invalid_peer_check_) {
1311 log::info(
1312 "invalid_peer_check_ so allow to connect here, when BTA_AV_OPEN_EVT "
1313 "coming, would check again!");
1314 return true;
1315 }
1316
1317 // Count peers that are in the process of connecting or already connected
1318 for (auto it : peers_) {
1319 const BtifAvPeer* peer = it.second;
1320 switch (peer->StateMachine().StateId()) {
1321 case BtifAvStateMachine::kStateOpening:
1322 case BtifAvStateMachine::kStateOpened:
1323 case BtifAvStateMachine::kStateStarted:
1324 if (peer->PeerAddress() == peer_address) {
1325 /* we should check if another role is used */
1326 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
1327 btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
1328 break;
1329 }
1330
1331 return true; // Already connected or accounted for
1332 }
1333 connected++;
1334 break;
1335 default:
1336 break;
1337 }
1338 }
1339 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
1340 btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
1341 log::info("connected={}, max_connected_peers_={}, sink_peers={}", connected,
1342 max_connected_peers_, (int)btif_av_sink.Peers().size());
1343 /* if source device connected, don't connect sink device */
1344
1345 if (connected >= max_connected_peers_ || !btif_av_sink.Peers().empty()) {
1346 return false;
1347 } else {
1348 return true;
1349 }
1350 }
1351 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
1352 const int sink_connected_peers_size = (int)btif_av_sink.Peers().size();
1353 log::info(
1354 "connected={}, max_connected_peers_={}, sink_connected_peers_size={}",
1355 connected, max_connected_peers_, (int)btif_av_sink.Peers().size());
1356 return ((connected + sink_connected_peers_size) < max_connected_peers_);
1357 }
1358 return (connected < max_connected_peers_);
1359 }
1360
DeleteIdlePeers()1361 void BtifAvSource::DeleteIdlePeers() {
1362 for (auto it = peers_.begin(); it != peers_.end();) {
1363 BtifAvPeer* peer = it->second;
1364 auto prev_it = it++;
1365 if (!peer->CanBeDeleted()) continue;
1366 log::info("peer={} bta_handle=0x{:x}", peer->PeerAddress(),
1367 peer->BtaHandle());
1368 peer->Cleanup();
1369 peers_.erase(prev_it);
1370 delete peer;
1371 }
1372 }
1373
CleanupAllPeers()1374 void BtifAvSource::CleanupAllPeers() {
1375 log::info("");
1376
1377 while (!peers_.empty()) {
1378 auto it = peers_.begin();
1379 BtifAvPeer* peer = it->second;
1380 peer->Cleanup();
1381 peers_.erase(it);
1382 delete peer;
1383 }
1384 }
1385
RegisterAllBtaHandles()1386 void BtifAvSource::RegisterAllBtaHandles() {
1387 for (int peer_id = kPeerIdMin; peer_id < kPeerIdMax; peer_id++) {
1388 BTA_AvRegister(BTA_AV_CHNL_AUDIO, kBtifAvSourceServiceName.c_str(), peer_id,
1389 nullptr, UUID_SERVCLASS_AUDIO_SOURCE);
1390 }
1391 }
1392
DeregisterAllBtaHandles()1393 void BtifAvSource::DeregisterAllBtaHandles() {
1394 for (auto it : peer_id2bta_handle_) {
1395 tBTA_AV_HNDL bta_handle = it.second;
1396 BTA_AvDeregister(bta_handle);
1397 }
1398 peer_id2bta_handle_.clear();
1399 }
1400
BtaHandleRegistered(uint8_t peer_id,tBTA_AV_HNDL bta_handle)1401 void BtifAvSource::BtaHandleRegistered(uint8_t peer_id,
1402 tBTA_AV_HNDL bta_handle) {
1403 peer_id2bta_handle_.insert(std::make_pair(peer_id, bta_handle));
1404
1405 // Set the BTA Handle for the Peer (if exists)
1406 BtifAvPeer* peer = FindPeerByPeerId(peer_id);
1407 if (peer != nullptr && peer->BtaHandle() != bta_handle) {
1408 if (peer->BtaHandle() == kBtaHandleUnknown) {
1409 log::verbose("Assign peer: peer={} bta_handle=0x{:x} peer_id={}",
1410 peer->PeerAddress(), bta_handle, peer_id);
1411 } else {
1412 log::warn(
1413 "Correct peer: peer={} bta_handle=0x{:x}->0x{:x} peer_id={}",
1414 peer->PeerAddress(), peer->BtaHandle(), bta_handle, peer_id);
1415 }
1416 peer->SetBtaHandle(bta_handle);
1417 }
1418 }
1419
popPeer(const RawAddress & peer_address)1420 BtifAvPeer* BtifAvSource::popPeer(const RawAddress& peer_address) {
1421 auto it = peers_.find(peer_address);
1422 if (it == peers_.end()) return nullptr;
1423 BtifAvPeer* peer = it->second;
1424 peers_.erase(it);
1425 log::info("peer={}, state={}", peer->PeerAddress(),
1426 peer->StateMachine().StateId());
1427 return peer;
1428 }
1429
AddPeer(BtifAvPeer * peer)1430 void BtifAvSource::AddPeer(BtifAvPeer* peer) {
1431 log::info("peer={}, state={}", peer->PeerAddress(),
1432 peer->StateMachine().StateId());
1433 peers_.insert(std::make_pair(peer->PeerAddress(), peer));
1434 }
~BtifAvSink()1435 BtifAvSink::~BtifAvSink() { CleanupAllPeers(); }
1436
Init(btav_sink_callbacks_t * callbacks,int max_connected_audio_devices)1437 bt_status_t BtifAvSink::Init(btav_sink_callbacks_t* callbacks,
1438 int max_connected_audio_devices) {
1439 log::info("(max_connected_audio_devices={})", max_connected_audio_devices);
1440 if (enabled_) return BT_STATUS_SUCCESS;
1441
1442 CleanupAllPeers();
1443 max_connected_peers_ = max_connected_audio_devices;
1444 callbacks_ = callbacks;
1445
1446 /** source will have this configuration, but sink don't have, so don't
1447 * overwrite it. */
1448 if (!btif_av_source.Enabled()) {
1449 std::vector<btav_a2dp_codec_config_t>
1450 codec_priorities; // Default priorities
1451 std::vector<btav_a2dp_codec_info_t> supported_codecs;
1452 bta_av_co_init(codec_priorities, &supported_codecs);
1453 }
1454
1455 if (!btif_a2dp_sink_init()) {
1456 return BT_STATUS_FAIL;
1457 }
1458 enabled_ = true;
1459 btif_enable_service(BTA_A2DP_SINK_SERVICE_ID);
1460 return BT_STATUS_SUCCESS;
1461 }
1462
Cleanup()1463 void BtifAvSink::Cleanup() {
1464 log::info("");
1465 if (!enabled_) return;
1466 enabled_ = false;
1467
1468 btif_queue_cleanup(UUID_SERVCLASS_AUDIO_SINK);
1469
1470 std::promise<void> peer_ready_promise;
1471 do_in_main_thread(
1472 FROM_HERE,
1473 base::BindOnce(base::IgnoreResult(&BtifAvSink::SetActivePeer),
1474 base::Unretained(&btif_av_sink), RawAddress::kEmpty,
1475 std::move(peer_ready_promise)));
1476 do_in_main_thread(FROM_HERE, base::BindOnce(&btif_a2dp_sink_cleanup));
1477
1478 btif_disable_service(BTA_A2DP_SINK_SERVICE_ID);
1479 CleanupAllPeers();
1480
1481 callbacks_ = nullptr;
1482 }
1483
FindPeer(const RawAddress & peer_address)1484 BtifAvPeer* BtifAvSink::FindPeer(const RawAddress& peer_address) {
1485 auto it = peers_.find(peer_address);
1486 if (it != peers_.end()) return it->second;
1487 return nullptr;
1488 }
1489
FindPeerByHandle(tBTA_AV_HNDL bta_handle)1490 BtifAvPeer* BtifAvSink::FindPeerByHandle(tBTA_AV_HNDL bta_handle) {
1491 for (auto it : peers_) {
1492 BtifAvPeer* peer = it.second;
1493 if (peer->BtaHandle() == bta_handle) {
1494 return peer;
1495 }
1496 }
1497 return nullptr;
1498 }
1499
FindPeerByPeerId(uint8_t peer_id)1500 BtifAvPeer* BtifAvSink::FindPeerByPeerId(uint8_t peer_id) {
1501 for (auto it : peers_) {
1502 BtifAvPeer* peer = it.second;
1503 if (peer->PeerId() == peer_id) {
1504 return peer;
1505 }
1506 }
1507 return nullptr;
1508 }
1509
FindOrCreatePeer(const RawAddress & peer_address,tBTA_AV_HNDL bta_handle)1510 BtifAvPeer* BtifAvSink::FindOrCreatePeer(const RawAddress& peer_address,
1511 tBTA_AV_HNDL bta_handle) {
1512 log::verbose("peer={} bta_handle=0x{:x}", peer_address, bta_handle);
1513
1514 BtifAvPeer* peer = FindPeer(peer_address);
1515 if (peer != nullptr) return peer;
1516
1517 // Find next availabie Peer ID to use
1518 uint8_t peer_id;
1519 for (peer_id = kPeerIdMin; peer_id < kPeerIdMax; peer_id++) {
1520 /* because the peer id may be in source cb and we cannot use it */
1521 if (btif_av_both_enable()) {
1522 if (FindPeerByPeerId(peer_id) == nullptr &&
1523 btif_av_source.FindPeerByPeerId(peer_id) == nullptr)
1524 break;
1525
1526 } else {
1527 if (FindPeerByPeerId(peer_id) == nullptr) break;
1528 }
1529 }
1530 if (peer_id == kPeerIdMax) {
1531 log::error(
1532 "Cannot create peer for peer={} : cannot allocate unique Peer "
1533 "ID",
1534 peer_address);
1535 return nullptr;
1536 }
1537
1538 // Get the BTA Handle (if known)
1539 if (bta_handle == kBtaHandleUnknown) {
1540 auto it = peer_id2bta_handle_.find(peer_id);
1541 if (it == peer_id2bta_handle_.end() || it->second == kBtaHandleUnknown) {
1542 log::error(
1543 "Cannot create peer for peer={} : cannot convert Peer ID={} "
1544 "to unique BTA Handle",
1545 peer_address, peer_id);
1546 return nullptr;
1547 }
1548 bta_handle = it->second;
1549 }
1550
1551 log::info("Create peer: peer={} bta_handle=0x{:x} peer_id={}",
1552 peer_address, bta_handle, peer_id);
1553 peer = new BtifAvPeer(peer_address, AVDT_TSEP_SRC, bta_handle, peer_id);
1554 peers_.insert(std::make_pair(peer_address, peer));
1555 peer->Init();
1556 return peer;
1557 }
1558
AllowedToConnect(const RawAddress & peer_address) const1559 bool BtifAvSink::AllowedToConnect(const RawAddress& peer_address) const {
1560 int connected = 0;
1561
1562 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
1563 btif_av_src_sink_coexist_enabled() && invalid_peer_check_) {
1564 log::info(
1565 "invalid_peer_check_ so allow to connect here, when BTA_AV_OPEN_EVT "
1566 "coming, would check again!");
1567 return true;
1568 }
1569 // Count peers that are in the process of connecting or already connected
1570 for (auto it : peers_) {
1571 const BtifAvPeer* peer = it.second;
1572 switch (peer->StateMachine().StateId()) {
1573 case BtifAvStateMachine::kStateOpening:
1574 case BtifAvStateMachine::kStateOpened:
1575 case BtifAvStateMachine::kStateStarted:
1576 if (peer->PeerAddress() == peer_address) {
1577 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
1578 /* we should check if another role is used */
1579 if (btif_av_both_enable()) break;
1580 }
1581 return true; // Already connected or accounted for
1582 }
1583 connected++;
1584 break;
1585 case BtifAvStateMachine::kStateClosing:
1586 case BtifAvStateMachine::kStateIdle:
1587 if ((btif_a2dp_sink_get_audio_track() != nullptr) &&
1588 (peer->PeerAddress() != peer_address)) {
1589 log::info(
1590 "there is another peer with audio track({}), another={}, peer={}",
1591 fmt::ptr(btif_a2dp_sink_get_audio_track()), peer->PeerAddress(),
1592 peer_address);
1593 connected++;
1594 }
1595 break;
1596 default:
1597 break;
1598 }
1599 }
1600 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() &&
1601 btif_av_both_enable()) {
1602 log::info("connected={}, max_connected_peers_={}, source_peers={}",
1603 connected, max_connected_peers_,
1604 (int)btif_av_source.Peers().size());
1605 /* if source device connected, don't connect sink device */
1606 return (connected < max_connected_peers_) && btif_av_source.Peers().empty();
1607 }
1608
1609 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
1610 const int source_connected_peers_size = (int)btif_av_source.Peers().size();
1611 log::info(
1612 "connected={}, max_connected_peers_={}, source_connected_peers_size={}",
1613 connected, max_connected_peers_, source_connected_peers_size);
1614 return ((connected + source_connected_peers_size) < max_connected_peers_);
1615 }
1616 return (connected < max_connected_peers_);
1617 }
1618
DeleteIdlePeers()1619 void BtifAvSink::DeleteIdlePeers() {
1620 for (auto it = peers_.begin(); it != peers_.end();) {
1621 BtifAvPeer* peer = it->second;
1622 auto prev_it = it++;
1623 if (!peer->CanBeDeleted()) continue;
1624 log::info("Deleting idle peer: {} bta_handle=0x{:x}", peer->PeerAddress(),
1625 peer->BtaHandle());
1626 peer->Cleanup();
1627 peers_.erase(prev_it);
1628 delete peer;
1629 }
1630 }
1631
CleanupAllPeers()1632 void BtifAvSink::CleanupAllPeers() {
1633 log::info("");
1634
1635 while (!peers_.empty()) {
1636 auto it = peers_.begin();
1637 BtifAvPeer* peer = it->second;
1638 peer->Cleanup();
1639 peers_.erase(it);
1640 delete peer;
1641 }
1642 }
1643
RegisterAllBtaHandles()1644 void BtifAvSink::RegisterAllBtaHandles() {
1645 for (int peer_id = kPeerIdMin; peer_id < kPeerIdMax; peer_id++) {
1646 BTA_AvRegister(BTA_AV_CHNL_AUDIO, kBtifAvSinkServiceName.c_str(), peer_id,
1647 bta_av_sink_media_callback, UUID_SERVCLASS_AUDIO_SINK);
1648 }
1649 }
1650
DeregisterAllBtaHandles()1651 void BtifAvSink::DeregisterAllBtaHandles() {
1652 for (auto it : peer_id2bta_handle_) {
1653 tBTA_AV_HNDL bta_handle = it.second;
1654 BTA_AvDeregister(bta_handle);
1655 }
1656 peer_id2bta_handle_.clear();
1657 }
1658
BtaHandleRegistered(uint8_t peer_id,tBTA_AV_HNDL bta_handle)1659 void BtifAvSink::BtaHandleRegistered(uint8_t peer_id, tBTA_AV_HNDL bta_handle) {
1660 peer_id2bta_handle_.insert(std::make_pair(peer_id, bta_handle));
1661
1662 // Set the BTA Handle for the Peer (if exists)
1663 BtifAvPeer* peer = FindPeerByPeerId(peer_id);
1664 if (peer != nullptr && peer->BtaHandle() != bta_handle) {
1665 if (peer->BtaHandle() == kBtaHandleUnknown) {
1666 log::verbose("Assign peer: peer={} bta_handle=0x{:x} peer_id={}",
1667 peer->PeerAddress(), bta_handle, peer_id);
1668 } else {
1669 log::warn(
1670 "Correct peer: peer={} bta_handle=0x{:x}->0x{:x} peer_id={}",
1671 peer->PeerAddress(), peer->BtaHandle(), bta_handle, peer_id);
1672 }
1673 peer->SetBtaHandle(bta_handle);
1674 }
1675 }
1676
popPeer(const RawAddress & peer_address)1677 BtifAvPeer* BtifAvSink::popPeer(const RawAddress& peer_address) {
1678 auto it = peers_.find(peer_address);
1679 if (it == peers_.end()) return nullptr;
1680 BtifAvPeer* peer = it->second;
1681 peers_.erase(it);
1682 log::info("peer={}, state={}", peer->PeerAddress(),
1683 peer->StateMachine().StateId());
1684 return peer;
1685 }
1686
AddPeer(BtifAvPeer * peer)1687 void BtifAvSink::AddPeer(BtifAvPeer* peer) {
1688 log::info("peer={}, state={}", peer->PeerAddress(),
1689 peer->StateMachine().StateId());
1690 peers_.insert(std::make_pair(peer->PeerAddress(), peer));
1691 }
1692
OnEnter()1693 void BtifAvStateMachine::StateIdle::OnEnter() {
1694 log::info("state=Idle peer={}", peer_.PeerAddress());
1695
1696 peer_.SetEdr(0);
1697 peer_.ClearAllFlags();
1698
1699 // Stop A2DP if this is the active peer
1700 if (peer_.IsActivePeer() || peer_.ActivePeerAddress().IsEmpty()) {
1701 btif_a2dp_on_idle(peer_.PeerAddress(),
1702 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
1703 }
1704
1705 // Reset the active peer if this was the active peer and
1706 // the Idle state was reentered
1707 if (peer_.IsActivePeer() && peer_.CanBeDeleted()) {
1708 std::promise<void> peer_ready_promise;
1709 if (peer_.IsSink()) {
1710 btif_av_source.SetActivePeer(RawAddress::kEmpty,
1711 std::move(peer_ready_promise));
1712 } else if (peer_.IsSource()) {
1713 btif_av_sink.SetActivePeer(RawAddress::kEmpty,
1714 std::move(peer_ready_promise));
1715 }
1716 }
1717
1718 // Delete peers that are re-entering the Idle state
1719 if (peer_.IsSink()) {
1720 do_in_main_thread(FROM_HERE,
1721 base::BindOnce(&BtifAvSource::DeleteIdlePeers,
1722 base::Unretained(&btif_av_source)));
1723 } else if (peer_.IsSource()) {
1724 do_in_main_thread(FROM_HERE,
1725 base::BindOnce(&BtifAvSink::DeleteIdlePeers,
1726 base::Unretained(&btif_av_sink)));
1727 }
1728 }
1729
OnExit()1730 void BtifAvStateMachine::StateIdle::OnExit() {
1731 log::info("state=Idle peer={}", peer_.PeerAddress());
1732 }
1733
ProcessEvent(uint32_t event,void * p_data)1734 bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) {
1735 log::info("state=Idle peer={} event={} flags={} active_peer={}",
1736 peer_.PeerAddress(), BtifAvEvent::EventName(event),
1737 peer_.FlagsToString(), peer_.IsActivePeer());
1738
1739 switch (event) {
1740 case BTA_AV_ENABLE_EVT:
1741 break;
1742
1743 case BTIF_AV_STOP_STREAM_REQ_EVT:
1744 case BTIF_AV_SUSPEND_STREAM_REQ_EVT:
1745 case BTIF_AV_ACL_DISCONNECTED:
1746 // Ignore. Just re-enter Idle so the peer can be deleted
1747 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
1748 break;
1749
1750 case BTIF_AV_DISCONNECT_REQ_EVT:
1751 if (peer_.BtaHandle() != kBtaHandleUnknown) {
1752 BTA_AvClose(peer_.BtaHandle());
1753 if (peer_.IsSource()) {
1754 BTA_AvCloseRc(peer_.BtaHandle());
1755 }
1756 }
1757 // Re-enter Idle so the peer can be deleted
1758 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
1759 break;
1760
1761 case BTIF_AV_CONNECT_REQ_EVT:
1762 case BTA_AV_PENDING_EVT: {
1763 bool can_connect = true;
1764 peer_.SetSelfInitiatedConnection(event == BTIF_AV_CONNECT_REQ_EVT);
1765 // Check whether connection is allowed
1766 if (peer_.IsSink()) {
1767 can_connect = btif_av_source.AllowedToConnect(peer_.PeerAddress());
1768 if (!can_connect) src_disconnect_sink(peer_.PeerAddress());
1769 } else if (peer_.IsSource()) {
1770 can_connect = btif_av_sink.AllowedToConnect(peer_.PeerAddress());
1771 if (!can_connect) sink_disconnect_src(peer_.PeerAddress());
1772 }
1773 if (!can_connect) {
1774 log::error("Cannot connect to peer {}: too many connected peers",
1775 peer_.PeerAddress());
1776 if (peer_.SelfInitiatedConnection()) {
1777 btif_queue_advance();
1778 }
1779 break;
1780 }
1781 btif_av_query_mandatory_codec_priority(peer_.PeerAddress());
1782 BTA_AvOpen(peer_.PeerAddress(), peer_.BtaHandle(), true,
1783 peer_.LocalUuidServiceClass());
1784 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpening);
1785 if (event == BTIF_AV_CONNECT_REQ_EVT) {
1786 DEVICE_IOT_CONFIG_ADDR_SET_INT(
1787 peer_.PeerAddress(), IOT_CONF_KEY_A2DP_ROLE,
1788 (peer_.LocalUuidServiceClass() == UUID_SERVCLASS_AUDIO_SOURCE)
1789 ? IOT_CONF_VAL_A2DP_ROLE_SINK
1790 : IOT_CONF_VAL_A2DP_ROLE_SOURCE);
1791 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(),
1792 IOT_CONF_KEY_A2DP_CONN_COUNT);
1793 } else if (event == BTA_AV_PENDING_EVT) {
1794 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(),
1795 IOT_CONF_KEY_A2DP_CONN_COUNT);
1796 }
1797 } break;
1798 case BTIF_AV_AVRCP_OPEN_EVT:
1799 case BTA_AV_RC_OPEN_EVT: {
1800 // IOP_FIX: Jabra 620 only does AVRCP Open without AV Open whenever it
1801 // connects. So as per the AV WP, an AVRCP connection cannot exist
1802 // without an AV connection. Therefore, we initiate an AV connection
1803 // if an RC_OPEN_EVT is received when we are in AV_CLOSED state.
1804 // We initiate the AV connection after a small 3s timeout to avoid any
1805 // collisions from the headsets, as some headsets initiate the AVRCP
1806 // connection first and then immediately initiate the AV connection
1807 //
1808 // TODO: We may need to do this only on an AVRCP Play. FixMe
1809 log::warn("Peer {} : event={} received without AV", peer_.PeerAddress(),
1810 BtifAvEvent::EventName(event));
1811
1812 bool can_connect = true;
1813 // Check whether connection is allowed
1814 if (peer_.IsSink()) {
1815 can_connect = btif_av_source.AllowedToConnect(peer_.PeerAddress());
1816 if (!can_connect) {
1817 log::error("Source profile doesn't allow connection to peer:{}",
1818 peer_.PeerAddress());
1819 if (btif_av_src_sink_coexist_enabled())
1820 BTA_AvCloseRc(((tBTA_AV*)p_data)->rc_open.rc_handle);
1821 else
1822 src_disconnect_sink(peer_.PeerAddress());
1823 }
1824 } else if (peer_.IsSource()) {
1825 can_connect = btif_av_sink.AllowedToConnect(peer_.PeerAddress());
1826 if (!can_connect) {
1827 log::error("Sink profile doesn't allow connection to peer:{}",
1828 peer_.PeerAddress());
1829 if (btif_av_src_sink_coexist_enabled())
1830 BTA_AvCloseRc(((tBTA_AV*)p_data)->rc_open.rc_handle);
1831 else
1832 sink_disconnect_src(peer_.PeerAddress());
1833 }
1834 }
1835 if (!can_connect) {
1836 log::error("Cannot connect to peer {}: too many connected peers",
1837 peer_.PeerAddress());
1838 break;
1839 }
1840 /* if peer is source, then start timer for sink connect to src */
1841 if (btif_av_src_sink_coexist_enabled()) {
1842 if (peer_.IsSource()) {
1843 alarm_set_on_mloop(
1844 peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs,
1845 btif_av_sink_initiate_av_open_timer_timeout, &peer_);
1846 } else {
1847 alarm_set_on_mloop(
1848 peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs,
1849 btif_av_source_initiate_av_open_timer_timeout, &peer_);
1850 }
1851 } else {
1852 if (btif_av_source.Enabled()) {
1853 alarm_set_on_mloop(
1854 peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs,
1855 btif_av_source_initiate_av_open_timer_timeout, &peer_);
1856 } else if (btif_av_sink.Enabled()) {
1857 alarm_set_on_mloop(
1858 peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs,
1859 btif_av_sink_initiate_av_open_timer_timeout, &peer_);
1860 }
1861 }
1862 if (event == BTA_AV_RC_OPEN_EVT) {
1863 btif_rc_handler(event, (tBTA_AV*)p_data);
1864 }
1865 } break;
1866
1867 case BTA_AV_RC_BROWSE_OPEN_EVT:
1868 btif_rc_handler(event, (tBTA_AV*)p_data);
1869 break;
1870
1871 // In case Signalling channel is not down and remote started Streaming
1872 // Procedure, we have to handle Config and Open event in Idle state.
1873 // We hit these scenarios while running PTS test case for AVRCP Controller.
1874 case BTIF_AV_SINK_CONFIG_REQ_EVT: {
1875 const btif_av_sink_config_req_t* p_config_req =
1876 static_cast<const btif_av_sink_config_req_t*>(p_data);
1877 btif_av_report_sink_audio_config_state(p_config_req->peer_address,
1878 p_config_req->sample_rate,
1879 p_config_req->channel_count);
1880 } break;
1881
1882 case BTA_AV_OPEN_EVT: {
1883 tBTA_AV* p_bta_data = (tBTA_AV*)p_data;
1884 tBTA_AV_STATUS status = p_bta_data->open.status;
1885 bool can_connect = true;
1886
1887 log::info("Peer {} : event={} flags={} status={}({}) edr=0x{:x}",
1888 peer_.PeerAddress(), BtifAvEvent::EventName(event),
1889 peer_.FlagsToString(), status,
1890 (status == BTA_AV_SUCCESS) ? "SUCCESS" : "FAILED",
1891 p_bta_data->open.edr);
1892
1893 btif_report_connection_state(
1894 peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTING,
1895 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
1896 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
1897
1898 if (p_bta_data->open.status == BTA_AV_SUCCESS) {
1899 peer_.SetEdr(p_bta_data->open.edr);
1900 if (btif_av_src_sink_coexist_enabled()) {
1901 log::verbose("Peer {} sep={}, open_sep={}", peer_.PeerAddress(),
1902 peer_.PeerSep(), p_bta_data->open.sep);
1903 /* if peer is wrong sep type, move it to BtifAvSxxx */
1904 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
1905 if (peer_.PeerSep() == AVDT_TSEP_SNK) {
1906 log::verbose("set source invalid_peer_check as false");
1907 btif_av_source.SetInvalidPeerCheck(false);
1908 } else {
1909 log::verbose("set sink invalid_peer_check as false");
1910 btif_av_sink.SetInvalidPeerCheck(false);
1911 }
1912 }
1913 if (peer_.PeerSep() != p_bta_data->open.sep) {
1914 BtifAvPeer* tmp_peer = nullptr;
1915 if (peer_.PeerSep() == AVDT_TSEP_SNK) {
1916 tmp_peer = btif_av_source.popPeer(peer_.PeerAddress());
1917
1918 if (peer_.PeerAddress() != tmp_peer->PeerAddress())
1919 log::error("error, not same peer");
1920
1921 btif_av_sink.AddPeer(tmp_peer);
1922 } else {
1923 tmp_peer = btif_av_sink.popPeer(peer_.PeerAddress());
1924
1925 if (peer_.PeerAddress() != tmp_peer->PeerAddress())
1926 log::error("error, not same peer");
1927
1928 btif_av_source.AddPeer(tmp_peer);
1929 }
1930 peer_.SetSep(p_bta_data->open.sep);
1931 }
1932 if (btif_rc_is_connected_peer(peer_.PeerAddress())) {
1933 log::verbose("AVRCP connected, update avrc sep");
1934 BTA_AvSetPeerSep(peer_.PeerAddress(), peer_.PeerSep());
1935 }
1936 btif_rc_check_pending_cmd(p_bta_data->open.bd_addr);
1937 }
1938 log::assert_that(
1939 peer_.PeerSep() == p_bta_data->open.sep,
1940 "assert failed: peer_.PeerSep() == p_bta_data->open.sep");
1941
1942 can_connect = peer_.IsSink()
1943 ? btif_av_source.AllowedToConnect(peer_.PeerAddress())
1944 : btif_av_sink.AllowedToConnect(peer_.PeerAddress());
1945
1946 if (!can_connect) {
1947 log::error("Cannot connect to peer {}: too many connected peers",
1948 peer_.PeerAddress());
1949
1950 if (peer_.IsSink()) {
1951 src_disconnect_sink(peer_.PeerAddress());
1952 } else if (peer_.IsSource()) {
1953 sink_disconnect_src(peer_.PeerAddress());
1954 }
1955
1956 btif_report_connection_state(
1957 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
1958 bt_status_t::BT_STATUS_NOMEM, BTA_AV_FAIL_RESOURCES,
1959 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
1960 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
1961 } else {
1962 if (peer_.IsSink()) {
1963 // If queued PLAY command, send it now
1964 btif_rc_check_handle_pending_play(
1965 p_bta_data->open.bd_addr,
1966 (p_bta_data->open.status == BTA_AV_SUCCESS));
1967 } else if (peer_.IsSource() &&
1968 (p_bta_data->open.status == BTA_AV_SUCCESS)) {
1969 // Bring up AVRCP connection as well
1970 BTA_AvOpenRc(peer_.BtaHandle());
1971 }
1972 btif_report_connection_state(
1973 peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTED,
1974 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
1975 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
1976 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpened);
1977 }
1978 } else {
1979 btif_report_connection_state(
1980 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
1981 bt_status_t::BT_STATUS_FAIL, status,
1982 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
1983 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
1984 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(),
1985 IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT);
1986 }
1987 btif_queue_advance();
1988 } break;
1989
1990 case BTA_AV_REMOTE_CMD_EVT:
1991 case BTA_AV_VENDOR_CMD_EVT:
1992 case BTA_AV_META_MSG_EVT:
1993 case BTA_AV_RC_FEAT_EVT:
1994 case BTA_AV_RC_PSM_EVT:
1995 case BTA_AV_REMOTE_RSP_EVT:
1996 btif_rc_handler(event, (tBTA_AV*)p_data);
1997 break;
1998
1999 case BTIF_AV_AVRCP_CLOSE_EVT:
2000 case BTA_AV_RC_CLOSE_EVT: {
2001 log::verbose("Peer {} : event={} : Stopping AV timer",
2002 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2003 alarm_cancel(peer_.AvOpenOnRcTimer());
2004
2005 if (event == BTA_AV_RC_CLOSE_EVT) {
2006 btif_rc_handler(event, (tBTA_AV*)p_data);
2007 }
2008 } break;
2009
2010 case BTIF_AV_OFFLOAD_START_REQ_EVT:
2011 log::error("Peer {} : event={}: stream is not Opened",
2012 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2013 btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL);
2014 break;
2015
2016 default:
2017 log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(),
2018 BtifAvEvent::EventName(event));
2019 return false;
2020 }
2021
2022 return true;
2023 }
2024
OnEnter()2025 void BtifAvStateMachine::StateOpening::OnEnter() {
2026 log::info("state=Opening peer={}", peer_.PeerAddress());
2027
2028 // Inform the application that we are entering connecting state
2029 if (btif_av_both_enable()) {
2030 /* if peer connect to us, don't know which role it is */
2031 if (!peer_.SelfInitiatedConnection()) return;
2032 }
2033 btif_report_connection_state(
2034 peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTING,
2035 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2036 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2037 }
2038
OnExit()2039 void BtifAvStateMachine::StateOpening::OnExit() {
2040 log::info("state=Opening peer={}", peer_.PeerAddress());
2041 }
2042
ProcessEvent(uint32_t event,void * p_data)2043 bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event,
2044 void* p_data) {
2045 log::info("state=Opening peer={} event={} flags={} active_peer={}",
2046 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2047 peer_.FlagsToString(), peer_.IsActivePeer());
2048
2049 switch (event) {
2050 case BTIF_AV_STOP_STREAM_REQ_EVT:
2051 case BTIF_AV_SUSPEND_STREAM_REQ_EVT:
2052 break; // Ignore
2053
2054 case BTIF_AV_ACL_DISCONNECTED:
2055 // ACL Disconnected needs to be handled only in Opening state, because
2056 // it is in an intermediate state. In other states we can handle
2057 // incoming/outgoing connect/disconnect requests.
2058 log::warn(
2059 "Peer {} : event={}: transitioning to Idle due to ACL Disconnect",
2060 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2061 log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::
2062 A2DP_CONNECTION_ACL_DISCONNECTED,
2063 1);
2064 btif_report_connection_state(
2065 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2066 bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL,
2067 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2068 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2069 if (peer_.SelfInitiatedConnection()) {
2070 btif_queue_advance();
2071 }
2072 break;
2073 case BTA_AV_REJECT_EVT:
2074 log::warn("Peer {} : event={} flags={}", peer_.PeerAddress(),
2075 BtifAvEvent::EventName(event), peer_.FlagsToString());
2076 log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::
2077 A2DP_CONNECTION_REJECT_EVT,
2078 1);
2079 btif_report_connection_state(
2080 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2081 bt_status_t::BT_STATUS_AUTH_REJECTED, BTA_AV_FAIL,
2082 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2083 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2084 if (peer_.SelfInitiatedConnection()) {
2085 btif_queue_advance();
2086 }
2087 break;
2088
2089 case BTA_AV_OPEN_EVT: {
2090 tBTA_AV* p_bta_data = (tBTA_AV*)p_data;
2091 int av_state;
2092 tBTA_AV_STATUS status = p_bta_data->open.status;
2093
2094 log::info("Peer {} : event={} flags={} status={}({}) edr=0x{:x}",
2095 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2096 peer_.FlagsToString(), status,
2097 (status == BTA_AV_SUCCESS) ? "SUCCESS" : "FAILED",
2098 p_bta_data->open.edr);
2099
2100 if (p_bta_data->open.status == BTA_AV_SUCCESS) {
2101 av_state = BtifAvStateMachine::kStateOpened;
2102 peer_.SetEdr(p_bta_data->open.edr);
2103 if (btif_av_src_sink_coexist_enabled()) {
2104 log::verbose("Peer {} sep={}, open_sep={}", peer_.PeerAddress(),
2105 peer_.PeerSep(), p_bta_data->open.sep);
2106 /* if peer is wrong sep type, move it to BtifAvSxxx */
2107 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
2108 if (peer_.PeerSep() == AVDT_TSEP_SNK) {
2109 log::verbose("set source invalid_peer_check as false");
2110 btif_av_source.SetInvalidPeerCheck(false);
2111 } else {
2112 log::verbose("set sink invalid_peer_check as false");
2113 btif_av_sink.SetInvalidPeerCheck(false);
2114 }
2115 }
2116 if (peer_.PeerSep() != p_bta_data->open.sep) {
2117 BtifAvPeer* tmp_peer = nullptr;
2118 if (peer_.PeerSep() == AVDT_TSEP_SNK) {
2119 tmp_peer = btif_av_source.popPeer(peer_.PeerAddress());
2120
2121 if (peer_.PeerAddress() != tmp_peer->PeerAddress())
2122 log::error("error, not same peer");
2123
2124 btif_av_sink.AddPeer(tmp_peer);
2125 } else {
2126 tmp_peer = btif_av_sink.popPeer(peer_.PeerAddress());
2127
2128 if (peer_.PeerAddress() != tmp_peer->PeerAddress())
2129 log::error("error, not same peer");
2130
2131 btif_av_source.AddPeer(tmp_peer);
2132 }
2133 peer_.SetSep(p_bta_data->open.sep);
2134 }
2135 if (btif_rc_is_connected_peer(peer_.PeerAddress())) {
2136 log::verbose("AVRCP connected, update avrc sep");
2137 BTA_AvSetPeerSep(peer_.PeerAddress(), peer_.PeerSep());
2138 }
2139 btif_rc_check_pending_cmd(p_bta_data->open.bd_addr);
2140 }
2141 log::assert_that(
2142 peer_.PeerSep() == p_bta_data->open.sep,
2143 "assert failed: peer_.PeerSep() == p_bta_data->open.sep");
2144 /** normally it can be checked in IDLE PENDING/CONNECT_REQ, in case:
2145 * 1 speacker connected to DUT and phone connect DUT, because
2146 * default
2147 * connect req is as SINK peer. only at here, we can know which
2148 * role
2149 * it is.@{ */
2150 if (btif_av_src_sink_coexist_enabled()) {
2151 bool can_connect = true;
2152 if (peer_.IsSink()) {
2153 can_connect = btif_av_source.AllowedToConnect(peer_.PeerAddress());
2154 if (!can_connect) src_disconnect_sink(peer_.PeerAddress());
2155 } else if (peer_.IsSource()) {
2156 can_connect = btif_av_sink.AllowedToConnect(peer_.PeerAddress());
2157 if (!can_connect) sink_disconnect_src(peer_.PeerAddress());
2158 }
2159 }
2160 /** @} */
2161
2162 // Report the connection state to the application
2163 btif_report_connection_state(
2164 peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTED,
2165 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2166 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2167 log_counter_metrics_btif(
2168 android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_SUCCESS,
2169 1);
2170 } else {
2171 if (btif_rc_is_connected_peer(peer_.PeerAddress())) {
2172 // Disconnect the AVRCP connection, in case the A2DP connectiton
2173 // failed for any reason.
2174 log::warn("Peer {} : Disconnecting AVRCP", peer_.PeerAddress());
2175 uint8_t peer_handle =
2176 btif_rc_get_connected_peer_handle(peer_.PeerAddress());
2177 if (peer_handle != BTRC_HANDLE_NONE) {
2178 BTA_AvCloseRc(peer_handle);
2179 }
2180 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(),
2181 IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT);
2182 }
2183 av_state = BtifAvStateMachine::kStateIdle;
2184 // Report the connection state to the application
2185 btif_report_connection_state(
2186 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2187 bt_status_t::BT_STATUS_FAIL, status,
2188 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2189 log_counter_metrics_btif(
2190 android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_FAILURE,
2191 1);
2192 }
2193
2194 // Change state to Open/Idle based on the status
2195 peer_.StateMachine().TransitionTo(av_state);
2196 if (peer_.IsSink()) {
2197 // If queued PLAY command, send it now
2198 btif_rc_check_handle_pending_play(
2199 p_bta_data->open.bd_addr,
2200 (p_bta_data->open.status == BTA_AV_SUCCESS));
2201 } else if (peer_.IsSource() &&
2202 (p_bta_data->open.status == BTA_AV_SUCCESS)) {
2203 // Bring up AVRCP connection as well
2204 if (btif_av_src_sink_coexist_enabled() &&
2205 btif_av_sink.AllowedToConnect(peer_.PeerAddress()))
2206 BTA_AvOpenRc(peer_.BtaHandle());
2207 }
2208 if (peer_.SelfInitiatedConnection()) {
2209 btif_queue_advance();
2210 }
2211 } break;
2212
2213 case BTIF_AV_SINK_CONFIG_REQ_EVT: {
2214 const btif_av_sink_config_req_t* p_config_req =
2215 static_cast<const btif_av_sink_config_req_t*>(p_data);
2216 /* before this point, we don't know it's role, actually peer is source */
2217 if (btif_av_both_enable()) {
2218 btif_av_report_sink_audio_config_state(p_config_req->peer_address,
2219 p_config_req->sample_rate,
2220 p_config_req->channel_count);
2221 break;
2222 }
2223 if (peer_.IsSource()) {
2224 btif_av_report_sink_audio_config_state(p_config_req->peer_address,
2225 p_config_req->sample_rate,
2226 p_config_req->channel_count);
2227 }
2228 } break;
2229
2230 case BTIF_AV_CONNECT_REQ_EVT: {
2231 // The device has moved already to Opening, hence don't report the
2232 // connection state.
2233 log::warn(
2234 "Peer {} : event={} : device is already connecting, ignore Connect "
2235 "request",
2236 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2237 log_counter_metrics_btif(
2238 android::bluetooth::CodePathCounterKeyEnum::A2DP_ALREADY_CONNECTING,
2239 1);
2240 btif_queue_advance();
2241 } break;
2242
2243 case BTA_AV_PENDING_EVT: {
2244 // The device has moved already to Opening, hence don't report the
2245 // connection state.
2246 log::warn(
2247 "Peer {} : event={} : device is already connecting, ignore incoming "
2248 "request",
2249 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2250 log_counter_metrics_btif(
2251 android::bluetooth::CodePathCounterKeyEnum::A2DP_ALREADY_CONNECTING,
2252 1);
2253 } break;
2254
2255 case BTIF_AV_OFFLOAD_START_REQ_EVT:
2256 log::error("Peer {} : event={}: stream is not Opened",
2257 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2258 btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL);
2259 log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::
2260 A2DP_OFFLOAD_START_REQ_FAILURE,
2261 1);
2262 break;
2263
2264 case BTA_AV_CLOSE_EVT:
2265 btif_a2dp_on_stopped(
2266 nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2267 btif_report_connection_state(
2268 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2269 bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL,
2270 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2271 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2272 log_counter_metrics_btif(
2273 android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_CLOSE, 1);
2274 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(),
2275 IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT);
2276 if (peer_.SelfInitiatedConnection()) {
2277 btif_queue_advance();
2278 }
2279 break;
2280
2281 case BTIF_AV_DISCONNECT_REQ_EVT:
2282 BTA_AvClose(peer_.BtaHandle());
2283 btif_report_connection_state(
2284 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2285 bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL,
2286 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2287 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2288 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(),
2289 IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT);
2290 log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::
2291 A2DP_CONNECTION_DISCONNECTED,
2292 1);
2293 if (peer_.SelfInitiatedConnection()) {
2294 btif_queue_advance();
2295 }
2296 break;
2297
2298 CHECK_RC_EVENT(event, (tBTA_AV*)p_data);
2299
2300 default:
2301 log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::
2302 A2DP_CONNECTION_UNKNOWN_EVENT,
2303 1);
2304 log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(),
2305 BtifAvEvent::EventName(event));
2306 return false;
2307 }
2308 return true;
2309 }
2310
OnEnter()2311 void BtifAvStateMachine::StateOpened::OnEnter() {
2312 log::info("state=Opened peer={}", peer_.PeerAddress());
2313
2314 peer_.ClearFlags(BtifAvPeer::kFlagLocalSuspendPending |
2315 BtifAvPeer::kFlagPendingStart |
2316 BtifAvPeer::kFlagPendingStop);
2317
2318 // Set the active peer if the first connected device.
2319 // NOTE: This should be done only if we are A2DP Sink, because the A2DP Sink
2320 // implementation in Java doesn't support active devices (yet).
2321 // For A2DP Source, the setting of the Active device is done by the
2322 // ActiveDeviceManager in Java.
2323 if (peer_.IsSource() && btif_av_sink.ActivePeer().IsEmpty()) {
2324 std::promise<void> peer_ready_promise;
2325 if (!btif_av_sink.SetActivePeer(peer_.PeerAddress(),
2326 std::move(peer_ready_promise))) {
2327 log::error("Error setting {} as active Source peer", peer_.PeerAddress());
2328 }
2329 }
2330 }
2331
OnExit()2332 void BtifAvStateMachine::StateOpened::OnExit() {
2333 log::info("state=Opened peer={}", peer_.PeerAddress());
2334
2335 peer_.ClearFlags(BtifAvPeer::kFlagPendingStart);
2336 }
2337
ProcessEvent(uint32_t event,void * p_data)2338 bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event,
2339 void* p_data) {
2340 tBTA_AV* p_av = (tBTA_AV*)p_data;
2341
2342 log::info("state=Opened peer={} event={} flags={} active_peer={}",
2343 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2344 peer_.FlagsToString(), peer_.IsActivePeer());
2345
2346 if ((event == BTA_AV_REMOTE_CMD_EVT) &&
2347 peer_.CheckFlags(BtifAvPeer::kFlagRemoteSuspend) &&
2348 (p_av->remote_cmd.rc_id == AVRC_ID_PLAY)) {
2349 log::verbose("Peer {} : Resetting remote suspend flag on RC PLAY",
2350 peer_.PeerAddress());
2351 peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend);
2352 }
2353
2354 switch (event) {
2355 case BTIF_AV_STOP_STREAM_REQ_EVT:
2356 case BTIF_AV_SUSPEND_STREAM_REQ_EVT:
2357 case BTIF_AV_ACL_DISCONNECTED:
2358 break; // Ignore
2359
2360 case BTIF_AV_START_STREAM_REQ_EVT: {
2361 log::info("Peer {} : event={} flags={}", peer_.PeerAddress(),
2362 BtifAvEvent::EventName(event), peer_.FlagsToString());
2363 if (p_data) {
2364 const btif_av_start_stream_req_t* p_start_steam_req =
2365 static_cast<const btif_av_start_stream_req_t*>(p_data);
2366 log::info("Stream use_latency_mode={}",
2367 p_start_steam_req->use_latency_mode);
2368 peer_.SetUseLatencyMode(p_start_steam_req->use_latency_mode);
2369 }
2370
2371 BTA_AvStart(peer_.BtaHandle(), peer_.UseLatencyMode());
2372 peer_.SetFlags(BtifAvPeer::kFlagPendingStart);
2373 } break;
2374
2375 case BTA_AV_START_EVT: {
2376 log::info(
2377 "Peer {} : event={} status={} suspending={} initiator={} flags={}",
2378 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2379 p_av->start.status, p_av->start.suspending, p_av->start.initiator,
2380 peer_.FlagsToString());
2381
2382 if ((p_av->start.status == BTA_SUCCESS) && p_av->start.suspending)
2383 return true;
2384
2385 // If remote tries to start A2DP when DUT is A2DP Source, then Suspend.
2386 // If A2DP is Sink and call is active, then disconnect the AVDTP
2387 // channel.
2388 bool should_suspend = false;
2389 if (peer_.IsSink()) {
2390 if (!peer_.CheckFlags(BtifAvPeer::kFlagPendingStart |
2391 BtifAvPeer::kFlagRemoteSuspend)) {
2392 log::warn("Peer {} : trigger Suspend as remote initiated",
2393 peer_.PeerAddress());
2394 should_suspend = true;
2395 } else if (!peer_.IsActivePeer()) {
2396 log::warn("Peer {} : trigger Suspend as non-active",
2397 peer_.PeerAddress());
2398 should_suspend = true;
2399 }
2400
2401 // If peer is A2DP Source, do ACK commands to audio HAL and start
2402 // media task
2403 if (btif_a2dp_on_started(
2404 peer_.PeerAddress(), &p_av->start,
2405 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource)) {
2406 // Only clear pending flag after acknowledgement
2407 peer_.ClearFlags(BtifAvPeer::kFlagPendingStart);
2408 }
2409 }
2410
2411 // Remain in Open state if status failed
2412 if (p_av->start.status != BTA_AV_SUCCESS) return false;
2413
2414 if (peer_.IsSource() && peer_.IsActivePeer()) {
2415 // Remove flush state, ready for streaming
2416 btif_a2dp_sink_set_rx_flush(false);
2417 btif_a2dp_sink_on_start();
2418 }
2419
2420 if (should_suspend) {
2421 btif_av_source_dispatch_sm_event(peer_.PeerAddress(),
2422 BTIF_AV_SUSPEND_STREAM_REQ_EVT);
2423 }
2424 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateStarted);
2425
2426 } break;
2427
2428 case BTIF_AV_DISCONNECT_REQ_EVT:
2429 BTA_AvClose(peer_.BtaHandle());
2430 if (peer_.IsSource()) {
2431 BTA_AvCloseRc(peer_.BtaHandle());
2432 }
2433
2434 // Inform the application that we are disconnecting
2435 btif_report_connection_state(
2436 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING,
2437 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2438 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2439
2440 // Wait in closing state until fully closed
2441 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateClosing);
2442 break;
2443
2444 case BTA_AV_CLOSE_EVT:
2445 // AVDTP link is closed
2446 // Inform the application that we are disconnecting
2447 btif_report_connection_state(
2448 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING,
2449 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2450 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2451 // Change state to Idle, send acknowledgement if start is pending
2452 if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) {
2453 log::warn("Peer {} : failed pending start request",
2454 peer_.PeerAddress());
2455 tBTA_AV_START av_start = {.chnl = p_av->close.chnl,
2456 .hndl = p_av->close.hndl,
2457 .status = BTA_AV_FAIL_STREAM,
2458 .initiator = true,
2459 .suspending = true};
2460 btif_a2dp_on_started(
2461 peer_.PeerAddress(), &av_start,
2462 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2463 // Pending start flag will be cleared when exit current state
2464 } else if (peer_.IsActivePeer()) {
2465 btif_a2dp_on_stopped(
2466 nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2467 }
2468
2469 // Inform the application that we are disconnected
2470 btif_report_connection_state(
2471 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2472 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2473 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2474 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2475 break;
2476
2477 case BTA_AV_RECONFIG_EVT:
2478 if (p_av->reconfig.status != BTA_AV_SUCCESS) {
2479 log::warn("Peer {} : failed reconfiguration", peer_.PeerAddress());
2480 if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) {
2481 log::error("Peer {} : cannot proceed to do AvStart",
2482 peer_.PeerAddress());
2483 peer_.ClearFlags(BtifAvPeer::kFlagPendingStart);
2484 btif_a2dp_command_ack(A2DP_CTRL_ACK_FAILURE);
2485 }
2486 if (peer_.IsSink()) {
2487 src_disconnect_sink(peer_.PeerAddress());
2488 } else if (peer_.IsSource()) {
2489 sink_disconnect_src(peer_.PeerAddress());
2490 }
2491 break;
2492 }
2493
2494 if (peer_.IsActivePeer()) {
2495 log::info(
2496 "Peer {} : Reconfig done - calling startSession() to audio HAL",
2497 peer_.PeerAddress());
2498 std::promise<void> peer_ready_promise;
2499 std::future<void> peer_ready_future = peer_ready_promise.get_future();
2500 btif_a2dp_source_start_session(peer_.PeerAddress(),
2501 std::move(peer_ready_promise));
2502 }
2503 if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) {
2504 log::info("Peer {} : Reconfig done - calling BTA_AvStart(0x{:x})",
2505 peer_.PeerAddress(), peer_.BtaHandle());
2506 BTA_AvStart(peer_.BtaHandle(), peer_.UseLatencyMode());
2507 }
2508 break;
2509
2510 case BTIF_AV_CONNECT_REQ_EVT: {
2511 log::warn("Peer {} : Ignore {} for same device", peer_.PeerAddress(),
2512 BtifAvEvent::EventName(event));
2513 btif_queue_advance();
2514 } break;
2515
2516 case BTIF_AV_OFFLOAD_START_REQ_EVT:
2517 log::error("Peer {} : event={}: stream is not Started",
2518 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2519 btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL);
2520 break;
2521
2522 case BTIF_AV_AVRCP_REMOTE_PLAY_EVT:
2523 if (peer_.CheckFlags(BtifAvPeer::kFlagRemoteSuspend)) {
2524 log::verbose("Peer {} : Resetting remote suspend flag on RC PLAY",
2525 peer_.PeerAddress());
2526 peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend);
2527 }
2528 break;
2529
2530 CHECK_RC_EVENT(event, (tBTA_AV*)p_data);
2531
2532 case BTIF_AV_SET_LATENCY_REQ_EVT: {
2533 const btif_av_set_latency_req_t* p_set_latency_req =
2534 static_cast<const btif_av_set_latency_req_t*>(p_data);
2535 log::info("Peer {} : event={} flags={} is_low_latency={}",
2536 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2537 peer_.FlagsToString(), p_set_latency_req->is_low_latency);
2538
2539 BTA_AvSetLatency(peer_.BtaHandle(), p_set_latency_req->is_low_latency);
2540 } break;
2541
2542 default:
2543 log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(),
2544 BtifAvEvent::EventName(event));
2545 return false;
2546 }
2547 return true;
2548 }
2549
OnEnter()2550 void BtifAvStateMachine::StateStarted::OnEnter() {
2551 log::info("state=Started peer={}", peer_.PeerAddress());
2552
2553 // We are again in started state, clear any remote suspend flags
2554 peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend);
2555
2556 btif_a2dp_sink_set_rx_flush(false);
2557
2558 // Report that we have entered the Streaming stage. Usually, this should
2559 // be followed by focus grant. See update_audio_focus_state()
2560 btif_report_audio_state(
2561 peer_.PeerAddress(), BTAV_AUDIO_STATE_STARTED,
2562 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2563 }
2564
OnExit()2565 void BtifAvStateMachine::StateStarted::OnExit() {
2566 log::info("state=Started peer={}", peer_.PeerAddress());
2567 }
2568
ProcessEvent(uint32_t event,void * p_data)2569 bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event,
2570 void* p_data) {
2571 tBTA_AV* p_av = (tBTA_AV*)p_data;
2572
2573 log::info("state=Started peer={} event={} flags={} active_peer={}",
2574 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2575 peer_.FlagsToString(), peer_.IsActivePeer());
2576
2577 switch (event) {
2578 case BTIF_AV_ACL_DISCONNECTED:
2579 break; // Ignore
2580
2581 case BTIF_AV_START_STREAM_REQ_EVT:
2582 log::info("Peer {} : event={} flags={}", peer_.PeerAddress(),
2583 BtifAvEvent::EventName(event), peer_.FlagsToString());
2584 // We were started remotely, just ACK back the local request
2585 if (peer_.IsSink())
2586 btif_a2dp_on_started(
2587 peer_.PeerAddress(), nullptr,
2588 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2589 break;
2590
2591 // FIXME -- use suspend = true always to work around issue with BTA AV
2592 case BTIF_AV_STOP_STREAM_REQ_EVT:
2593 case BTIF_AV_SUSPEND_STREAM_REQ_EVT:
2594 log::info("Peer {} : event={} flags={}", peer_.PeerAddress(),
2595 BtifAvEvent::EventName(event), peer_.FlagsToString());
2596
2597 // There is a pending LocalSuspend already, ignore.
2598 if (peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending)) {
2599 break;
2600 }
2601
2602 // Set pending flag to ensure the BTIF task is not trying to restart
2603 // the stream while suspend is in progress.
2604 peer_.SetFlags(BtifAvPeer::kFlagLocalSuspendPending);
2605
2606 // If we were remotely suspended but suspend locally, local suspend
2607 // always overrides.
2608 peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend);
2609
2610 if (peer_.IsSink() &&
2611 (peer_.IsActivePeer() ||
2612 !btif_av_stream_started_ready(A2dpType::kSource))) {
2613 // Immediately stop transmission of frames while suspend is pending
2614 if (event == BTIF_AV_STOP_STREAM_REQ_EVT) {
2615 btif_a2dp_on_stopped(
2616 nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2617 } else {
2618 // ensure tx frames are immediately suspended
2619 btif_a2dp_source_set_tx_flush(true);
2620 }
2621 } else if (peer_.IsSource()) {
2622 btif_a2dp_on_stopped(
2623 nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2624 }
2625 BTA_AvStop(peer_.BtaHandle(), true);
2626 break;
2627
2628 case BTIF_AV_DISCONNECT_REQ_EVT:
2629 log::info("Peer {} : event={} flags={}", peer_.PeerAddress(),
2630 BtifAvEvent::EventName(event), peer_.FlagsToString());
2631
2632 // Request AVDTP to close
2633 BTA_AvClose(peer_.BtaHandle());
2634 if (peer_.IsSource()) {
2635 BTA_AvCloseRc(peer_.BtaHandle());
2636 }
2637
2638 // Inform the application that we are disconnecting
2639 btif_report_connection_state(
2640 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING,
2641 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2642 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2643
2644 // Wait in closing state until fully closed
2645 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateClosing);
2646 break;
2647
2648 case BTA_AV_SUSPEND_EVT: {
2649 log::info("Peer {} : event={} status={} initiator={} flags={}",
2650 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2651 p_av->suspend.status, p_av->suspend.initiator,
2652 peer_.FlagsToString());
2653
2654 // A2DP suspended, stop A2DP encoder / decoder until resumed
2655 if (peer_.IsActivePeer() ||
2656 !btif_av_stream_started_ready(peer_.IsSource() ? A2dpType::kSink
2657 : A2dpType::kSource)) {
2658 btif_a2dp_on_suspended(&p_av->suspend, peer_.IsSource()
2659 ? A2dpType::kSink
2660 : A2dpType::kSource);
2661 }
2662
2663 // If not successful, remain in current state
2664 if (p_av->suspend.status != BTA_AV_SUCCESS) {
2665 peer_.ClearFlags(BtifAvPeer::kFlagLocalSuspendPending);
2666
2667 if (peer_.IsSink() && peer_.IsActivePeer()) {
2668 // Suspend failed, reset back tx flush state
2669 btif_a2dp_source_set_tx_flush(false);
2670 }
2671 return false;
2672 }
2673
2674 btav_audio_state_t state = BTAV_AUDIO_STATE_REMOTE_SUSPEND;
2675 if (p_av->suspend.initiator != true) {
2676 // Remote suspend, notify HAL and await audioflinger to
2677 // suspend/stop stream.
2678 //
2679 // Set remote suspend flag to block media task from restarting
2680 // stream only if we did not already initiate a local suspend.
2681 if (!peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending))
2682 peer_.SetFlags(BtifAvPeer::kFlagRemoteSuspend);
2683 } else {
2684 state = BTAV_AUDIO_STATE_STOPPED;
2685 }
2686
2687 btif_report_audio_state(
2688 peer_.PeerAddress(), state,
2689 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2690 // Suspend completed, clear local pending flags while entering Opened
2691 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpened);
2692 } break;
2693
2694 case BTA_AV_STOP_EVT:
2695 log::info("Peer {} : event={} flags={}", peer_.PeerAddress(),
2696 BtifAvEvent::EventName(event), peer_.FlagsToString());
2697
2698 peer_.SetFlags(BtifAvPeer::kFlagPendingStop);
2699 peer_.ClearFlags(BtifAvPeer::kFlagLocalSuspendPending);
2700
2701 // Don't change the encoder and audio provider state by a non-active
2702 // peer since they are shared between peers
2703 if (peer_.IsActivePeer() ||
2704 !btif_av_stream_started_ready(peer_.IsSource() ? A2dpType::kSink
2705 : A2dpType::kSource)) {
2706 btif_a2dp_on_stopped(&p_av->suspend, peer_.IsSource()
2707 ? A2dpType::kSink
2708 : A2dpType::kSource);
2709 }
2710
2711 btif_report_audio_state(
2712 peer_.PeerAddress(), BTAV_AUDIO_STATE_STOPPED,
2713 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2714
2715 // If stop was successful, change state to Open
2716 if (p_av->suspend.status == BTA_AV_SUCCESS)
2717 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpened);
2718
2719 break;
2720
2721 case BTA_AV_CLOSE_EVT:
2722 log::info("Peer {} : event={} flags={}", peer_.PeerAddress(),
2723 BtifAvEvent::EventName(event), peer_.FlagsToString());
2724 // Inform the application that we are disconnecting
2725 btif_report_connection_state(
2726 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING,
2727 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2728 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2729
2730 peer_.SetFlags(BtifAvPeer::kFlagPendingStop);
2731
2732 // AVDTP link is closed
2733 if (peer_.IsActivePeer()) {
2734 btif_a2dp_on_stopped(
2735 nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2736 }
2737
2738 // Inform the application that we are disconnected
2739 btif_report_connection_state(
2740 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2741 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2742 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2743
2744 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2745 break;
2746
2747 case BTIF_AV_OFFLOAD_START_REQ_EVT:
2748 if (peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending |
2749 BtifAvPeer::kFlagRemoteSuspend |
2750 BtifAvPeer::kFlagPendingStop)) {
2751 log::warn("Peer {} : event={} flags={}: stream is Suspending",
2752 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2753 peer_.FlagsToString());
2754 btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL);
2755 break;
2756 }
2757 BTA_AvOffloadStart(peer_.BtaHandle());
2758 break;
2759
2760 case BTA_AV_OFFLOAD_START_RSP_EVT:
2761 btif_a2dp_on_offload_started(peer_.PeerAddress(), p_av->status);
2762 break;
2763
2764 case BTIF_AV_SET_LATENCY_REQ_EVT: {
2765 const btif_av_set_latency_req_t* p_set_latency_req =
2766 static_cast<const btif_av_set_latency_req_t*>(p_data);
2767 log::info("Peer {} : event={} flags={} is_low_latency={}",
2768 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2769 peer_.FlagsToString(), p_set_latency_req->is_low_latency);
2770
2771 BTA_AvSetLatency(peer_.BtaHandle(), p_set_latency_req->is_low_latency);
2772 } break;
2773
2774 CHECK_RC_EVENT(event, (tBTA_AV*)p_data);
2775
2776 default:
2777 log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(),
2778 BtifAvEvent::EventName(event));
2779 return false;
2780 }
2781
2782 return true;
2783 }
2784
OnEnter()2785 void BtifAvStateMachine::StateClosing::OnEnter() {
2786 log::info("state=Closing peer={}", peer_.PeerAddress());
2787
2788 if (peer_.IsActivePeer()) {
2789 if (peer_.IsSink()) {
2790 // Immediately stop transmission of frames
2791 btif_a2dp_source_set_tx_flush(true);
2792 // Wait for Audio Flinger to stop A2DP
2793 } else if (peer_.IsSource()) {
2794 btif_a2dp_sink_set_rx_flush(true);
2795 }
2796 }
2797 }
2798
OnExit()2799 void BtifAvStateMachine::StateClosing::OnExit() {
2800 log::info("state=Closing peer={}", peer_.PeerAddress());
2801 }
2802
ProcessEvent(uint32_t event,void * p_data)2803 bool BtifAvStateMachine::StateClosing::ProcessEvent(uint32_t event,
2804 void* p_data) {
2805 log::info("state=Closing peer={} event={} flags={} active_peer={}",
2806 peer_.PeerAddress(), BtifAvEvent::EventName(event),
2807 peer_.FlagsToString(), peer_.IsActivePeer());
2808
2809 switch (event) {
2810 case BTIF_AV_SUSPEND_STREAM_REQ_EVT:
2811 case BTIF_AV_ACL_DISCONNECTED:
2812 break; // Ignore
2813
2814 case BTA_AV_STOP_EVT:
2815 case BTIF_AV_STOP_STREAM_REQ_EVT:
2816 if (peer_.IsActivePeer()) {
2817 btif_a2dp_on_stopped(
2818 nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2819 }
2820 break;
2821
2822 case BTA_AV_CLOSE_EVT:
2823 // Inform the application that we are disconnecting
2824 btif_report_connection_state(
2825 peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED,
2826 bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS,
2827 peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource);
2828
2829 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2830 break;
2831
2832 // Handle the RC_CLOSE event for the cleanup
2833 case BTA_AV_RC_CLOSE_EVT:
2834 btif_rc_handler(event, (tBTA_AV*)p_data);
2835 break;
2836
2837 // Handle the RC_BROWSE_CLOSE event for testing
2838 case BTA_AV_RC_BROWSE_CLOSE_EVT:
2839 btif_rc_handler(event, (tBTA_AV*)p_data);
2840 break;
2841
2842 case BTIF_AV_OFFLOAD_START_REQ_EVT:
2843 log::error("Peer {} : event={}: stream is not Opened",
2844 peer_.PeerAddress(), BtifAvEvent::EventName(event));
2845 btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL);
2846 break;
2847
2848 case BTIF_AV_CONNECT_REQ_EVT:
2849 log::warn("Peer {} : Ignore {} in StateClosing", peer_.PeerAddress(),
2850 BtifAvEvent::EventName(event));
2851 btif_queue_advance();
2852 peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle);
2853 break;
2854
2855 default:
2856 log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(),
2857 BtifAvEvent::EventName(event));
2858 return false;
2859 }
2860 return true;
2861 }
2862
2863 /**
2864 * Timer to trigger AV Open on the Source if the remote Sink device
2865 * establishes AVRCP connection without AV connection. The timer is needed to
2866 * interoperate with headsets that do establish AV after AVRCP connection.
2867 */
btif_av_source_initiate_av_open_timer_timeout(void * data)2868 static void btif_av_source_initiate_av_open_timer_timeout(void* data) {
2869 BtifAvPeer* peer = (BtifAvPeer*)data;
2870 bool device_connected = false;
2871
2872 if (com::android::bluetooth::flags::avrcp_connect_a2dp_delayed() &&
2873 is_new_avrcp_enabled()) {
2874 // check if device is connected
2875 if (bluetooth::avrcp::AvrcpService::Get() != nullptr) {
2876 device_connected =
2877 bluetooth::avrcp::AvrcpService::Get()->IsDeviceConnected(
2878 peer->PeerAddress());
2879 }
2880 } else {
2881 device_connected = btif_rc_is_connected_peer(peer->PeerAddress());
2882 }
2883
2884 log::verbose("Peer {}", peer->PeerAddress());
2885
2886 // Check if AVRCP is connected to the peer
2887 if (!device_connected) {
2888 log::error("AVRCP peer {} is not connected", peer->PeerAddress());
2889 return;
2890 }
2891
2892 // Connect to the AVRCP peer
2893 if (btif_av_source.Enabled() &&
2894 btif_av_source.FindPeer(peer->PeerAddress()) == peer) {
2895 log::verbose("Connecting to AVRCP peer {}", peer->PeerAddress());
2896 btif_av_source_dispatch_sm_event(peer->PeerAddress(),
2897 BTIF_AV_CONNECT_REQ_EVT);
2898 }
2899 }
2900
2901 /**
2902 * Timer to trigger AV Open on the Sink if the remote Source device
2903 * establishes AVRCP connection without AV connection.
2904 */
btif_av_sink_initiate_av_open_timer_timeout(void * data)2905 static void btif_av_sink_initiate_av_open_timer_timeout(void* data) {
2906 BtifAvPeer* peer = (BtifAvPeer*)data;
2907
2908 log::verbose("Peer {}", peer->PeerAddress());
2909
2910 // Check if AVRCP is connected to the peer
2911 if (!btif_rc_is_connected_peer(peer->PeerAddress())) {
2912 log::error("AVRCP peer {} is not connected", peer->PeerAddress());
2913 return;
2914 }
2915
2916 // Connect to the AVRCP peer
2917 if (btif_av_sink.Enabled() &&
2918 btif_av_sink.FindPeer(peer->PeerAddress()) == peer) {
2919 log::verbose("Connecting to AVRCP peer {}", peer->PeerAddress());
2920 btif_av_sink_dispatch_sm_event(peer->PeerAddress(),
2921 BTIF_AV_CONNECT_REQ_EVT);
2922 }
2923 }
2924
2925 /**
2926 * Report the A2DP connection state
2927 *
2928 * @param peer_address the peer address
2929 * @param state the connection state
2930 */
btif_report_connection_state(const RawAddress & peer_address,btav_connection_state_t state,bt_status_t status,uint8_t error_code,const A2dpType local_a2dp_type)2931 static void btif_report_connection_state(const RawAddress& peer_address,
2932 btav_connection_state_t state,
2933 bt_status_t status, uint8_t error_code,
2934 const A2dpType local_a2dp_type) {
2935 log::info("peer={} state={}", peer_address, state);
2936 if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
2937 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
2938 if (peer == nullptr) {
2939 log::error("peer is null");
2940 return;
2941 }
2942
2943 if (peer->IsSink()) {
2944 do_in_jni_thread(
2945 base::BindOnce(btif_av_source.Callbacks()->connection_state_cb,
2946 peer_address, state, btav_error_t{}));
2947 } else if (peer->IsSource()) {
2948 do_in_jni_thread(
2949 base::BindOnce(btif_av_sink.Callbacks()->connection_state_cb,
2950 peer_address, state, btav_error_t{}));
2951 }
2952 return;
2953 }
2954
2955 if (btif_av_source.Enabled()) {
2956 do_in_jni_thread(base::BindOnce(
2957 btif_av_source.Callbacks()->connection_state_cb, peer_address, state,
2958 btav_error_t{.status = status, .error_code = error_code}));
2959 } else if (btif_av_sink.Enabled()) {
2960 do_in_jni_thread(base::BindOnce(
2961 btif_av_sink.Callbacks()->connection_state_cb, peer_address, state,
2962 btav_error_t{.status = status, .error_code = error_code}));
2963 }
2964 }
2965
2966 /**
2967 * Report the audio state of the A2DP connection.
2968 * The state is updated when either the remote ends starts streaming
2969 * (Started state) or whenever it transitions out of Started state
2970 * (to Opened or Streaming state).
2971 *
2972 * @param peer_address the peer address
2973 * @param state the audio state
2974 */
btif_report_audio_state(const RawAddress & peer_address,btav_audio_state_t state,const A2dpType local_a2dp_type)2975 static void btif_report_audio_state(const RawAddress& peer_address,
2976 btav_audio_state_t state,
2977 const A2dpType local_a2dp_type) {
2978 log::info("peer={} state={}", peer_address, state);
2979
2980 if (btif_av_both_enable()) {
2981 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
2982 if (peer->IsSink()) {
2983 do_in_jni_thread(base::BindOnce(
2984 btif_av_source.Callbacks()->audio_state_cb, peer_address, state));
2985 } else if (peer->IsSource()) {
2986 do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_state_cb,
2987 peer_address, state));
2988 }
2989 return;
2990 }
2991 if (btif_av_source.Enabled()) {
2992 do_in_jni_thread(base::BindOnce(btif_av_source.Callbacks()->audio_state_cb,
2993 peer_address, state));
2994 } else if (btif_av_sink.Enabled()) {
2995 do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_state_cb,
2996 peer_address, state));
2997 }
2998
2999 using android::bluetooth::a2dp::AudioCodingModeEnum;
3000 using android::bluetooth::a2dp::PlaybackStateEnum;
3001 PlaybackStateEnum playback_state = PlaybackStateEnum::PLAYBACK_STATE_UNKNOWN;
3002 switch (state) {
3003 case BTAV_AUDIO_STATE_STARTED:
3004 playback_state = PlaybackStateEnum::PLAYBACK_STATE_PLAYING;
3005 break;
3006 case BTAV_AUDIO_STATE_STOPPED:
3007 playback_state = PlaybackStateEnum::PLAYBACK_STATE_NOT_PLAYING;
3008 break;
3009 default:
3010 break;
3011 }
3012 AudioCodingModeEnum audio_coding_mode =
3013 btif_av_is_a2dp_offload_running()
3014 ? AudioCodingModeEnum::AUDIO_CODING_MODE_HARDWARE
3015 : AudioCodingModeEnum::AUDIO_CODING_MODE_SOFTWARE;
3016
3017 log_a2dp_playback_event(peer_address, playback_state, audio_coding_mode);
3018 }
3019
btif_av_report_source_codec_state(const RawAddress & peer_address,const btav_a2dp_codec_config_t & codec_config,const std::vector<btav_a2dp_codec_config_t> & codecs_local_capabilities,const std::vector<btav_a2dp_codec_config_t> & codecs_selectable_capabilities)3020 void btif_av_report_source_codec_state(
3021 const RawAddress& peer_address,
3022 const btav_a2dp_codec_config_t& codec_config,
3023 const std::vector<btav_a2dp_codec_config_t>& codecs_local_capabilities,
3024 const std::vector<btav_a2dp_codec_config_t>&
3025 codecs_selectable_capabilities) {
3026 log::verbose("peer={}", peer_address);
3027 if (btif_av_source.Enabled()) {
3028 do_in_jni_thread(base::BindOnce(
3029 btif_av_source.Callbacks()->audio_config_cb, peer_address, codec_config,
3030 codecs_local_capabilities, codecs_selectable_capabilities));
3031 }
3032 }
3033
3034 /**
3035 * Report the audio config state of the A2DP Sink connection.
3036 *
3037 * @param peer_address the peer address
3038 * @param sample_rate the sample rate (in samples per second)
3039 * @param channel_count the channel count (1 for Mono, 2 for Stereo)
3040 */
btif_av_report_sink_audio_config_state(const RawAddress & peer_address,int sample_rate,int channel_count)3041 static void btif_av_report_sink_audio_config_state(
3042 const RawAddress& peer_address, int sample_rate, int channel_count) {
3043 log::info("peer={} sample_rate={} channel_count={}", peer_address,
3044 sample_rate, channel_count);
3045 if (btif_av_sink.Enabled()) {
3046 do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_config_cb,
3047 peer_address, sample_rate, channel_count));
3048 }
3049 }
3050
3051 /**
3052 * Call out to JNI / JAVA layers to retrieve whether the mandatory codec is
3053 * more preferred than others.
3054 *
3055 * @param peer_address the peer address
3056 */
btif_av_query_mandatory_codec_priority(const RawAddress & peer_address)3057 static void btif_av_query_mandatory_codec_priority(
3058 const RawAddress& peer_address) {
3059 auto query_priority = [](const RawAddress& peer_address) {
3060 if (!btif_av_source.Enabled()) {
3061 log::warn("BTIF AV Source is not enabled");
3062 return;
3063 }
3064 btav_source_callbacks_t* callbacks = btif_av_source.Callbacks();
3065 bool preferred = callbacks != nullptr &&
3066 callbacks->mandatory_codec_preferred_cb(peer_address);
3067 if (preferred) {
3068 auto apply_priority = [](const RawAddress& peer_address, bool preferred) {
3069 BtifAvPeer* peer = btif_av_find_peer(peer_address, A2dpType::kSource);
3070 if (peer == nullptr) {
3071 log::warn("btif_av_query_mandatory_codec_priority: peer is null");
3072 return;
3073 }
3074 peer->SetMandatoryCodecPreferred(preferred);
3075 };
3076 do_in_main_thread(
3077 FROM_HERE, base::BindOnce(apply_priority, peer_address, preferred));
3078 }
3079 };
3080 if (btif_av_source.Enabled()) {
3081 do_in_jni_thread(base::BindOnce(query_priority, peer_address));
3082 }
3083 }
3084
btif_av_handle_both_peer(uint8_t peer_sep,const RawAddress & peer_address,tBTA_AV_HNDL bta_handle)3085 static BtifAvPeer* btif_av_handle_both_peer(uint8_t peer_sep,
3086 const RawAddress& peer_address,
3087 tBTA_AV_HNDL bta_handle) {
3088 BtifAvPeer* peer = nullptr;
3089
3090 if (peer_address != RawAddress::kEmpty) {
3091 if (btif_av_both_enable()) {
3092 peer = btif_av_find_peer(peer_address, A2dpType::kUnknown);
3093 /* if no this peer, default it's sink device */
3094 if (peer == nullptr) {
3095 if (peer_sep == AVDT_TSEP_SRC) {
3096 log::verbose("peer_sep({}), create a new source peer", peer_sep);
3097 peer = btif_av_sink.FindOrCreatePeer(peer_address, bta_handle);
3098 } else if (peer_sep == AVDT_TSEP_SNK) {
3099 log::verbose("peer_sep({}), create a new sink peer", peer_sep);
3100 peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle);
3101 } else {
3102 if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
3103 btif_av_source.SetInvalidPeerCheck(true);
3104 }
3105 if (!btif_av_source.Peers().empty()) {
3106 log::verbose(
3107 "peer_sep invalid, and already has sink peer, so try create a "
3108 "new sink peer");
3109 peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle);
3110 } else if (!btif_av_sink.Peers().empty()) {
3111 log::verbose(
3112 "peer_sep invalid, and already has source peer, so try create "
3113 "a new source peer");
3114 peer = btif_av_sink.FindOrCreatePeer(peer_address, bta_handle);
3115 } else {
3116 log::verbose(
3117 "peer_sep invalid, and no active peer, so try create a new "
3118 "sink peer");
3119 peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle);
3120 }
3121 }
3122 }
3123 } else {
3124 if (peer_sep == AVDT_TSEP_SNK) {
3125 log::verbose("peer_sep({}), only init src create a new source peer",
3126 peer_sep);
3127 peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle);
3128 } else if (peer_sep == AVDT_TSEP_SRC) {
3129 log::verbose("peer_sep({}), only init sink create a new source peer",
3130 peer_sep);
3131 peer = btif_av_sink.FindOrCreatePeer(peer_address, bta_handle);
3132 }
3133 }
3134 if (peer == NULL && bta_handle != 0) {
3135 if (peer_sep == AVDT_TSEP_SNK) {
3136 peer = btif_av_source.FindPeerByHandle(bta_handle);
3137 } else if (peer_sep == AVDT_TSEP_SRC) {
3138 peer = btif_av_sink.FindPeerByHandle(bta_handle);
3139 }
3140 log::verbose("peer is check 3");
3141 }
3142 } else if (bta_handle != 0) {
3143 if (peer_sep == AVDT_TSEP_INVALID) {
3144 peer = btif_av_source.FindPeerByHandle(bta_handle);
3145 /* if no this peer, default it's sink device */
3146 if (peer == nullptr) {
3147 peer = btif_av_sink.FindPeerByHandle(bta_handle);
3148 }
3149 } else if (peer_sep == AVDT_TSEP_SNK) {
3150 peer = btif_av_source.FindPeerByHandle(bta_handle);
3151 } else if (peer_sep == AVDT_TSEP_SRC) {
3152 peer = btif_av_sink.FindPeerByHandle(bta_handle);
3153 }
3154 }
3155 return peer;
3156 }
3157
3158 /**
3159 * Process BTIF or BTA AV or BTA AVRCP events. The processing is done on the
3160 * JNI thread.
3161 *
3162 * @param peer_sep the corresponding peer's SEP: AVDT_TSEP_SRC if the peer
3163 * is A2DP Source, or AVDT_TSEP_SNK if the peer is A2DP Sink.
3164 * @param peer_address the peer address if known, otherwise RawAddress::kEmpty
3165 * @param bta_handle the BTA handle for the peer if known, otherwise
3166 * kBtaHandleUnknown
3167 * @param btif_av_event the corresponding event
3168 */
btif_av_handle_event(uint8_t peer_sep,const RawAddress & peer_address,tBTA_AV_HNDL bta_handle,const BtifAvEvent & btif_av_event)3169 static void btif_av_handle_event(uint8_t peer_sep,
3170 const RawAddress& peer_address,
3171 tBTA_AV_HNDL bta_handle,
3172 const BtifAvEvent& btif_av_event) {
3173 log::info("peer={} handle=0x{:x} event={}",
3174 peer_address, bta_handle, btif_av_event.ToString());
3175
3176 BtifAvPeer* peer = nullptr;
3177
3178 // Find the peer
3179 if (btif_av_src_sink_coexist_enabled()) {
3180 peer = btif_av_handle_both_peer(peer_sep, peer_address, bta_handle);
3181 } else {
3182 if (peer_address != RawAddress::kEmpty) {
3183 if (peer_sep == AVDT_TSEP_SNK) {
3184 peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle);
3185 } else if (peer_sep == AVDT_TSEP_SRC) {
3186 peer = btif_av_sink.FindOrCreatePeer(peer_address, bta_handle);
3187 }
3188 } else if (bta_handle != kBtaHandleUnknown) {
3189 if (peer_sep == AVDT_TSEP_SNK) {
3190 peer = btif_av_source.FindPeerByHandle(bta_handle);
3191 } else if (peer_sep == AVDT_TSEP_SRC) {
3192 peer = btif_av_sink.FindPeerByHandle(bta_handle);
3193 }
3194 }
3195 }
3196 if (peer == nullptr) {
3197 log::error(
3198 "Cannot find or create {} peer for peer={} "
3199 "bta_handle=0x{:x} : event dropped: {}",
3200 peer_stream_endpoint_text(peer_sep), peer_address, bta_handle,
3201 btif_av_event.ToString());
3202 return;
3203 }
3204
3205 peer->StateMachine().ProcessEvent(btif_av_event.Event(),
3206 btif_av_event.Data());
3207 }
3208
3209 /**
3210 * Process BTA AV or BTA AVRCP events. The processing is done on the JNI
3211 * thread.
3212 *
3213 * @param peer_sep the corresponding peer's SEP: AVDT_TSEP_SRC if the peer
3214 * is A2DP Source, or AVDT_TSEP_SNK if the peer is A2DP Sink.
3215 * @param btif_av_event the corresponding event
3216 */
btif_av_handle_bta_av_event(uint8_t peer_sep,const BtifAvEvent & btif_av_event)3217 static void btif_av_handle_bta_av_event(uint8_t peer_sep,
3218 const BtifAvEvent& btif_av_event) {
3219 RawAddress peer_address = RawAddress::kEmpty;
3220 tBTA_AV_HNDL bta_handle = kBtaHandleUnknown;
3221 tBTA_AV_EVT event = btif_av_event.Event();
3222 tBTA_AV* p_data = (tBTA_AV*)btif_av_event.Data();
3223 std::string msg;
3224
3225 log::verbose("peer_sep={} event={}", peer_stream_endpoint_text(peer_sep),
3226 btif_av_event.ToString());
3227
3228 switch (event) {
3229 case BTA_AV_ENABLE_EVT: {
3230 const tBTA_AV_ENABLE& enable = p_data->enable;
3231 log::verbose("Enable features=0x{:x}", enable.features);
3232 return; // Nothing to do
3233 }
3234 case BTA_AV_REGISTER_EVT: {
3235 const tBTA_AV_REGISTER& reg = p_data->reg;
3236 bta_handle = reg.hndl;
3237 uint8_t peer_id = reg.app_id; // The PeerId is used as AppId
3238 log::verbose("Register bta_handle=0x{:x} app_id={}", bta_handle,
3239 reg.app_id);
3240 if (btif_av_src_sink_coexist_enabled()) {
3241 if (peer_sep == AVDT_TSEP_INVALID) {
3242 if (reg.peer_sep == AVDT_TSEP_SNK)
3243 peer_sep = AVDT_TSEP_SNK;
3244 else
3245 peer_sep = AVDT_TSEP_SRC;
3246 }
3247 }
3248 if (peer_sep == AVDT_TSEP_SNK) {
3249 btif_av_source.BtaHandleRegistered(peer_id, bta_handle);
3250 } else if (peer_sep == AVDT_TSEP_SRC) {
3251 btif_av_sink.BtaHandleRegistered(peer_id, bta_handle);
3252 }
3253 return; // Nothing else to do
3254 }
3255 case BTA_AV_OPEN_EVT: {
3256 const tBTA_AV_OPEN& open = p_data->open;
3257 peer_address = open.bd_addr;
3258 bta_handle = open.hndl;
3259 msg = "Stream opened";
3260 break;
3261 }
3262 case BTA_AV_CLOSE_EVT: {
3263 const tBTA_AV_CLOSE& close = p_data->close;
3264 bta_handle = close.hndl;
3265 msg = "Stream closed";
3266 break;
3267 }
3268 case BTA_AV_START_EVT: {
3269 const tBTA_AV_START& start = p_data->start;
3270 bta_handle = start.hndl;
3271 msg = "Stream started";
3272 break;
3273 }
3274 case BTA_AV_SUSPEND_EVT:
3275 case BTA_AV_STOP_EVT: {
3276 const tBTA_AV_SUSPEND& suspend = p_data->suspend;
3277 bta_handle = suspend.hndl;
3278 msg = "Stream stopped";
3279 break;
3280 }
3281 case BTA_AV_PROTECT_REQ_EVT: {
3282 const tBTA_AV_PROTECT_REQ& protect_req = p_data->protect_req;
3283 bta_handle = protect_req.hndl;
3284 break;
3285 }
3286 case BTA_AV_PROTECT_RSP_EVT: {
3287 const tBTA_AV_PROTECT_RSP& protect_rsp = p_data->protect_rsp;
3288 bta_handle = protect_rsp.hndl;
3289 break;
3290 }
3291 case BTA_AV_RC_OPEN_EVT: {
3292 const tBTA_AV_RC_OPEN& rc_open = p_data->rc_open;
3293 peer_address = rc_open.peer_addr;
3294 break;
3295 }
3296 case BTA_AV_RC_CLOSE_EVT: {
3297 const tBTA_AV_RC_CLOSE& rc_close = p_data->rc_close;
3298 peer_address = rc_close.peer_addr;
3299 break;
3300 }
3301 case BTA_AV_RC_BROWSE_OPEN_EVT: {
3302 const tBTA_AV_RC_BROWSE_OPEN& rc_browse_open = p_data->rc_browse_open;
3303 peer_address = rc_browse_open.peer_addr;
3304 break;
3305 }
3306 case BTA_AV_RC_BROWSE_CLOSE_EVT: {
3307 const tBTA_AV_RC_BROWSE_CLOSE& rc_browse_close = p_data->rc_browse_close;
3308 peer_address = rc_browse_close.peer_addr;
3309 break;
3310 }
3311 case BTA_AV_REMOTE_CMD_EVT:
3312 case BTA_AV_REMOTE_RSP_EVT:
3313 case BTA_AV_VENDOR_CMD_EVT:
3314 case BTA_AV_VENDOR_RSP_EVT:
3315 case BTA_AV_META_MSG_EVT: {
3316 if (btif_av_src_sink_coexist_enabled()) {
3317 if (peer_sep == AVDT_TSEP_INVALID) {
3318 const tBTA_AV_REMOTE_CMD& rc_rmt_cmd = p_data->remote_cmd;
3319 btif_rc_get_addr_by_handle(rc_rmt_cmd.rc_handle, peer_address);
3320 if (peer_address == RawAddress::kEmpty) {
3321 peer_address = btif_av_source.ActivePeer();
3322 if (peer_address == RawAddress::kEmpty) {
3323 peer_address = btif_av_sink.ActivePeer();
3324 }
3325 }
3326 } else if (peer_sep == AVDT_TSEP_SNK) {
3327 peer_address = btif_av_source.ActivePeer();
3328 } else if (peer_sep == AVDT_TSEP_SRC) {
3329 peer_address = btif_av_sink.ActivePeer();
3330 }
3331 break;
3332 } else
3333 FALLTHROUGH_INTENDED;
3334 }
3335 case BTA_AV_OFFLOAD_START_RSP_EVT: {
3336 // TODO: Might be wrong - this code will be removed once those
3337 // events are received from the AVRCP module.
3338 if (peer_sep == AVDT_TSEP_SNK) {
3339 peer_address = btif_av_source.ActivePeer();
3340 msg = "Stream sink offloaded";
3341 } else if (peer_sep == AVDT_TSEP_SRC) {
3342 peer_address = btif_av_sink.ActivePeer();
3343 msg = "Stream source offloaded";
3344 }
3345 break;
3346 }
3347 case BTA_AV_RECONFIG_EVT: {
3348 const tBTA_AV_RECONFIG& reconfig = p_data->reconfig;
3349 bta_handle = reconfig.hndl;
3350 break;
3351 }
3352 case BTA_AV_PENDING_EVT: {
3353 const tBTA_AV_PEND& pend = p_data->pend;
3354 peer_address = pend.bd_addr;
3355 break;
3356 }
3357 case BTA_AV_REJECT_EVT: {
3358 const tBTA_AV_REJECT& reject = p_data->reject;
3359 peer_address = reject.bd_addr;
3360 bta_handle = reject.hndl;
3361 break;
3362 }
3363 case BTA_AV_RC_FEAT_EVT: {
3364 const tBTA_AV_RC_FEAT& rc_feat = p_data->rc_feat;
3365 peer_address = rc_feat.peer_addr;
3366 break;
3367 }
3368 case BTA_AV_RC_PSM_EVT: {
3369 const tBTA_AV_RC_PSM& rc_psm = p_data->rc_cover_art_psm;
3370 peer_address = rc_psm.peer_addr;
3371 break;
3372 }
3373 }
3374
3375 if (!msg.empty()) {
3376 BTM_LogHistory(kBtmLogHistoryTag, peer_address, msg,
3377 btif_av_event.ToString());
3378 }
3379 btif_av_handle_event(peer_sep, peer_address, bta_handle, btif_av_event);
3380 }
3381
btif_av_both_enable(void)3382 bool btif_av_both_enable(void) {
3383 return (btif_av_sink.Enabled() && btif_av_source.Enabled());
3384 }
3385
is_a2dp_source_property_enabled(void)3386 bool is_a2dp_source_property_enabled(void) {
3387 #ifdef __ANDROID__
3388 return android::sysprop::BluetoothProperties::isProfileA2dpSourceEnabled()
3389 .value_or(false);
3390 #else
3391 return false;
3392 #endif
3393 }
3394
is_a2dp_sink_property_enabled(void)3395 bool is_a2dp_sink_property_enabled(void) {
3396 #ifdef __ANDROID__
3397 return android::sysprop::BluetoothProperties::isProfileA2dpSinkEnabled()
3398 .value_or(false);
3399 #else
3400 return false;
3401 #endif
3402 }
btif_av_src_sink_coexist_enabled(void)3403 bool btif_av_src_sink_coexist_enabled(void) {
3404 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) {
3405 return is_a2dp_sink_property_enabled() && is_a2dp_source_property_enabled();
3406 }
3407 return GET_SYSPROP(A2dp, src_sink_coexist, false);
3408 }
3409
bta_av_source_callback(tBTA_AV_EVT event,tBTA_AV * p_data)3410 static void bta_av_source_callback(tBTA_AV_EVT event, tBTA_AV* p_data) {
3411 BtifAvEvent btif_av_event(event, p_data, sizeof(tBTA_AV));
3412 log::verbose("event={}", btif_av_event.ToString());
3413
3414 do_in_main_thread(
3415 FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event,
3416 AVDT_TSEP_SNK /* peer_sep */, btif_av_event));
3417 }
3418
bta_av_sink_callback(tBTA_AV_EVT event,tBTA_AV * p_data)3419 static void bta_av_sink_callback(tBTA_AV_EVT event, tBTA_AV* p_data) {
3420 BtifAvEvent btif_av_event(event, p_data, sizeof(tBTA_AV));
3421 do_in_main_thread(
3422 FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event,
3423 AVDT_TSEP_SRC /* peer_sep */, btif_av_event));
3424 }
3425
bta_av_event_callback(tBTA_AV_EVT event,tBTA_AV * p_data)3426 static void bta_av_event_callback(tBTA_AV_EVT event, tBTA_AV* p_data) {
3427 if (btif_av_both_enable()) {
3428 BtifAvEvent btif_av_event(event, p_data, sizeof(tBTA_AV));
3429 do_in_main_thread(
3430 FROM_HERE,
3431 base::BindOnce(&btif_av_handle_bta_av_event,
3432 AVDT_TSEP_INVALID /* peer_sep */, btif_av_event));
3433 return;
3434 }
3435
3436 if (btif_av_is_sink_enabled()) {
3437 return bta_av_sink_callback(event, p_data);
3438 }
3439
3440 return bta_av_source_callback(event, p_data);
3441 }
3442
3443 // TODO: All processing should be done on the JNI thread
bta_av_sink_media_callback(const RawAddress & peer_address,tBTA_AV_EVT event,tBTA_AV_MEDIA * p_data)3444 static void bta_av_sink_media_callback(const RawAddress& peer_address,
3445 tBTA_AV_EVT event,
3446 tBTA_AV_MEDIA* p_data) {
3447 log::verbose("event={}", event);
3448
3449 switch (event) {
3450 case BTA_AV_SINK_MEDIA_DATA_EVT: {
3451 BtifAvPeer* peer = btif_av_sink_find_peer(peer_address);
3452 if (peer != nullptr && peer->IsActivePeer()) {
3453 int state = peer->StateMachine().StateId();
3454 if ((state == BtifAvStateMachine::kStateStarted) ||
3455 (state == BtifAvStateMachine::kStateOpened)) {
3456 uint8_t queue_len = btif_a2dp_sink_enqueue_buf((BT_HDR*)p_data);
3457 log::verbose("Packets in Sink queue {}", queue_len);
3458 }
3459 }
3460 break;
3461 }
3462 case BTA_AV_SINK_MEDIA_CFG_EVT: {
3463 btif_av_sink_config_req_t config_req;
3464
3465 log::verbose("address={}", p_data->avk_config.bd_addr);
3466
3467 // Update the codec info of the A2DP Sink decoder
3468 btif_a2dp_sink_update_decoder((uint8_t*)(p_data->avk_config.codec_info));
3469
3470 config_req.sample_rate =
3471 A2DP_GetTrackSampleRate(p_data->avk_config.codec_info);
3472 if (config_req.sample_rate == -1) {
3473 log::error("Cannot get the track frequency");
3474 break;
3475 }
3476 config_req.channel_count =
3477 A2DP_GetTrackChannelCount(p_data->avk_config.codec_info);
3478 if (config_req.channel_count == -1) {
3479 log::error("Cannot get the channel count");
3480 break;
3481 }
3482 config_req.peer_address = p_data->avk_config.bd_addr;
3483 BtifAvEvent btif_av_event(BTIF_AV_SINK_CONFIG_REQ_EVT, &config_req,
3484 sizeof(config_req));
3485 do_in_main_thread(
3486 FROM_HERE, base::BindOnce(&btif_av_handle_event,
3487 AVDT_TSEP_SRC, // peer_sep
3488 config_req.peer_address, kBtaHandleUnknown,
3489 btif_av_event));
3490 break;
3491 }
3492 default:
3493 break;
3494 }
3495 }
3496
3497 // Initializes the AV interface for source mode
init_src(btav_source_callbacks_t * callbacks,int max_connected_audio_devices,const std::vector<btav_a2dp_codec_config_t> & codec_priorities,const std::vector<btav_a2dp_codec_config_t> & offloading_preference,std::vector<btav_a2dp_codec_info_t> * supported_codecs)3498 static bt_status_t init_src(
3499 btav_source_callbacks_t* callbacks, int max_connected_audio_devices,
3500 const std::vector<btav_a2dp_codec_config_t>& codec_priorities,
3501 const std::vector<btav_a2dp_codec_config_t>& offloading_preference,
3502 std::vector<btav_a2dp_codec_info_t>* supported_codecs) {
3503 log::info("");
3504 return btif_av_source.Init(callbacks, max_connected_audio_devices,
3505 codec_priorities, offloading_preference,
3506 supported_codecs);
3507 }
3508
3509 // Initializes the AV interface for sink mode
init_sink(btav_sink_callbacks_t * callbacks,int max_connected_audio_devices)3510 static bt_status_t init_sink(btav_sink_callbacks_t* callbacks,
3511 int max_connected_audio_devices) {
3512 log::info("");
3513 return btif_av_sink.Init(callbacks, max_connected_audio_devices);
3514 }
3515
3516 // Updates the final focus state reported by components calling this module
update_audio_focus_state(int state)3517 static void update_audio_focus_state(int state) {
3518 log::info("state={}", state);
3519 btif_a2dp_sink_set_focus_state_req((btif_a2dp_sink_focus_state_t)state);
3520 }
3521
3522 // Updates the track gain (used for ducking).
update_audio_track_gain(float gain)3523 static void update_audio_track_gain(float gain) {
3524 log::info("gain={:f}", gain);
3525 btif_a2dp_sink_set_audio_track_gain(gain);
3526 }
3527
3528 // Establishes the AV signalling channel with the remote headset
connect_int(RawAddress * peer_address,uint16_t uuid)3529 static bt_status_t connect_int(RawAddress* peer_address, uint16_t uuid) {
3530 log::info("peer={} uuid=0x{:x}", *peer_address, uuid);
3531
3532 if (btif_av_both_enable()) {
3533 const RawAddress tmp = *peer_address;
3534 if (uuid == UUID_SERVCLASS_AUDIO_SOURCE) {
3535 btif_av_source_dispatch_sm_event(tmp, BTIF_AV_CONNECT_REQ_EVT);
3536 } else if (uuid == UUID_SERVCLASS_AUDIO_SINK) {
3537 btif_av_sink_dispatch_sm_event(tmp, BTIF_AV_CONNECT_REQ_EVT);
3538 }
3539 return BT_STATUS_SUCCESS;
3540 }
3541
3542 auto connection_task = [](RawAddress* peer_address, uint16_t uuid) {
3543 BtifAvPeer* peer = nullptr;
3544 if (uuid == UUID_SERVCLASS_AUDIO_SOURCE) {
3545 peer = btif_av_source.FindOrCreatePeer(*peer_address, kBtaHandleUnknown);
3546 } else if (uuid == UUID_SERVCLASS_AUDIO_SINK) {
3547 peer = btif_av_sink.FindOrCreatePeer(*peer_address, kBtaHandleUnknown);
3548 }
3549 if (peer == nullptr) {
3550 btif_queue_advance();
3551 return;
3552 }
3553 peer->StateMachine().ProcessEvent(BTIF_AV_CONNECT_REQ_EVT, nullptr);
3554 };
3555 bt_status_t status = do_in_main_thread(
3556 FROM_HERE, base::BindOnce(connection_task, peer_address, uuid));
3557 if (status != BT_STATUS_SUCCESS) {
3558 log::error("can't post connection task to main_thread");
3559 }
3560 return status;
3561 }
3562
set_source_silence_peer_int(const RawAddress & peer_address,bool silence)3563 static void set_source_silence_peer_int(const RawAddress& peer_address,
3564 bool silence) {
3565 log::info("peer={} silence={}", peer_address, silence);
3566
3567 if (!btif_av_source.SetSilencePeer(peer_address, silence)) {
3568 log::error("Error setting silence state to {}", peer_address);
3569 }
3570 }
3571
3572 // Set the active peer
set_active_peer_int(uint8_t peer_sep,const RawAddress & peer_address,std::promise<void> peer_ready_promise)3573 static void set_active_peer_int(uint8_t peer_sep,
3574 const RawAddress& peer_address,
3575 std::promise<void> peer_ready_promise) {
3576 log::info("peer_sep={} peer={}",
3577 peer_sep == AVDT_TSEP_SRC ? "Source" : "Sink", peer_address);
3578
3579 BtifAvPeer* peer = nullptr;
3580 if (peer_sep == AVDT_TSEP_SNK) {
3581 if (!btif_av_src_sink_coexist_enabled() || (btif_av_src_sink_coexist_enabled() &&
3582 btif_av_both_enable() && (btif_av_sink.FindPeer(peer_address) == nullptr))) {
3583 if (!btif_av_source.SetActivePeer(peer_address,
3584 std::move(peer_ready_promise))) {
3585 log::error("Error setting {} as active Sink peer", peer_address);
3586 }
3587 }
3588 return;
3589 }
3590 if (peer_sep == AVDT_TSEP_SRC) {
3591 if (!btif_av_src_sink_coexist_enabled() || (btif_av_src_sink_coexist_enabled() &&
3592 btif_av_both_enable() && (btif_av_source.FindPeer(peer_address) == nullptr))) {
3593 if (!btif_av_sink.SetActivePeer(peer_address,
3594 std::move(peer_ready_promise))) {
3595 log::error("Error setting {} as active Source peer", peer_address);
3596 }
3597 }
3598 return;
3599 }
3600 // If reached here, we could not set the active peer
3601 log::error("Cannot set active {} peer to {}: peer not {}",
3602 (peer_sep == AVDT_TSEP_SRC) ? "Source" : "Sink", peer_address,
3603 (peer == nullptr) ? "found" : "connected");
3604 peer_ready_promise.set_value();
3605 }
3606
src_connect_sink(const RawAddress & peer_address)3607 static bt_status_t src_connect_sink(const RawAddress& peer_address) {
3608 log::info("peer={}", peer_address);
3609
3610 if (!btif_av_source.Enabled()) {
3611 log::warn("BTIF AV Source is not enabled");
3612 return BT_STATUS_NOT_READY;
3613 }
3614
3615 RawAddress peer_address_copy(peer_address);
3616 return btif_queue_connect(UUID_SERVCLASS_AUDIO_SOURCE, &peer_address_copy,
3617 connect_int);
3618 }
3619
sink_connect_src(const RawAddress & peer_address)3620 static bt_status_t sink_connect_src(const RawAddress& peer_address) {
3621 log::info("peer={}", peer_address);
3622
3623 if (!btif_av_sink.Enabled()) {
3624 log::warn("BTIF AV Sink is not enabled");
3625 return BT_STATUS_NOT_READY;
3626 }
3627
3628 RawAddress peer_address_copy(peer_address);
3629 return btif_queue_connect(UUID_SERVCLASS_AUDIO_SINK, &peer_address_copy,
3630 connect_int);
3631 }
3632
src_disconnect_sink(const RawAddress & peer_address)3633 static bt_status_t src_disconnect_sink(const RawAddress& peer_address) {
3634 log::info("peer={}", peer_address);
3635
3636 if (!btif_av_source.Enabled()) {
3637 log::warn("BTIF AV Source is not enabled");
3638 return BT_STATUS_NOT_READY;
3639 }
3640
3641 BtifAvEvent btif_av_event(BTIF_AV_DISCONNECT_REQ_EVT, &peer_address,
3642 sizeof(peer_address));
3643 return do_in_main_thread(
3644 FROM_HERE,
3645 base::BindOnce(&btif_av_handle_event,
3646 AVDT_TSEP_SNK, // peer_sep
3647 peer_address, kBtaHandleUnknown, btif_av_event));
3648 }
3649
sink_disconnect_src(const RawAddress & peer_address)3650 static bt_status_t sink_disconnect_src(const RawAddress& peer_address) {
3651 log::info("peer={}", peer_address);
3652
3653 if (!btif_av_sink.Enabled()) {
3654 log::warn("BTIF AV Sink is not enabled");
3655 return BT_STATUS_NOT_READY;
3656 }
3657
3658 BtifAvEvent btif_av_event(BTIF_AV_DISCONNECT_REQ_EVT, &peer_address,
3659 sizeof(peer_address));
3660 return do_in_main_thread(
3661 FROM_HERE,
3662 base::BindOnce(&btif_av_handle_event,
3663 AVDT_TSEP_SRC, // peer_sep
3664 peer_address, kBtaHandleUnknown, btif_av_event));
3665 }
3666
sink_set_active_device(const RawAddress & peer_address)3667 static bt_status_t sink_set_active_device(const RawAddress& peer_address) {
3668 log::info("peer={}", peer_address);
3669
3670 if (!btif_av_sink.Enabled()) {
3671 log::warn("BTIF AV Source is not enabled");
3672 return BT_STATUS_NOT_READY;
3673 }
3674
3675 std::promise<void> peer_ready_promise;
3676 std::future<void> peer_ready_future = peer_ready_promise.get_future();
3677 bt_status_t status = do_in_main_thread(
3678 FROM_HERE, base::BindOnce(&set_active_peer_int,
3679 AVDT_TSEP_SRC, // peer_sep
3680 peer_address, std::move(peer_ready_promise)));
3681 if (status == BT_STATUS_SUCCESS) {
3682 peer_ready_future.wait();
3683 } else {
3684 log::warn("BTIF AV Sink fails to change peer");
3685 }
3686 return status;
3687 }
3688
src_set_silence_sink(const RawAddress & peer_address,bool silence)3689 static bt_status_t src_set_silence_sink(const RawAddress& peer_address,
3690 bool silence) {
3691 log::info("peer={} silence={}", peer_address, silence);
3692
3693 if (!btif_av_source.Enabled()) {
3694 log::warn("BTIF AV Source is not enabled");
3695 return BT_STATUS_NOT_READY;
3696 }
3697
3698 return do_in_main_thread(
3699 FROM_HERE,
3700 base::BindOnce(&set_source_silence_peer_int, peer_address, silence));
3701 }
3702
src_set_active_sink(const RawAddress & peer_address)3703 static bt_status_t src_set_active_sink(const RawAddress& peer_address) {
3704 log::info("peer={}", peer_address);
3705
3706 if (!btif_av_source.Enabled()) {
3707 log::warn("BTIF AV Source is not enabled");
3708 return BT_STATUS_NOT_READY;
3709 }
3710
3711 std::promise<void> peer_ready_promise;
3712 std::future<void> peer_ready_future = peer_ready_promise.get_future();
3713 bt_status_t status = do_in_main_thread(
3714 FROM_HERE, base::BindOnce(&set_active_peer_int,
3715 AVDT_TSEP_SNK, // peer_sep
3716 peer_address, std::move(peer_ready_promise)));
3717 if (status == BT_STATUS_SUCCESS) {
3718 peer_ready_future.wait();
3719 } else {
3720 log::warn("BTIF AV Source fails to change peer");
3721 }
3722 return status;
3723 }
3724
codec_config_src(const RawAddress & peer_address,std::vector<btav_a2dp_codec_config_t> codec_preferences)3725 static bt_status_t codec_config_src(
3726 const RawAddress& peer_address,
3727 std::vector<btav_a2dp_codec_config_t> codec_preferences) {
3728 log::info("peer={} codec_preferences=[{}]", peer_address,
3729 codec_preferences.size());
3730
3731 if (!btif_av_source.Enabled()) {
3732 log::warn("BTIF AV Source is not enabled");
3733 return BT_STATUS_NOT_READY;
3734 }
3735
3736 if (peer_address.IsEmpty()) {
3737 log::warn("BTIF AV Source needs peer to config");
3738 return BT_STATUS_PARM_INVALID;
3739 }
3740
3741 std::promise<void> peer_ready_promise;
3742 std::future<void> peer_ready_future = peer_ready_promise.get_future();
3743 bt_status_t status = do_in_main_thread(
3744 FROM_HERE,
3745 base::BindOnce(&BtifAvSource::UpdateCodecConfig,
3746 base::Unretained(&btif_av_source), peer_address,
3747 codec_preferences, std::move(peer_ready_promise)));
3748 if (status == BT_STATUS_SUCCESS) {
3749 peer_ready_future.wait();
3750 } else {
3751 log::warn("BTIF AV Source fails to config codec");
3752 }
3753 return status;
3754 }
3755
cleanup_src(void)3756 static void cleanup_src(void) {
3757 log::info("");
3758 do_in_main_thread(FROM_HERE,
3759 base::BindOnce(&BtifAvSource::Cleanup,
3760 base::Unretained(&btif_av_source)));
3761 }
3762
cleanup_sink(void)3763 static void cleanup_sink(void) {
3764 log::info("");
3765 do_in_main_thread(FROM_HERE, base::BindOnce(&BtifAvSink::Cleanup,
3766 base::Unretained(&btif_av_sink)));
3767 }
3768
3769 static const btav_source_interface_t bt_av_src_interface = {
3770 sizeof(btav_source_interface_t),
3771 init_src,
3772 src_connect_sink,
3773 src_disconnect_sink,
3774 src_set_silence_sink,
3775 src_set_active_sink,
3776 codec_config_src,
3777 cleanup_src,
3778 };
3779
3780 static const btav_sink_interface_t bt_av_sink_interface = {
3781 sizeof(btav_sink_interface_t),
3782 init_sink,
3783 sink_connect_src,
3784 sink_disconnect_src,
3785 cleanup_sink,
3786 update_audio_focus_state,
3787 update_audio_track_gain,
3788 sink_set_active_device};
3789
btif_av_source_active_peer(void)3790 RawAddress btif_av_source_active_peer(void) {
3791 return btif_av_source.ActivePeer();
3792 }
btif_av_sink_active_peer(void)3793 RawAddress btif_av_sink_active_peer(void) { return btif_av_sink.ActivePeer(); }
3794
btif_av_is_sink_enabled(void)3795 bool btif_av_is_sink_enabled(void) { return btif_av_sink.Enabled(); }
3796
btif_av_is_source_enabled(void)3797 bool btif_av_is_source_enabled(void) { return btif_av_source.Enabled(); }
3798
btif_av_stream_start(const A2dpType local_a2dp_type)3799 void btif_av_stream_start(const A2dpType local_a2dp_type) {
3800 log::info("");
3801
3802 btif_av_source_dispatch_sm_event(btif_av_source_active_peer(),
3803 BTIF_AV_START_STREAM_REQ_EVT);
3804 }
3805
btif_av_stream_start_with_latency(bool use_latency_mode)3806 void btif_av_stream_start_with_latency(bool use_latency_mode) {
3807 log::info("peer={} use_latency_mode={}",
3808 btif_av_source_active_peer(), use_latency_mode);
3809
3810 btif_av_start_stream_req_t start_stream_req;
3811 start_stream_req.use_latency_mode = use_latency_mode;
3812 BtifAvEvent btif_av_event(BTIF_AV_START_STREAM_REQ_EVT, &start_stream_req,
3813 sizeof(start_stream_req));
3814
3815 do_in_main_thread(
3816 FROM_HERE, base::BindOnce(&btif_av_handle_event,
3817 AVDT_TSEP_SNK, // peer_sep
3818 btif_av_source_active_peer(), kBtaHandleUnknown,
3819 btif_av_event));
3820 }
3821
src_do_suspend_in_main_thread(btif_av_sm_event_t event)3822 static void src_do_suspend_in_main_thread(btif_av_sm_event_t event) {
3823 if (event != BTIF_AV_SUSPEND_STREAM_REQ_EVT &&
3824 event != BTIF_AV_STOP_STREAM_REQ_EVT)
3825 return;
3826 auto src_do_stream_suspend = [](btif_av_sm_event_t event) {
3827 bool is_idle = true;
3828 for (auto it : btif_av_source.Peers()) {
3829 const BtifAvPeer* peer = it.second;
3830 if (peer->StateMachine().StateId() == BtifAvStateMachine::kStateStarted) {
3831 btif_av_source_dispatch_sm_event(peer->PeerAddress(), event);
3832 is_idle = false;
3833 }
3834 }
3835 if (is_idle) {
3836 btif_a2dp_on_stopped(nullptr, A2dpType::kSource);
3837 }
3838 };
3839 // switch to main thread to prevent a race condition of accessing peers
3840 do_in_main_thread(FROM_HERE, base::BindOnce(src_do_stream_suspend, event));
3841 }
3842
btif_av_stream_stop(const RawAddress & peer_address)3843 void btif_av_stream_stop(const RawAddress& peer_address) {
3844 log::info("peer={}", peer_address);
3845
3846 if (!peer_address.IsEmpty()) {
3847 btif_av_source_dispatch_sm_event(peer_address, BTIF_AV_STOP_STREAM_REQ_EVT);
3848 return;
3849 }
3850
3851 // The active peer might have changed and we might be in the process
3852 // of reconfiguring the stream. We need to stop the appropriate peer(s).
3853 src_do_suspend_in_main_thread(BTIF_AV_STOP_STREAM_REQ_EVT);
3854 }
3855
btif_av_stream_suspend(void)3856 void btif_av_stream_suspend(void) {
3857 log::info("");
3858
3859 // The active peer might have changed and we might be in the process
3860 // of reconfiguring the stream. We need to suspend the appropriate peer(s).
3861 src_do_suspend_in_main_thread(BTIF_AV_SUSPEND_STREAM_REQ_EVT);
3862 }
3863
btif_av_stream_start_offload(void)3864 void btif_av_stream_start_offload(void) {
3865 log::info("");
3866
3867 btif_av_source_dispatch_sm_event(btif_av_source_active_peer(),
3868 BTIF_AV_OFFLOAD_START_REQ_EVT);
3869 }
3870
btif_av_src_disconnect_sink(const RawAddress & peer_address)3871 void btif_av_src_disconnect_sink(const RawAddress& peer_address) {
3872 log::info("peer={}", peer_address);
3873
3874 src_disconnect_sink(peer_address);
3875 }
3876
btif_av_stream_ready(const A2dpType local_a2dp_type)3877 bool btif_av_stream_ready(const A2dpType local_a2dp_type) {
3878 // Make sure the main adapter is enabled
3879 if (btif_is_enabled() == 0) {
3880 log::verbose("Main adapter is not enabled");
3881 return false;
3882 }
3883
3884 BtifAvPeer* peer = btif_av_find_active_peer(local_a2dp_type);
3885 if (peer == nullptr) {
3886 log::warn("No active peer found");
3887 return false;
3888 }
3889
3890 int state = peer->StateMachine().StateId();
3891 log::info("active_peer={} state={} flags={}", peer->PeerAddress(), state,
3892 peer->FlagsToString());
3893
3894 // check if we are remotely suspended or stop is pending
3895 if (peer->CheckFlags(BtifAvPeer::kFlagRemoteSuspend |
3896 BtifAvPeer::kFlagPendingStop)) {
3897 return false;
3898 }
3899
3900 return (state == BtifAvStateMachine::kStateOpened);
3901 }
3902
btif_av_stream_started_ready(const A2dpType local_a2dp_type)3903 bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) {
3904 BtifAvPeer* peer = btif_av_find_active_peer(local_a2dp_type);
3905 if (peer == nullptr) {
3906 log::warn("No active peer found");
3907 return false;
3908 }
3909
3910 int state = peer->StateMachine().StateId();
3911 bool ready = false;
3912 if (peer->CheckFlags(BtifAvPeer::kFlagLocalSuspendPending |
3913 BtifAvPeer::kFlagRemoteSuspend |
3914 BtifAvPeer::kFlagPendingStop)) {
3915 // Disallow media task to start if we have pending actions
3916 ready = false;
3917 } else {
3918 ready = (state == BtifAvStateMachine::kStateStarted);
3919 }
3920
3921 log::info("active_peer={} state={} flags={} ready={}", peer->PeerAddress(),
3922 state, peer->FlagsToString(), ready);
3923
3924 return ready;
3925 }
3926
btif_av_source_dispatch_sm_event(const RawAddress & peer_address,btif_av_sm_event_t event)3927 static void btif_av_source_dispatch_sm_event(const RawAddress& peer_address,
3928 btif_av_sm_event_t event) {
3929 BtifAvEvent btif_av_event(event, nullptr, 0);
3930 log::verbose("peer={} event={}", peer_address,
3931 btif_av_event.ToString());
3932
3933 do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_event,
3934 AVDT_TSEP_SNK, // peer_sep
3935 peer_address, kBtaHandleUnknown,
3936 btif_av_event));
3937 }
3938
btif_av_sink_dispatch_sm_event(const RawAddress & peer_address,btif_av_sm_event_t event)3939 static void btif_av_sink_dispatch_sm_event(const RawAddress& peer_address,
3940 btif_av_sm_event_t event) {
3941 BtifAvEvent btif_av_event(event, nullptr, 0);
3942 log::verbose("peer={} event={}", peer_address,
3943 btif_av_event.ToString());
3944
3945 do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_event,
3946 AVDT_TSEP_SRC, // peer_sep
3947 peer_address, kBtaHandleUnknown,
3948 btif_av_event));
3949 }
3950
btif_av_source_execute_service(bool enable)3951 bt_status_t btif_av_source_execute_service(bool enable) {
3952 log::info("enable={}", enable);
3953
3954 if (enable) {
3955 // Added BTA_AV_FEAT_NO_SCO_SSPD - this ensures that the BTA does not
3956 // auto-suspend av streaming on AG events(SCO or Call). The suspend shall
3957 // be initiated by the app/audioflinger layers.
3958 // Support for browsing for SDP record should work only if we enable
3959 // BROWSE while registering.
3960 tBTA_AV_FEAT features = BTA_AV_FEAT_RCTG | BTA_AV_FEAT_METADATA |
3961 BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_NO_SCO_SSPD;
3962
3963 if (delay_reporting_enabled()) {
3964 features |= BTA_AV_FEAT_DELAY_RPT;
3965 }
3966
3967 if (avrcp_absolute_volume_is_enabled()) {
3968 features |= BTA_AV_FEAT_RCCT | BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_BROWSE;
3969 }
3970
3971 if (btif_av_src_sink_coexist_enabled()) {
3972 features |= BTA_AV_FEAT_SRC;
3973 BTA_AvEnable(features, bta_av_event_callback);
3974 } else {
3975 BTA_AvEnable(features, bta_av_source_callback);
3976 }
3977 btif_av_source.RegisterAllBtaHandles();
3978 return BT_STATUS_SUCCESS;
3979 }
3980
3981 // Disable the service
3982 btif_av_source.DeregisterAllBtaHandles();
3983 BTA_AvDisable();
3984 return BT_STATUS_SUCCESS;
3985 }
3986
btif_av_sink_execute_service(bool enable)3987 bt_status_t btif_av_sink_execute_service(bool enable) {
3988 log::info("enable={}", enable);
3989
3990 if (enable) {
3991 // Added BTA_AV_FEAT_NO_SCO_SSPD - this ensures that the BTA does not
3992 // auto-suspend AV streaming on AG events (SCO or Call). The suspend shall
3993 // be initiated by the app/audioflinger layers.
3994 tBTA_AV_FEAT features = BTA_AV_FEAT_NO_SCO_SSPD | BTA_AV_FEAT_RCCT |
3995 BTA_AV_FEAT_METADATA | BTA_AV_FEAT_VENDOR |
3996 BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCTG |
3997 BTA_AV_FEAT_BROWSE | BTA_AV_FEAT_COVER_ARTWORK;
3998
3999 if (delay_reporting_enabled()) {
4000 features |= BTA_AV_FEAT_DELAY_RPT;
4001 }
4002
4003 if (btif_av_src_sink_coexist_enabled())
4004 BTA_AvEnable(features, bta_av_event_callback);
4005 else
4006 BTA_AvEnable(features, bta_av_sink_callback);
4007 btif_av_sink.RegisterAllBtaHandles();
4008 return BT_STATUS_SUCCESS;
4009 }
4010
4011 // Disable the service
4012 btif_av_sink.DeregisterAllBtaHandles();
4013 BTA_AvDisable();
4014 return BT_STATUS_SUCCESS;
4015 }
4016
4017 // Get the AV callback interface for A2DP source profile
btif_av_get_src_interface(void)4018 const btav_source_interface_t* btif_av_get_src_interface(void) {
4019 return &bt_av_src_interface;
4020 }
4021
4022 // Get the AV callback interface for A2DP sink profile
btif_av_get_sink_interface(void)4023 const btav_sink_interface_t* btif_av_get_sink_interface(void) {
4024 return &bt_av_sink_interface;
4025 }
4026
btif_av_is_connected(const A2dpType local_a2dp_type)4027 bool btif_av_is_connected(const A2dpType local_a2dp_type) {
4028 BtifAvPeer* peer = btif_av_find_active_peer(local_a2dp_type);
4029 if (peer == nullptr) {
4030 log::warn("No active peer found");
4031 return false;
4032 }
4033
4034 bool connected = peer->IsConnected();
4035 log::verbose("active_peer={} connected={}", peer->PeerAddress(), connected);
4036 return peer->IsConnected();
4037 }
4038
btif_av_get_peer_sep(const A2dpType local_a2dp_type)4039 uint8_t btif_av_get_peer_sep(const A2dpType local_a2dp_type) {
4040 BtifAvPeer* peer = btif_av_find_active_peer(local_a2dp_type);
4041 if (peer == nullptr) {
4042 log::warn("No active peer found");
4043 return AVDT_TSEP_INVALID;
4044 }
4045
4046 uint8_t peer_sep = peer->PeerSep();
4047 log::verbose("active_peer={} sep={}", peer->PeerAddress(),
4048 peer_sep == AVDT_TSEP_SRC ? "Source" : "Sink");
4049 return peer_sep;
4050 }
4051
btif_av_clear_remote_suspend_flag(const A2dpType local_a2dp_type)4052 void btif_av_clear_remote_suspend_flag(const A2dpType local_a2dp_type) {
4053 auto clear_remote_suspend_flag = [](const A2dpType local_a2dp_type) {
4054 BtifAvPeer* peer = btif_av_find_active_peer(local_a2dp_type);
4055 if (peer == nullptr) {
4056 log::warn("No active peer found");
4057 return;
4058 }
4059 log::verbose("active_peer={} flags={}", peer->PeerAddress(),
4060 peer->FlagsToString());
4061 peer->ClearFlags(BtifAvPeer::kFlagRemoteSuspend);
4062 };
4063 // switch to main thread to prevent a race condition of accessing peers
4064 do_in_main_thread(FROM_HERE,
4065 base::BindOnce(clear_remote_suspend_flag, local_a2dp_type));
4066 }
4067
btif_av_is_peer_edr(const RawAddress & peer_address,const A2dpType local_a2dp_type)4068 bool btif_av_is_peer_edr(const RawAddress& peer_address,
4069 const A2dpType local_a2dp_type) {
4070 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
4071 if (peer == nullptr) {
4072 log::warn("peer={} not found", peer_address);
4073 return false;
4074 }
4075 if (!peer->IsConnected()) {
4076 log::warn("peer={} not connected", peer_address);
4077 return false;
4078 }
4079
4080 bool is_edr = peer->IsEdr();
4081 log::verbose("peer={} is_edr={}", peer_address, is_edr);
4082 return is_edr;
4083 }
4084
btif_av_peer_supports_3mbps(const RawAddress & peer_address,const A2dpType local_a2dp_type)4085 bool btif_av_peer_supports_3mbps(const RawAddress& peer_address,
4086 const A2dpType local_a2dp_type) {
4087 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
4088 if (peer == nullptr) {
4089 log::warn("peer={} not found", peer_address);
4090 return false;
4091 }
4092
4093 bool is_3mbps = peer->Is3Mbps();
4094 bool is_connected = peer->IsConnected();
4095 log::verbose("peer={} connected={}, edr_3mbps={}", peer_address,
4096 is_connected, is_3mbps);
4097 return is_connected && is_3mbps;
4098 }
4099
btif_av_peer_prefers_mandatory_codec(const RawAddress & peer_address,const A2dpType local_a2dp_type)4100 bool btif_av_peer_prefers_mandatory_codec(const RawAddress& peer_address,
4101 const A2dpType local_a2dp_type) {
4102 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
4103 if (peer == nullptr) {
4104 log::warn("peer={} not found", peer_address);
4105 return false;
4106 }
4107 return peer->IsMandatoryCodecPreferred();
4108 }
4109
btif_av_acl_disconnected(const RawAddress & peer_address,const A2dpType local_a2dp_type)4110 void btif_av_acl_disconnected(const RawAddress& peer_address,
4111 const A2dpType local_a2dp_type) {
4112 log::info("peer={}", peer_address);
4113
4114 // Inform the application that ACL is disconnected and move to idle state
4115 if (com::android::bluetooth::flags::a2dp_concurrent_source_sink() ||
4116 btif_av_both_enable()) {
4117 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
4118 if (peer != nullptr) {
4119 if (peer->IsSource()) {
4120 btif_av_sink_dispatch_sm_event(peer_address, BTIF_AV_ACL_DISCONNECTED);
4121 } else {
4122 btif_av_source_dispatch_sm_event(peer_address,
4123 BTIF_AV_ACL_DISCONNECTED);
4124 }
4125 }
4126 return;
4127 }
4128
4129 if (btif_av_source.Enabled()) {
4130 btif_av_source_dispatch_sm_event(peer_address, BTIF_AV_ACL_DISCONNECTED);
4131 } else if (btif_av_sink.Enabled()) {
4132 btif_av_sink_dispatch_sm_event(peer_address, BTIF_AV_ACL_DISCONNECTED);
4133 }
4134 }
4135
btif_debug_av_peer_dump(int fd,const BtifAvPeer & peer)4136 static void btif_debug_av_peer_dump(int fd, const BtifAvPeer& peer) {
4137 std::string state_str;
4138 int state = peer.StateMachine().StateId();
4139 switch (state) {
4140 case BtifAvStateMachine::kStateIdle:
4141 state_str = "Idle";
4142 break;
4143 case BtifAvStateMachine::kStateOpening:
4144 state_str = "Opening";
4145 break;
4146 case BtifAvStateMachine::kStateOpened:
4147 state_str = "Opened";
4148 break;
4149 case BtifAvStateMachine::kStateStarted:
4150 state_str = "Started";
4151 break;
4152 case BtifAvStateMachine::kStateClosing:
4153 state_str = "Closing";
4154 break;
4155 default:
4156 state_str = "Unknown(" + std::to_string(state) + ")";
4157 break;
4158 }
4159
4160 dprintf(fd, " Peer: %s\n", ADDRESS_TO_LOGGABLE_CSTR(peer.PeerAddress()));
4161 dprintf(fd, " Connected: %s\n", peer.IsConnected() ? "true" : "false");
4162 dprintf(fd, " Streaming: %s\n", peer.IsStreaming() ? "true" : "false");
4163 dprintf(fd, " SEP: %d(%s)\n", peer.PeerSep(),
4164 (peer.IsSource()) ? "Source" : "Sink");
4165 dprintf(fd, " State Machine: %s\n", state_str.c_str());
4166 dprintf(fd, " Flags: %s\n", peer.FlagsToString().c_str());
4167 dprintf(fd, " OpenOnRcTimer: %s\n",
4168 alarm_is_scheduled(peer.AvOpenOnRcTimer()) ? "Scheduled"
4169 : "Not scheduled");
4170 dprintf(fd, " BTA Handle: 0x%x\n", peer.BtaHandle());
4171 dprintf(fd, " Peer ID: %d\n", peer.PeerId());
4172 dprintf(fd, " EDR: %s\n", peer.IsEdr() ? "true" : "false");
4173 dprintf(fd, " Support 3Mbps: %s\n", peer.Is3Mbps() ? "true" : "false");
4174 dprintf(fd, " Self Initiated Connection: %s\n",
4175 peer.SelfInitiatedConnection() ? "true" : "false");
4176 dprintf(fd, " Delay Reporting: %u (in 1/10 milliseconds) \n",
4177 peer.GetDelayReport());
4178 dprintf(fd, " Codec Preferred: %s\n",
4179 peer.IsMandatoryCodecPreferred() ? "Mandatory" : "Optional");
4180 }
4181
btif_debug_av_source_dump(int fd)4182 static void btif_debug_av_source_dump(int fd) {
4183 bool enabled = btif_av_source.Enabled();
4184
4185 dprintf(fd, "\nA2DP Source State: %s\n", (enabled) ? "Enabled" : "Disabled");
4186 if (!enabled) return;
4187 dprintf(fd, " Active peer: %s\n",
4188 ADDRESS_TO_LOGGABLE_CSTR(btif_av_source.ActivePeer()));
4189 for (auto it : btif_av_source.Peers()) {
4190 const BtifAvPeer* peer = it.second;
4191 if (peer != nullptr) {
4192 btif_debug_av_peer_dump(fd, *peer);
4193 }
4194 }
4195 }
4196
btif_debug_av_sink_dump(int fd)4197 static void btif_debug_av_sink_dump(int fd) {
4198 bool enabled = btif_av_sink.Enabled();
4199
4200 dprintf(fd, "\nA2DP Sink State: %s\n", (enabled) ? "Enabled" : "Disabled");
4201 if (!enabled) return;
4202 dprintf(fd, " Active peer: %s\n",
4203 ADDRESS_TO_LOGGABLE_CSTR(btif_av_sink.ActivePeer()));
4204 dprintf(fd, " Peers:\n");
4205 for (auto it : btif_av_sink.Peers()) {
4206 const BtifAvPeer* peer = it.second;
4207 btif_debug_av_peer_dump(fd, *peer);
4208 }
4209 }
4210
btif_debug_av_dump(int fd)4211 void btif_debug_av_dump(int fd) {
4212 btif_debug_av_source_dump(fd);
4213 btif_debug_av_sink_dump(fd);
4214 }
4215
btif_av_set_audio_delay(const RawAddress & peer_address,uint16_t delay,const A2dpType local_a2dp_type)4216 void btif_av_set_audio_delay(const RawAddress& peer_address, uint16_t delay,
4217 const A2dpType local_a2dp_type) {
4218 log::info("peer={} delay={}", peer_address, delay);
4219
4220 btif_a2dp_control_set_audio_delay(delay);
4221
4222 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
4223 if (peer != nullptr && peer->IsSink()) {
4224 peer->SetDelayReport(delay);
4225 if (peer->IsActivePeer()) {
4226 bluetooth::audio::a2dp::set_remote_delay(peer->GetDelayReport());
4227 }
4228 }
4229 }
4230
btif_av_get_audio_delay(const A2dpType local_a2dp_type)4231 uint16_t btif_av_get_audio_delay(const A2dpType local_a2dp_type) {
4232 BtifAvPeer* peer = btif_av_find_active_peer(local_a2dp_type);
4233 if (peer != nullptr && peer->IsSink()) {
4234 return peer->GetDelayReport();
4235 }
4236 return 0;
4237 }
4238
btif_av_reset_audio_delay(void)4239 void btif_av_reset_audio_delay(void) { btif_a2dp_control_reset_audio_delay(); }
4240
btif_av_is_a2dp_offload_enabled()4241 bool btif_av_is_a2dp_offload_enabled() {
4242 return btif_av_source.A2dpOffloadEnabled();
4243 }
4244
btif_av_is_a2dp_offload_running()4245 bool btif_av_is_a2dp_offload_running() {
4246 if (!btif_av_is_a2dp_offload_enabled()) {
4247 return false;
4248 }
4249 if (!bluetooth::audio::a2dp::is_hal_enabled()) {
4250 return false;
4251 }
4252 return bluetooth::audio::a2dp::is_hal_offloading();
4253 }
4254
btif_av_is_peer_silenced(const RawAddress & peer_address)4255 bool btif_av_is_peer_silenced(const RawAddress& peer_address) {
4256 return btif_av_source.IsPeerSilenced(peer_address);
4257 }
4258
btif_av_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size)4259 void btif_av_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size) {
4260 btif_a2dp_source_set_dynamic_audio_buffer_size(dynamic_audio_buffer_size);
4261 }
4262
btif_av_set_low_latency(bool is_low_latency)4263 void btif_av_set_low_latency(bool is_low_latency) {
4264 log::info("active_peer={} is_low_latency={}",
4265 btif_av_source_active_peer(), is_low_latency);
4266
4267 btif_av_set_latency_req_t set_latency_req;
4268 set_latency_req.is_low_latency = is_low_latency;
4269 BtifAvEvent btif_av_event(BTIF_AV_SET_LATENCY_REQ_EVT, &set_latency_req,
4270 sizeof(set_latency_req));
4271
4272 do_in_main_thread(
4273 FROM_HERE, base::BindOnce(&btif_av_handle_event,
4274 AVDT_TSEP_SNK, // peer_sep
4275 btif_av_source_active_peer(), kBtaHandleUnknown,
4276 btif_av_event));
4277 }
4278
btif_av_sink_delete_active_peer(void)4279 static void btif_av_sink_delete_active_peer(void) {
4280 btif_av_sink.DeleteActivePeer();
4281 }
4282
btif_av_source_delete_active_peer(void)4283 static void btif_av_source_delete_active_peer(void) {
4284 btif_av_source.DeleteActivePeer();
4285 }
4286
btif_av_is_connected_addr(const RawAddress & peer_address,const A2dpType local_a2dp_type)4287 bool btif_av_is_connected_addr(const RawAddress& peer_address,
4288 const A2dpType local_a2dp_type) {
4289 BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type);
4290 if (peer == nullptr) {
4291 log::warn("No active peer found");
4292 return false;
4293 }
4294
4295 bool connected = peer->IsConnected();
4296 log::verbose("active_peer={} connected={}", peer->PeerAddress(), connected);
4297 return connected;
4298 }
4299
btif_av_peer_is_connected_sink(const RawAddress & peer_address)4300 bool btif_av_peer_is_connected_sink(const RawAddress& peer_address) {
4301 BtifAvPeer* peer = btif_av_source_find_peer(peer_address);
4302 if (peer == nullptr) {
4303 log::warn("No active peer found");
4304 return false;
4305 }
4306
4307 bool connected = peer->IsConnected();
4308 log::verbose("active_peer={} connected={}", peer->PeerAddress(), connected);
4309 return connected;
4310 }
4311
btif_av_peer_is_connected_source(const RawAddress & peer_address)4312 bool btif_av_peer_is_connected_source(const RawAddress& peer_address) {
4313 BtifAvPeer* peer = btif_av_sink_find_peer(peer_address);
4314 if (peer == nullptr) {
4315 log::warn("No active peer found");
4316 return false;
4317 }
4318
4319 bool connected = peer->IsConnected();
4320 log::verbose("active_peer={} connected={}", peer->PeerAddress(), connected);
4321 return connected;
4322 }
4323
btif_av_peer_is_sink(const RawAddress & peer_address)4324 bool btif_av_peer_is_sink(const RawAddress& peer_address) {
4325 BtifAvPeer* peer = btif_av_source_find_peer(peer_address);
4326 if (peer == nullptr) {
4327 log::warn("No active peer found");
4328 return false;
4329 }
4330
4331 return true;
4332 }
4333
btif_av_peer_is_source(const RawAddress & peer_address)4334 bool btif_av_peer_is_source(const RawAddress& peer_address) {
4335 BtifAvPeer* peer = btif_av_sink_find_peer(peer_address);
4336 if (peer == nullptr) {
4337 log::warn("No active peer found");
4338 return false;
4339 }
4340
4341 return true;
4342 }
4343
btif_av_connect_sink_delayed(uint8_t handle,const RawAddress & peer_address)4344 void btif_av_connect_sink_delayed(uint8_t handle,
4345 const RawAddress& peer_address) {
4346 log::info("peer={} handle=0x{:x}", peer_address, handle);
4347
4348 if (btif_av_source.Enabled()) {
4349 btif_av_source_dispatch_sm_event(peer_address, BTIF_AV_AVRCP_OPEN_EVT);
4350 }
4351 }
4352