• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2016 The Android Open Source Project
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 #define LOG_TAG "bluetooth-a2dp"
21 
22 #include "btif/include/btif_a2dp_sink.h"
23 
24 #include <base/functional/bind.h>
25 #include <bluetooth/log.h>
26 #include <com_android_bluetooth_flags.h>
27 
28 #include <atomic>
29 #include <cstddef>
30 #include <cstdint>
31 #include <cstring>
32 #include <future>
33 #include <mutex>
34 #include <string>
35 #include <utility>
36 
37 #include "a2dp_api.h"
38 #include "a2dp_codec_api.h"
39 #include "avdt_api.h"
40 #include "bta_av_api.h"
41 #include "btif/include/btif_av.h"
42 #include "btif/include/btif_av_co.h"
43 #include "btif/include/btif_avrcp_audio_track.h"
44 #include "btif/include/btif_util.h"  // CASE_RETURN_STR
45 #include "common/message_loop_thread.h"
46 #include "osi/include/alarm.h"
47 #include "osi/include/allocator.h"
48 #include "osi/include/fixed_queue.h"
49 #include "stack/include/bt_hdr.h"
50 #include "types/raw_address.h"
51 
52 using bluetooth::common::MessageLoopThread;
53 using LockGuard = std::lock_guard<std::mutex>;
54 using namespace bluetooth;
55 
56 /**
57  * The receiving queue buffer size.
58  */
59 #define MAX_INPUT_A2DP_FRAME_QUEUE_SZ (MAX_PCM_FRAME_NUM_PER_TICK * 2)
60 
61 #define BTIF_SINK_MEDIA_TIME_TICK_MS 20
62 
63 /* In case of A2DP Sink, we will delay start by 5 AVDTP Packets */
64 #define MAX_A2DP_DELAYED_START_FRAME_COUNT 5
65 
66 enum {
67   BTIF_A2DP_SINK_STATE_OFF,
68   BTIF_A2DP_SINK_STATE_STARTING_UP,
69   BTIF_A2DP_SINK_STATE_RUNNING,
70   BTIF_A2DP_SINK_STATE_SHUTTING_DOWN
71 };
72 
73 /* BTIF Media Sink command event definition */
74 enum {
75   BTIF_MEDIA_SINK_DECODER_UPDATE = 1,
76   BTIF_MEDIA_SINK_CLEAR_TRACK,
77   BTIF_MEDIA_SINK_SET_FOCUS_STATE,
78   BTIF_MEDIA_SINK_AUDIO_RX_FLUSH,
79   BTIF_MEDIA_SINK_START,
80   BTIF_MEDIA_SINK_SUSPEND
81 };
82 
83 typedef struct {
84   BT_HDR_RIGID hdr;
85   uint8_t codec_info[AVDT_CODEC_SIZE];
86   RawAddress peer_address;
87 } tBTIF_MEDIA_SINK_DECODER_UPDATE;
88 
89 typedef struct {
90   BT_HDR_RIGID hdr;
91   btif_a2dp_sink_focus_state_t focus_state;
92 } tBTIF_MEDIA_SINK_FOCUS_UPDATE;
93 
94 /* BTIF A2DP Sink control block */
95 class BtifA2dpSinkControlBlock {
96 public:
BtifA2dpSinkControlBlock(const std::string & thread_name)97   explicit BtifA2dpSinkControlBlock(const std::string& thread_name)
98       : worker_thread(thread_name),
99         rx_audio_queue(nullptr),
100         rx_flush(false),
101         decode_alarm(nullptr),
102         sample_rate(0),
103         channel_count(0),
104         rx_focus_state(BTIF_A2DP_SINK_FOCUS_NOT_GRANTED),
105         audio_track(nullptr),
106         decoder_interface(nullptr) {}
107 
Reset()108   void Reset() {
109     if (audio_track != nullptr) {
110       BtifAvrcpAudioTrackStop(audio_track);
111       BtifAvrcpAudioTrackDelete(audio_track);
112     }
113     audio_track = nullptr;
114     fixed_queue_free(rx_audio_queue, nullptr);
115     rx_audio_queue = nullptr;
116     alarm_free(decode_alarm);
117     decode_alarm = nullptr;
118     rx_flush = false;
119     rx_focus_state = BTIF_A2DP_SINK_FOCUS_NOT_GRANTED;
120     sample_rate = 0;
121     channel_count = 0;
122     decoder_interface = nullptr;
123   }
124 
125   MessageLoopThread worker_thread;
126   fixed_queue_t* rx_audio_queue;
127   bool rx_flush; /* discards any incoming data when true */
128   alarm_t* decode_alarm;
129   int sample_rate;                             // 32000, 44100, 48000, 96000
130   int bits_per_sample;                         // 16, 24, 32
131   int channel_count;                           // 1, 2
132   btif_a2dp_sink_focus_state_t rx_focus_state; /* audio focus state */
133   void* audio_track;
134   const tA2DP_DECODER_INTERFACE* decoder_interface;
135 };
136 
137 // Mutex for below data structures.
138 static std::mutex g_mutex;
139 
140 static BtifA2dpSinkControlBlock btif_a2dp_sink_cb("bt_a2dp_sink_worker_thread");
141 
142 static std::atomic<int> btif_a2dp_sink_state{BTIF_A2DP_SINK_STATE_OFF};
143 
144 static void btif_a2dp_sink_init_delayed();
145 static void btif_a2dp_sink_startup_delayed();
146 static void btif_a2dp_sink_start_session_delayed(const RawAddress& peer_address,
147                                                  std::promise<void> peer_ready_promise);
148 static void btif_a2dp_sink_end_session_delayed();
149 static void btif_a2dp_sink_shutdown_delayed();
150 static void btif_a2dp_sink_cleanup_delayed();
151 static void btif_a2dp_sink_command_ready(BT_HDR_RIGID* p_msg);
152 static void btif_a2dp_sink_audio_handle_stop_decoding();
153 static void btif_decode_alarm_cb(void* context);
154 static void btif_a2dp_sink_audio_handle_start_decoding();
155 static void btif_a2dp_sink_avk_handle_timer();
156 static void btif_a2dp_sink_audio_rx_flush_req();
157 /* Handle incoming media packets A2DP SINK streaming */
158 static void btif_a2dp_sink_handle_inc_media(BT_HDR* p_msg);
159 static void btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf);
160 static void btif_a2dp_sink_decoder_update_event_old(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf);
161 static void btif_a2dp_sink_clear_track_event();
162 static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state);
163 static void btif_a2dp_sink_audio_rx_flush_event();
164 static void btif_a2dp_sink_clear_track_event_req();
165 static void btif_a2dp_sink_on_start_event();
166 static void btif_a2dp_sink_on_suspend_event();
167 
dump_media_event(uint16_t event)168 static const char* dump_media_event(uint16_t event) {
169   switch (event) {
170     CASE_RETURN_STR(BTIF_MEDIA_SINK_DECODER_UPDATE)
171     CASE_RETURN_STR(BTIF_MEDIA_SINK_CLEAR_TRACK)
172     CASE_RETURN_STR(BTIF_MEDIA_SINK_SET_FOCUS_STATE)
173     CASE_RETURN_STR(BTIF_MEDIA_SINK_AUDIO_RX_FLUSH)
174     CASE_RETURN_STR(BTIF_MEDIA_SINK_START)
175     CASE_RETURN_STR(BTIF_MEDIA_SINK_SUSPEND)
176     default:
177       break;
178   }
179   return "UNKNOWN A2DP SINK EVENT";
180 }
181 
btif_a2dp_sink_init()182 bool btif_a2dp_sink_init() {
183   log::info("");
184   LockGuard lock(g_mutex);
185 
186   if (btif_a2dp_sink_state != BTIF_A2DP_SINK_STATE_OFF) {
187     log::error("A2DP Sink media task already running");
188     return false;
189   }
190 
191   btif_a2dp_sink_cb.Reset();
192   btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_STARTING_UP;
193 
194   /* Start A2DP Sink media task */
195   btif_a2dp_sink_cb.worker_thread.StartUp();
196   if (!btif_a2dp_sink_cb.worker_thread.IsRunning()) {
197     log::error("unable to start up media thread");
198     btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_OFF;
199     return false;
200   }
201 
202   btif_a2dp_sink_cb.rx_audio_queue = fixed_queue_new(SIZE_MAX);
203 
204   /* Schedule the rest of the operations */
205   if (!btif_a2dp_sink_cb.worker_thread.EnableRealTimeScheduling()) {
206 #if defined(__ANDROID__)
207     log::fatal("Failed to increase A2DP decoder thread priority");
208 #endif
209   }
210   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_init_delayed));
211   return true;
212 }
213 
btif_a2dp_sink_init_delayed()214 static void btif_a2dp_sink_init_delayed() {
215   log::info("");
216   btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_RUNNING;
217 }
218 
btif_a2dp_sink_startup()219 bool btif_a2dp_sink_startup() {
220   log::info("");
221   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_startup_delayed));
222   return true;
223 }
224 
btif_a2dp_sink_startup_delayed()225 static void btif_a2dp_sink_startup_delayed() {
226   log::info("");
227   LockGuard lock(g_mutex);
228   // Nothing to do
229 }
230 
btif_a2dp_sink_on_decode_complete(uint8_t * data,uint32_t len)231 static void btif_a2dp_sink_on_decode_complete([[maybe_unused]] uint8_t* data,
232                                               [[maybe_unused]] uint32_t len) {
233 #ifdef __ANDROID__
234   BtifAvrcpAudioTrackWriteData(btif_a2dp_sink_cb.audio_track, reinterpret_cast<void*>(data), len);
235 #endif
236 }
237 
btif_a2dp_sink_initialize_a2dp_control_block(const RawAddress & peer_address)238 static bool btif_a2dp_sink_initialize_a2dp_control_block(const RawAddress& peer_address) {
239   log::info("Initializing the control block for peer {}", peer_address);
240   if (peer_address.IsEmpty()) {
241     log::error("Peer address is empty. Control block cannot be initialized");
242     return false;
243   }
244   uint8_t* codec_config = bta_av_co_get_codec_config(peer_address);
245   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", codec_config[1], codec_config[2],
246                codec_config[3], codec_config[4], codec_config[5], codec_config[6]);
247 
248   btif_a2dp_sink_cb.decoder_interface = A2DP_GetDecoderInterface(codec_config);
249 
250   if (btif_a2dp_sink_cb.decoder_interface == nullptr) {
251     log::error("cannot stream audio: no source decoder interface");
252     return false;
253   }
254 
255   if (!btif_a2dp_sink_cb.decoder_interface->decoder_init(btif_a2dp_sink_on_decode_complete)) {
256     log::error("failed to initialize decoder");
257     return false;
258   }
259 
260   if (btif_a2dp_sink_cb.decoder_interface->decoder_configure != nullptr) {
261     btif_a2dp_sink_cb.decoder_interface->decoder_configure(codec_config);
262   }
263 
264   log::info("codec = {}", A2DP_CodecInfoString(codec_config));
265   int sample_rate = A2DP_GetTrackSampleRate(codec_config);
266   if (sample_rate == -1) {
267     log::error("cannot get the track frequency");
268     return false;
269   }
270   int bits_per_sample = A2DP_GetTrackBitsPerSample(codec_config);
271   if (bits_per_sample == -1) {
272     log::error("%cannot get the bits per sample");
273     return false;
274   }
275   int channel_count = A2DP_GetTrackChannelCount(codec_config);
276   if (channel_count == -1) {
277     log::error("cannot get the channel count");
278     return false;
279   }
280   int channel_type = A2DP_GetSinkTrackChannelType(codec_config);
281   if (channel_type == -1) {
282     log::error("cannot get the Sink channel type");
283     return false;
284   }
285   btif_a2dp_sink_cb.sample_rate = sample_rate;
286   btif_a2dp_sink_cb.bits_per_sample = bits_per_sample;
287   btif_a2dp_sink_cb.channel_count = channel_count;
288 
289   btif_a2dp_sink_cb.audio_track =
290 #ifdef __ANDROID__
291           BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count);
292 #else
293           NULL;
294 #endif
295   if (btif_a2dp_sink_cb.audio_track == nullptr) {
296     log::error("track creation failed");
297     return false;
298   }
299   log::info("A2DP sink control block initialized");
300   return true;
301 }
302 
btif_a2dp_sink_start_session(const RawAddress & peer_address,std::promise<void> peer_ready_promise)303 bool btif_a2dp_sink_start_session(const RawAddress& peer_address,
304                                   std::promise<void> peer_ready_promise) {
305   log::info("peer_address={}", peer_address);
306   if (btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(
307               btif_a2dp_sink_start_session_delayed, peer_address, std::move(peer_ready_promise)))) {
308     return true;
309   } else {
310     // cannot set promise but triggers crash
311     log::fatal("peer_address={} fails to context switch", peer_address);
312     return false;
313   }
314 }
315 
btif_a2dp_sink_start_session_delayed(const RawAddress & peer_address,std::promise<void> peer_ready_promise)316 static void btif_a2dp_sink_start_session_delayed(const RawAddress& peer_address,
317                                                  std::promise<void> peer_ready_promise) {
318   log::info("");
319   LockGuard lock(g_mutex);
320   if (com::android::bluetooth::flags::bta_av_use_peer_codec()) {
321     btif_a2dp_sink_initialize_a2dp_control_block(peer_address);
322   }
323   peer_ready_promise.set_value();
324   // Nothing to do
325 }
326 
btif_a2dp_sink_restart_session(const RawAddress & old_peer_address,const RawAddress & new_peer_address,std::promise<void> peer_ready_promise)327 bool btif_a2dp_sink_restart_session(const RawAddress& old_peer_address,
328                                     const RawAddress& new_peer_address,
329                                     std::promise<void> peer_ready_promise) {
330   log::info("old_peer_address={} new_peer_address={}", old_peer_address, new_peer_address);
331 
332   log::assert_that(!new_peer_address.IsEmpty(), "assert failed: !new_peer_address.IsEmpty()");
333 
334   if (!old_peer_address.IsEmpty()) {
335     btif_a2dp_sink_end_session(old_peer_address);
336   }
337   if (!bta_av_co_set_active_sink_peer(new_peer_address)) {
338     log::error("Cannot stream audio: cannot set active peer to {}", new_peer_address);
339     peer_ready_promise.set_value();
340     return false;
341   }
342 
343   if (old_peer_address.IsEmpty()) {
344     btif_a2dp_sink_startup();
345   }
346   btif_a2dp_sink_start_session(new_peer_address, std::move(peer_ready_promise));
347 
348   return true;
349 }
350 
btif_a2dp_sink_end_session(const RawAddress & peer_address)351 bool btif_a2dp_sink_end_session(const RawAddress& peer_address) {
352   log::info("peer_address={}", peer_address);
353   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_end_session_delayed));
354   return true;
355 }
356 
btif_a2dp_sink_end_session_delayed()357 static void btif_a2dp_sink_end_session_delayed() {
358   log::info("");
359   LockGuard lock(g_mutex);
360   // Nothing to do
361 }
362 
btif_a2dp_sink_shutdown()363 void btif_a2dp_sink_shutdown() {
364   log::info("");
365   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_shutdown_delayed));
366 }
367 
btif_a2dp_sink_shutdown_delayed()368 static void btif_a2dp_sink_shutdown_delayed() {
369   log::info("");
370   LockGuard lock(g_mutex);
371   // Nothing to do
372 }
373 
btif_a2dp_sink_cleanup()374 void btif_a2dp_sink_cleanup() {
375   log::info("");
376 
377   alarm_t* decode_alarm;
378 
379   // Make sure the sink is shutdown
380   btif_a2dp_sink_shutdown();
381 
382   {
383     LockGuard lock(g_mutex);
384     if ((btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) ||
385         (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_SHUTTING_DOWN)) {
386       return;
387     }
388     // Make sure no channels are restarted while shutting down
389     btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_SHUTTING_DOWN;
390 
391     decode_alarm = btif_a2dp_sink_cb.decode_alarm;
392     btif_a2dp_sink_cb.decode_alarm = nullptr;
393   }
394 
395   // Stop the timer
396   alarm_free(decode_alarm);
397 
398   // Exit the thread
399   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_cleanup_delayed));
400   btif_a2dp_sink_cb.worker_thread.ShutDown();
401 }
402 
btif_a2dp_sink_cleanup_delayed()403 static void btif_a2dp_sink_cleanup_delayed() {
404   log::info("");
405   LockGuard lock(g_mutex);
406 
407   fixed_queue_free(btif_a2dp_sink_cb.rx_audio_queue, nullptr);
408   btif_a2dp_sink_cb.rx_audio_queue = nullptr;
409   btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_OFF;
410 }
411 
btif_a2dp_sink_command_ready(BT_HDR_RIGID * p_msg)412 static void btif_a2dp_sink_command_ready(BT_HDR_RIGID* p_msg) {
413   log::verbose("event {} {}", p_msg->event, dump_media_event(p_msg->event));
414 
415   switch (p_msg->event) {
416     case BTIF_MEDIA_SINK_DECODER_UPDATE:
417       btif_a2dp_sink_decoder_update_event((tBTIF_MEDIA_SINK_DECODER_UPDATE*)p_msg);
418       break;
419     case BTIF_MEDIA_SINK_CLEAR_TRACK:
420       btif_a2dp_sink_clear_track_event();
421       break;
422     case BTIF_MEDIA_SINK_SET_FOCUS_STATE: {
423       btif_a2dp_sink_focus_state_t state = ((tBTIF_MEDIA_SINK_FOCUS_UPDATE*)p_msg)->focus_state;
424       btif_a2dp_sink_set_focus_state_event(state);
425       break;
426     }
427     case BTIF_MEDIA_SINK_AUDIO_RX_FLUSH:
428       btif_a2dp_sink_audio_rx_flush_event();
429       break;
430     case BTIF_MEDIA_SINK_START:
431       btif_a2dp_sink_on_start_event();
432       break;
433     case BTIF_MEDIA_SINK_SUSPEND:
434       btif_a2dp_sink_on_suspend_event();
435       break;
436     default:
437       log::error("unknown event {}", p_msg->event);
438       break;
439   }
440 
441   log::verbose("{} DONE", dump_media_event(p_msg->event));
442   osi_free(p_msg);
443 }
444 
btif_a2dp_sink_update_decoder(const RawAddress & peer_address,const uint8_t * p_codec_info)445 void btif_a2dp_sink_update_decoder(const RawAddress& peer_address, const uint8_t* p_codec_info) {
446   log::info("peer_address {}", peer_address);
447   tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf = reinterpret_cast<tBTIF_MEDIA_SINK_DECODER_UPDATE*>(
448           osi_malloc(sizeof(tBTIF_MEDIA_SINK_DECODER_UPDATE)));
449 
450   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], p_codec_info[2],
451                p_codec_info[3], p_codec_info[4], p_codec_info[5], p_codec_info[6]);
452   memcpy(p_buf->codec_info, p_codec_info, AVDT_CODEC_SIZE);
453   p_buf->peer_address = peer_address;
454   p_buf->hdr.event = BTIF_MEDIA_SINK_DECODER_UPDATE;
455 
456   btif_a2dp_sink_cb.worker_thread.DoInThread(
457           base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
458 }
459 
btif_a2dp_sink_on_idle()460 void btif_a2dp_sink_on_idle() {
461   log::info("");
462   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
463   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
464   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
465 
466   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
467     return;
468   }
469   btif_a2dp_sink_audio_handle_stop_decoding();
470   btif_a2dp_sink_clear_track_event_req();
471 }
472 
btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND *)473 void btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND* /* p_av_suspend */) {
474   log::info("");
475   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
476   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
477   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
478 
479   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
480     return;
481   }
482   btif_a2dp_sink_audio_handle_stop_decoding();
483 }
484 
btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND *)485 void btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND* /* p_av_suspend */) {
486   log::info("");
487   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
488   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
489   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
490 
491   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
492     return;
493   }
494   btif_a2dp_sink_audio_handle_stop_decoding();
495 }
496 
btif_a2dp_sink_on_start()497 bool btif_a2dp_sink_on_start() {
498   log::info("");
499 
500   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
501   p_buf->event = BTIF_MEDIA_SINK_START;
502   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
503 
504   return true;
505 }
506 
btif_a2dp_sink_audio_handle_stop_decoding()507 static void btif_a2dp_sink_audio_handle_stop_decoding() {
508   log::info("");
509   alarm_t* old_alarm;
510   {
511     LockGuard lock(g_mutex);
512     btif_a2dp_sink_cb.rx_flush = true;
513     btif_a2dp_sink_audio_rx_flush_req();
514     old_alarm = btif_a2dp_sink_cb.decode_alarm;
515     btif_a2dp_sink_cb.decode_alarm = nullptr;
516   }
517 
518   // Drop the lock here, btif_decode_alarm_cb may in the process of being called
519   // while we alarm free leading to deadlock.
520   //
521   // alarm_free waits for btif_decode_alarm_cb which is waiting for g_mutex.
522   alarm_free(old_alarm);
523 
524   {
525     LockGuard lock(g_mutex);
526 #ifdef __ANDROID__
527     BtifAvrcpAudioTrackPause(btif_a2dp_sink_cb.audio_track);
528 #endif
529   }
530 }
531 
btif_decode_alarm_cb(void *)532 static void btif_decode_alarm_cb(void* /* context */) {
533   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_avk_handle_timer));
534 }
535 
btif_a2dp_sink_clear_track_event()536 static void btif_a2dp_sink_clear_track_event() {
537   log::info("");
538   LockGuard lock(g_mutex);
539 
540 #ifdef __ANDROID__
541   BtifAvrcpAudioTrackStop(btif_a2dp_sink_cb.audio_track);
542   BtifAvrcpAudioTrackDelete(btif_a2dp_sink_cb.audio_track);
543 #endif
544   btif_a2dp_sink_cb.audio_track = nullptr;
545 }
546 
547 // Must be called while locked.
btif_a2dp_sink_audio_handle_start_decoding()548 static void btif_a2dp_sink_audio_handle_start_decoding() {
549   log::info("");
550   if (btif_a2dp_sink_cb.decode_alarm != nullptr) {
551     return;  // Already started decoding
552   }
553 
554 #ifdef __ANDROID__
555   BtifAvrcpAudioTrackStart(btif_a2dp_sink_cb.audio_track);
556 #endif
557 
558   btif_a2dp_sink_cb.decode_alarm = alarm_new_periodic("btif.a2dp_sink_decode");
559   if (btif_a2dp_sink_cb.decode_alarm == nullptr) {
560     log::error("unable to allocate decode alarm");
561     return;
562   }
563   alarm_set(btif_a2dp_sink_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK_MS, btif_decode_alarm_cb,
564             nullptr);
565 }
566 
567 // Must be called while locked.
btif_a2dp_sink_handle_inc_media(BT_HDR * p_msg)568 static void btif_a2dp_sink_handle_inc_media(BT_HDR* p_msg) {
569   if ((btif_av_get_peer_sep(A2dpType::kSink) == AVDT_TSEP_SNK) || (btif_a2dp_sink_cb.rx_flush)) {
570     log::verbose("state changed happened in this tick");
571     return;
572   }
573 
574   log::assert_that(btif_a2dp_sink_cb.decoder_interface != nullptr,
575                    "assert failed: btif_a2dp_sink_cb.decoder_interface != nullptr");
576   if (!btif_a2dp_sink_cb.decoder_interface->decode_packet(p_msg)) {
577     log::error("decoding failed");
578   }
579 }
580 
btif_a2dp_sink_avk_handle_timer()581 static void btif_a2dp_sink_avk_handle_timer() {
582   LockGuard lock(g_mutex);
583 
584   BT_HDR* p_msg;
585   if (fixed_queue_is_empty(btif_a2dp_sink_cb.rx_audio_queue)) {
586     log::verbose("empty queue");
587     return;
588   }
589 
590   /* Don't do anything in case of focus not granted */
591   if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_NOT_GRANTED) {
592     log::verbose("skipping frames since focus is not present");
593     return;
594   }
595   /* Play only in BTIF_A2DP_SINK_FOCUS_GRANTED case */
596   if (btif_a2dp_sink_cb.rx_flush) {
597     fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
598     return;
599   }
600 
601   log::verbose("process frames begin");
602   while (true) {
603     p_msg = (BT_HDR*)fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue);
604     if (p_msg == NULL) {
605       break;
606     }
607     log::verbose("number of packets in queue {}",
608                  fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue));
609 
610     /* Queue packet has less frames */
611     btif_a2dp_sink_handle_inc_media(p_msg);
612     osi_free(p_msg);
613   }
614   log::verbose("process frames end");
615 }
616 
617 /* when true media task discards any rx frames */
btif_a2dp_sink_set_rx_flush(bool enable)618 void btif_a2dp_sink_set_rx_flush(bool enable) {
619   log::info("enable={}", enable);
620   LockGuard lock(g_mutex);
621 
622   btif_a2dp_sink_cb.rx_flush = enable;
623 }
624 
btif_a2dp_sink_audio_rx_flush_event()625 static void btif_a2dp_sink_audio_rx_flush_event() {
626   log::info("");
627   LockGuard lock(g_mutex);
628   // Flush all received encoded audio buffers
629   fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
630 }
631 
btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE * p_buf)632 static void btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) {
633   log::info("");
634   if (!com::android::bluetooth::flags::bta_av_use_peer_codec()) {
635     btif_a2dp_sink_decoder_update_event_old(p_buf);
636     return;
637   }
638   LockGuard lock(g_mutex);
639   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_buf->codec_info[1],
640                p_buf->codec_info[2], p_buf->codec_info[3], p_buf->codec_info[4],
641                p_buf->codec_info[5], p_buf->codec_info[6]);
642 
643   btif_a2dp_sink_cb.rx_flush = false;
644   log::verbose("reset to Sink role");
645 
646   bta_av_co_save_codec(p_buf->peer_address, p_buf->codec_info);
647   log::info("codec = {}", A2DP_CodecInfoString(p_buf->codec_info));
648 }
649 
btif_a2dp_sink_decoder_update_event_old(tBTIF_MEDIA_SINK_DECODER_UPDATE * p_buf)650 static void btif_a2dp_sink_decoder_update_event_old(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) {
651   log::info("");
652   LockGuard lock(g_mutex);
653   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_buf->codec_info[1],
654                p_buf->codec_info[2], p_buf->codec_info[3], p_buf->codec_info[4],
655                p_buf->codec_info[5], p_buf->codec_info[6]);
656 
657   int sample_rate = A2DP_GetTrackSampleRate(p_buf->codec_info);
658   if (sample_rate == -1) {
659     log::error("cannot get the track frequency");
660     return;
661   }
662   int bits_per_sample = A2DP_GetTrackBitsPerSample(p_buf->codec_info);
663   if (bits_per_sample == -1) {
664     log::error("cannot get the bits per sample");
665     return;
666   }
667   int channel_count = A2DP_GetTrackChannelCount(p_buf->codec_info);
668   if (channel_count == -1) {
669     log::error("cannot get the channel count");
670     return;
671   }
672   int channel_type = A2DP_GetSinkTrackChannelType(p_buf->codec_info);
673   if (channel_type == -1) {
674     log::error("cannot get the Sink channel type");
675     return;
676   }
677   btif_a2dp_sink_cb.sample_rate = sample_rate;
678   btif_a2dp_sink_cb.bits_per_sample = bits_per_sample;
679   btif_a2dp_sink_cb.channel_count = channel_count;
680 
681   btif_a2dp_sink_cb.rx_flush = false;
682   log::verbose("reset to Sink role");
683 
684   bta_av_co_save_codec(p_buf->peer_address, p_buf->codec_info);
685   log::info("codec = {}", A2DP_CodecInfoString(p_buf->codec_info));
686 
687   btif_a2dp_sink_cb.decoder_interface = A2DP_GetDecoderInterface(p_buf->codec_info);
688 
689   if (btif_a2dp_sink_cb.decoder_interface == nullptr) {
690     log::error("cannot stream audio: no source decoder interface");
691     return;
692   }
693 
694   if (!btif_a2dp_sink_cb.decoder_interface->decoder_init(btif_a2dp_sink_on_decode_complete)) {
695     log::error("failed to initialize decoder");
696     return;
697   }
698 
699   if (btif_a2dp_sink_cb.decoder_interface->decoder_configure != nullptr) {
700     btif_a2dp_sink_cb.decoder_interface->decoder_configure(p_buf->codec_info);
701   }
702 
703   log::verbose("create audio track");
704   btif_a2dp_sink_cb.audio_track =
705 #ifdef __ANDROID__
706           BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count);
707 #else
708           NULL;
709 #endif
710   if (btif_a2dp_sink_cb.audio_track == nullptr) {
711     log::error("track creation failed");
712     return;
713   }
714 }
715 
btif_a2dp_sink_enqueue_buf(BT_HDR * p_pkt)716 uint8_t btif_a2dp_sink_enqueue_buf(BT_HDR* p_pkt) {
717   LockGuard lock(g_mutex);
718   if (btif_a2dp_sink_cb.rx_flush) { /* Flush enabled, do not enqueue */
719     return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
720   }
721 
722   log::verbose("+");
723 
724   /* Allocate and queue this buffer */
725   BT_HDR* p_msg = reinterpret_cast<BT_HDR*>(osi_malloc(sizeof(*p_msg) + p_pkt->len));
726   memcpy(p_msg, p_pkt, sizeof(*p_msg));
727   p_msg->offset = 0;
728   memcpy(p_msg->data, p_pkt->data + p_pkt->offset, p_pkt->len);
729   fixed_queue_enqueue(btif_a2dp_sink_cb.rx_audio_queue, p_msg);
730 
731   /* If the queue is full, pop the front off to make room for the new data */
732   if (fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) == MAX_INPUT_A2DP_FRAME_QUEUE_SZ) {
733     log::verbose("Audio data buffer has reached max size. Dropping front packet");
734     osi_free(fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue));
735   }
736 
737   /* Check to see if we need to start decoding */
738   if (btif_a2dp_sink_cb.decode_alarm == nullptr &&
739       fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) >= MAX_A2DP_DELAYED_START_FRAME_COUNT) {
740     log::verbose("Can initiate decoding, focus_state={}", btif_a2dp_sink_cb.rx_focus_state);
741     if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_GRANTED) {
742       log::info("Request to begin decoding");
743       btif_a2dp_sink_audio_handle_start_decoding();
744     }
745   }
746 
747   return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
748 }
749 
btif_a2dp_sink_audio_rx_flush_req()750 void btif_a2dp_sink_audio_rx_flush_req() {
751   log::info("");
752   if (fixed_queue_is_empty(btif_a2dp_sink_cb.rx_audio_queue)) {
753     /* Queue is already empty */
754     return;
755   }
756 
757   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
758   p_buf->event = BTIF_MEDIA_SINK_AUDIO_RX_FLUSH;
759   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
760 }
761 
btif_a2dp_sink_debug_dump(int)762 void btif_a2dp_sink_debug_dump(int /* fd */) {
763   // Nothing to do
764 }
765 
btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state)766 void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state) {
767   log::info("");
768   tBTIF_MEDIA_SINK_FOCUS_UPDATE* p_buf = reinterpret_cast<tBTIF_MEDIA_SINK_FOCUS_UPDATE*>(
769           osi_malloc(sizeof(tBTIF_MEDIA_SINK_FOCUS_UPDATE)));
770   p_buf->focus_state = state;
771   p_buf->hdr.event = BTIF_MEDIA_SINK_SET_FOCUS_STATE;
772   btif_a2dp_sink_cb.worker_thread.DoInThread(
773           base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
774 }
775 
btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state)776 static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state) {
777   log::info("state={}", state);
778   LockGuard lock(g_mutex);
779 
780   log::verbose("setting focus state to {}", state);
781   btif_a2dp_sink_cb.rx_focus_state = state;
782   if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_NOT_GRANTED) {
783     fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
784     btif_a2dp_sink_cb.rx_flush = true;
785   } else if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_GRANTED) {
786     btif_a2dp_sink_cb.rx_flush = false;
787   }
788 }
789 
btif_a2dp_sink_set_audio_track_gain(float gain)790 void btif_a2dp_sink_set_audio_track_gain(float gain) {
791   log::debug("set gain to {:f}", gain);
792   LockGuard lock(g_mutex);
793 
794 #ifdef __ANDROID__
795   BtifAvrcpSetAudioTrackGain(btif_a2dp_sink_cb.audio_track, gain);
796 #endif
797 }
798 
btif_a2dp_sink_get_audio_track(void)799 void* btif_a2dp_sink_get_audio_track(void) { return btif_a2dp_sink_cb.audio_track; }
800 
btif_a2dp_sink_clear_track_event_req()801 static void btif_a2dp_sink_clear_track_event_req() {
802   log::info("");
803   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
804 
805   p_buf->event = BTIF_MEDIA_SINK_CLEAR_TRACK;
806   btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
807 }
808 
btif_a2dp_sink_on_start_event()809 static void btif_a2dp_sink_on_start_event() {
810   log::info("");
811 
812   if ((btif_a2dp_sink_cb.decoder_interface != nullptr) &&
813       (btif_a2dp_sink_cb.decoder_interface->decoder_start != nullptr)) {
814     btif_a2dp_sink_cb.decoder_interface->decoder_start();
815   }
816 
817   return;
818 }
819 
btif_a2dp_sink_on_suspend_event()820 static void btif_a2dp_sink_on_suspend_event() {
821   log::info("");
822 
823   if ((btif_a2dp_sink_cb.decoder_interface != nullptr) &&
824       (btif_a2dp_sink_cb.decoder_interface->decoder_suspend != nullptr)) {
825     btif_a2dp_sink_cb.decoder_interface->decoder_suspend();
826   }
827 
828   return;
829 }
830