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