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