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