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