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(FROM_HERE,
211                                              base::BindOnce(btif_a2dp_sink_init_delayed));
212   return true;
213 }
214 
btif_a2dp_sink_init_delayed()215 static void btif_a2dp_sink_init_delayed() {
216   log::info("");
217   btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_RUNNING;
218 }
219 
btif_a2dp_sink_startup()220 bool btif_a2dp_sink_startup() {
221   log::info("");
222   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
223                                              base::BindOnce(btif_a2dp_sink_startup_delayed));
224   return true;
225 }
226 
btif_a2dp_sink_startup_delayed()227 static void btif_a2dp_sink_startup_delayed() {
228   log::info("");
229   LockGuard lock(g_mutex);
230   // Nothing to do
231 }
232 
btif_a2dp_sink_on_decode_complete(uint8_t * data,uint32_t len)233 static void btif_a2dp_sink_on_decode_complete([[maybe_unused]] uint8_t* data,
234                                               [[maybe_unused]] uint32_t len) {
235 #ifdef __ANDROID__
236   BtifAvrcpAudioTrackWriteData(btif_a2dp_sink_cb.audio_track, reinterpret_cast<void*>(data), len);
237 #endif
238 }
239 
btif_a2dp_sink_initialize_a2dp_control_block(const RawAddress & peer_address)240 static bool btif_a2dp_sink_initialize_a2dp_control_block(const RawAddress& peer_address) {
241   log::info("Initializing the control block for peer {}", peer_address);
242   if (peer_address.IsEmpty()) {
243     log::error("Peer address is empty. Control block cannot be initialized");
244     return false;
245   }
246   uint8_t* codec_config = bta_av_co_get_codec_config(peer_address);
247   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", codec_config[1], codec_config[2],
248                codec_config[3], codec_config[4], codec_config[5], codec_config[6]);
249 
250   btif_a2dp_sink_cb.decoder_interface = A2DP_GetDecoderInterface(codec_config);
251 
252   if (btif_a2dp_sink_cb.decoder_interface == nullptr) {
253     log::error("cannot stream audio: no source decoder interface");
254     return false;
255   }
256 
257   if (!btif_a2dp_sink_cb.decoder_interface->decoder_init(btif_a2dp_sink_on_decode_complete)) {
258     log::error("failed to initialize decoder");
259     return false;
260   }
261 
262   if (btif_a2dp_sink_cb.decoder_interface->decoder_configure != nullptr) {
263     btif_a2dp_sink_cb.decoder_interface->decoder_configure(codec_config);
264   }
265 
266   log::info("codec = {}", A2DP_CodecInfoString(codec_config));
267   int sample_rate = A2DP_GetTrackSampleRate(codec_config);
268   if (sample_rate == -1) {
269     log::error("cannot get the track frequency");
270     return false;
271   }
272   int bits_per_sample = A2DP_GetTrackBitsPerSample(codec_config);
273   if (bits_per_sample == -1) {
274     log::error("%cannot get the bits per sample");
275     return false;
276   }
277   int channel_count = A2DP_GetTrackChannelCount(codec_config);
278   if (channel_count == -1) {
279     log::error("cannot get the channel count");
280     return false;
281   }
282   int channel_type = A2DP_GetSinkTrackChannelType(codec_config);
283   if (channel_type == -1) {
284     log::error("cannot get the Sink channel type");
285     return false;
286   }
287   btif_a2dp_sink_cb.sample_rate = sample_rate;
288   btif_a2dp_sink_cb.bits_per_sample = bits_per_sample;
289   btif_a2dp_sink_cb.channel_count = channel_count;
290 
291   btif_a2dp_sink_cb.audio_track =
292 #ifdef __ANDROID__
293           BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count);
294 #else
295           NULL;
296 #endif
297   if (btif_a2dp_sink_cb.audio_track == nullptr) {
298     log::error("track creation failed");
299     return false;
300   }
301   log::info("A2DP sink control block initialized");
302   return true;
303 }
304 
btif_a2dp_sink_start_session(const RawAddress & peer_address,std::promise<void> peer_ready_promise)305 bool btif_a2dp_sink_start_session(const RawAddress& peer_address,
306                                   std::promise<void> peer_ready_promise) {
307   log::info("peer_address={}", peer_address);
308   if (btif_a2dp_sink_cb.worker_thread.DoInThread(
309               FROM_HERE, base::BindOnce(btif_a2dp_sink_start_session_delayed, peer_address,
310                                         std::move(peer_ready_promise)))) {
311     return true;
312   } else {
313     // cannot set promise but triggers crash
314     log::fatal("peer_address={} fails to context switch", peer_address);
315     return false;
316   }
317 }
318 
btif_a2dp_sink_start_session_delayed(const RawAddress & peer_address,std::promise<void> peer_ready_promise)319 static void btif_a2dp_sink_start_session_delayed(const RawAddress& peer_address,
320                                                  std::promise<void> peer_ready_promise) {
321   log::info("");
322   LockGuard lock(g_mutex);
323   if (com::android::bluetooth::flags::bta_av_use_peer_codec()) {
324     btif_a2dp_sink_initialize_a2dp_control_block(peer_address);
325   }
326   peer_ready_promise.set_value();
327   // Nothing to do
328 }
329 
btif_a2dp_sink_restart_session(const RawAddress & old_peer_address,const RawAddress & new_peer_address,std::promise<void> peer_ready_promise)330 bool btif_a2dp_sink_restart_session(const RawAddress& old_peer_address,
331                                     const RawAddress& new_peer_address,
332                                     std::promise<void> peer_ready_promise) {
333   log::info("old_peer_address={} new_peer_address={}", old_peer_address, new_peer_address);
334 
335   log::assert_that(!new_peer_address.IsEmpty(), "assert failed: !new_peer_address.IsEmpty()");
336 
337   if (!old_peer_address.IsEmpty()) {
338     btif_a2dp_sink_end_session(old_peer_address);
339   }
340   if (!bta_av_co_set_active_sink_peer(new_peer_address)) {
341     log::error("Cannot stream audio: cannot set active peer to {}", new_peer_address);
342     peer_ready_promise.set_value();
343     return false;
344   }
345 
346   if (old_peer_address.IsEmpty()) {
347     btif_a2dp_sink_startup();
348   }
349   btif_a2dp_sink_start_session(new_peer_address, std::move(peer_ready_promise));
350 
351   return true;
352 }
353 
btif_a2dp_sink_end_session(const RawAddress & peer_address)354 bool btif_a2dp_sink_end_session(const RawAddress& peer_address) {
355   log::info("peer_address={}", peer_address);
356   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
357                                              base::BindOnce(btif_a2dp_sink_end_session_delayed));
358   return true;
359 }
360 
btif_a2dp_sink_end_session_delayed()361 static void btif_a2dp_sink_end_session_delayed() {
362   log::info("");
363   LockGuard lock(g_mutex);
364   // Nothing to do
365 }
366 
btif_a2dp_sink_shutdown()367 void btif_a2dp_sink_shutdown() {
368   log::info("");
369   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
370                                              base::BindOnce(btif_a2dp_sink_shutdown_delayed));
371 }
372 
btif_a2dp_sink_shutdown_delayed()373 static void btif_a2dp_sink_shutdown_delayed() {
374   log::info("");
375   LockGuard lock(g_mutex);
376   // Nothing to do
377 }
378 
btif_a2dp_sink_cleanup()379 void btif_a2dp_sink_cleanup() {
380   log::info("");
381 
382   alarm_t* decode_alarm;
383 
384   // Make sure the sink is shutdown
385   btif_a2dp_sink_shutdown();
386 
387   {
388     LockGuard lock(g_mutex);
389     if ((btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) ||
390         (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_SHUTTING_DOWN)) {
391       return;
392     }
393     // Make sure no channels are restarted while shutting down
394     btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_SHUTTING_DOWN;
395 
396     decode_alarm = btif_a2dp_sink_cb.decode_alarm;
397     btif_a2dp_sink_cb.decode_alarm = nullptr;
398   }
399 
400   // Stop the timer
401   alarm_free(decode_alarm);
402 
403   // Exit the thread
404   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
405                                              base::BindOnce(btif_a2dp_sink_cleanup_delayed));
406   btif_a2dp_sink_cb.worker_thread.ShutDown();
407 }
408 
btif_a2dp_sink_cleanup_delayed()409 static void btif_a2dp_sink_cleanup_delayed() {
410   log::info("");
411   LockGuard lock(g_mutex);
412 
413   fixed_queue_free(btif_a2dp_sink_cb.rx_audio_queue, nullptr);
414   btif_a2dp_sink_cb.rx_audio_queue = nullptr;
415   btif_a2dp_sink_state = BTIF_A2DP_SINK_STATE_OFF;
416 }
417 
btif_a2dp_sink_command_ready(BT_HDR_RIGID * p_msg)418 static void btif_a2dp_sink_command_ready(BT_HDR_RIGID* p_msg) {
419   log::verbose("event {} {}", p_msg->event, dump_media_event(p_msg->event));
420 
421   switch (p_msg->event) {
422     case BTIF_MEDIA_SINK_DECODER_UPDATE:
423       btif_a2dp_sink_decoder_update_event((tBTIF_MEDIA_SINK_DECODER_UPDATE*)p_msg);
424       break;
425     case BTIF_MEDIA_SINK_CLEAR_TRACK:
426       btif_a2dp_sink_clear_track_event();
427       break;
428     case BTIF_MEDIA_SINK_SET_FOCUS_STATE: {
429       btif_a2dp_sink_focus_state_t state = ((tBTIF_MEDIA_SINK_FOCUS_UPDATE*)p_msg)->focus_state;
430       btif_a2dp_sink_set_focus_state_event(state);
431       break;
432     }
433     case BTIF_MEDIA_SINK_AUDIO_RX_FLUSH:
434       btif_a2dp_sink_audio_rx_flush_event();
435       break;
436     case BTIF_MEDIA_SINK_START:
437       btif_a2dp_sink_on_start_event();
438       break;
439     case BTIF_MEDIA_SINK_SUSPEND:
440       btif_a2dp_sink_on_suspend_event();
441       break;
442     default:
443       log::error("unknown event {}", p_msg->event);
444       break;
445   }
446 
447   log::verbose("{} DONE", dump_media_event(p_msg->event));
448   osi_free(p_msg);
449 }
450 
btif_a2dp_sink_update_decoder(const RawAddress & peer_address,const uint8_t * p_codec_info)451 void btif_a2dp_sink_update_decoder(const RawAddress& peer_address, const uint8_t* p_codec_info) {
452   log::info("peer_address {}", peer_address);
453   tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf = reinterpret_cast<tBTIF_MEDIA_SINK_DECODER_UPDATE*>(
454           osi_malloc(sizeof(tBTIF_MEDIA_SINK_DECODER_UPDATE)));
455 
456   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], p_codec_info[2],
457                p_codec_info[3], p_codec_info[4], p_codec_info[5], p_codec_info[6]);
458   memcpy(p_buf->codec_info, p_codec_info, AVDT_CODEC_SIZE);
459   p_buf->peer_address = peer_address;
460   p_buf->hdr.event = BTIF_MEDIA_SINK_DECODER_UPDATE;
461 
462   btif_a2dp_sink_cb.worker_thread.DoInThread(
463           FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
464 }
465 
btif_a2dp_sink_on_idle()466 void btif_a2dp_sink_on_idle() {
467   log::info("");
468   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
469   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
470   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
471                                              base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
472 
473   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
474     return;
475   }
476   btif_a2dp_sink_audio_handle_stop_decoding();
477   btif_a2dp_sink_clear_track_event_req();
478 }
479 
btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND *)480 void btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND* /* p_av_suspend */) {
481   log::info("");
482   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
483   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
484   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
485                                              base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
486 
487   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
488     return;
489   }
490   btif_a2dp_sink_audio_handle_stop_decoding();
491 }
492 
btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND *)493 void btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND* /* p_av_suspend */) {
494   log::info("");
495   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
496   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
497   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
498                                              base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
499 
500   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
501     return;
502   }
503   btif_a2dp_sink_audio_handle_stop_decoding();
504 }
505 
btif_a2dp_sink_on_start()506 bool btif_a2dp_sink_on_start() {
507   log::info("");
508 
509   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
510   p_buf->event = BTIF_MEDIA_SINK_START;
511   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
512                                              base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
513 
514   return true;
515 }
516 
btif_a2dp_sink_audio_handle_stop_decoding()517 static void btif_a2dp_sink_audio_handle_stop_decoding() {
518   log::info("");
519   alarm_t* old_alarm;
520   {
521     LockGuard lock(g_mutex);
522     btif_a2dp_sink_cb.rx_flush = true;
523     btif_a2dp_sink_audio_rx_flush_req();
524     old_alarm = btif_a2dp_sink_cb.decode_alarm;
525     btif_a2dp_sink_cb.decode_alarm = nullptr;
526   }
527 
528   // Drop the lock here, btif_decode_alarm_cb may in the process of being called
529   // while we alarm free leading to deadlock.
530   //
531   // alarm_free waits for btif_decode_alarm_cb which is waiting for g_mutex.
532   alarm_free(old_alarm);
533 
534   {
535     LockGuard lock(g_mutex);
536 #ifdef __ANDROID__
537     BtifAvrcpAudioTrackPause(btif_a2dp_sink_cb.audio_track);
538 #endif
539   }
540 }
541 
btif_decode_alarm_cb(void *)542 static void btif_decode_alarm_cb(void* /* context */) {
543   LockGuard lock(g_mutex);
544   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
545                                              base::BindOnce(btif_a2dp_sink_avk_handle_timer));
546 }
547 
btif_a2dp_sink_clear_track_event()548 static void btif_a2dp_sink_clear_track_event() {
549   log::info("");
550   LockGuard lock(g_mutex);
551 
552 #ifdef __ANDROID__
553   BtifAvrcpAudioTrackStop(btif_a2dp_sink_cb.audio_track);
554   BtifAvrcpAudioTrackDelete(btif_a2dp_sink_cb.audio_track);
555 #endif
556   btif_a2dp_sink_cb.audio_track = nullptr;
557 }
558 
559 // Must be called while locked.
btif_a2dp_sink_audio_handle_start_decoding()560 static void btif_a2dp_sink_audio_handle_start_decoding() {
561   log::info("");
562   if (btif_a2dp_sink_cb.decode_alarm != nullptr) {
563     return;  // Already started decoding
564   }
565 
566 #ifdef __ANDROID__
567   BtifAvrcpAudioTrackStart(btif_a2dp_sink_cb.audio_track);
568 #endif
569 
570   btif_a2dp_sink_cb.decode_alarm = alarm_new_periodic("btif.a2dp_sink_decode");
571   if (btif_a2dp_sink_cb.decode_alarm == nullptr) {
572     log::error("unable to allocate decode alarm");
573     return;
574   }
575   alarm_set(btif_a2dp_sink_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK_MS, btif_decode_alarm_cb,
576             nullptr);
577 }
578 
579 // Must be called while locked.
btif_a2dp_sink_handle_inc_media(BT_HDR * p_msg)580 static void btif_a2dp_sink_handle_inc_media(BT_HDR* p_msg) {
581   if ((btif_av_get_peer_sep(A2dpType::kSink) == AVDT_TSEP_SNK) || (btif_a2dp_sink_cb.rx_flush)) {
582     log::verbose("state changed happened in this tick");
583     return;
584   }
585 
586   log::assert_that(btif_a2dp_sink_cb.decoder_interface != nullptr,
587                    "assert failed: btif_a2dp_sink_cb.decoder_interface != nullptr");
588   if (!btif_a2dp_sink_cb.decoder_interface->decode_packet(p_msg)) {
589     log::error("decoding failed");
590   }
591 }
592 
btif_a2dp_sink_avk_handle_timer()593 static void btif_a2dp_sink_avk_handle_timer() {
594   LockGuard lock(g_mutex);
595 
596   BT_HDR* p_msg;
597   if (fixed_queue_is_empty(btif_a2dp_sink_cb.rx_audio_queue)) {
598     log::verbose("empty queue");
599     return;
600   }
601 
602   /* Don't do anything in case of focus not granted */
603   if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_NOT_GRANTED) {
604     log::verbose("skipping frames since focus is not present");
605     return;
606   }
607   /* Play only in BTIF_A2DP_SINK_FOCUS_GRANTED case */
608   if (btif_a2dp_sink_cb.rx_flush) {
609     fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
610     return;
611   }
612 
613   log::verbose("process frames begin");
614   while (true) {
615     p_msg = (BT_HDR*)fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue);
616     if (p_msg == NULL) {
617       break;
618     }
619     log::verbose("number of packets in queue {}",
620                  fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue));
621 
622     /* Queue packet has less frames */
623     btif_a2dp_sink_handle_inc_media(p_msg);
624     osi_free(p_msg);
625   }
626   log::verbose("process frames end");
627 }
628 
629 /* when true media task discards any rx frames */
btif_a2dp_sink_set_rx_flush(bool enable)630 void btif_a2dp_sink_set_rx_flush(bool enable) {
631   log::info("enable={}", enable);
632   LockGuard lock(g_mutex);
633 
634   btif_a2dp_sink_cb.rx_flush = enable;
635 }
636 
btif_a2dp_sink_audio_rx_flush_event()637 static void btif_a2dp_sink_audio_rx_flush_event() {
638   log::info("");
639   LockGuard lock(g_mutex);
640   // Flush all received encoded audio buffers
641   fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
642 }
643 
btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE * p_buf)644 static void btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) {
645   log::info("");
646   if (!com::android::bluetooth::flags::bta_av_use_peer_codec()) {
647     btif_a2dp_sink_decoder_update_event_old(p_buf);
648     return;
649   }
650   LockGuard lock(g_mutex);
651   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_buf->codec_info[1],
652                p_buf->codec_info[2], p_buf->codec_info[3], p_buf->codec_info[4],
653                p_buf->codec_info[5], p_buf->codec_info[6]);
654 
655   btif_a2dp_sink_cb.rx_flush = false;
656   log::verbose("reset to Sink role");
657 
658   bta_av_co_save_codec(p_buf->peer_address, p_buf->codec_info);
659   log::info("codec = {}", A2DP_CodecInfoString(p_buf->codec_info));
660 }
661 
btif_a2dp_sink_decoder_update_event_old(tBTIF_MEDIA_SINK_DECODER_UPDATE * p_buf)662 static void btif_a2dp_sink_decoder_update_event_old(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) {
663   log::info("");
664   LockGuard lock(g_mutex);
665   log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_buf->codec_info[1],
666                p_buf->codec_info[2], p_buf->codec_info[3], p_buf->codec_info[4],
667                p_buf->codec_info[5], p_buf->codec_info[6]);
668 
669   int sample_rate = A2DP_GetTrackSampleRate(p_buf->codec_info);
670   if (sample_rate == -1) {
671     log::error("cannot get the track frequency");
672     return;
673   }
674   int bits_per_sample = A2DP_GetTrackBitsPerSample(p_buf->codec_info);
675   if (bits_per_sample == -1) {
676     log::error("cannot get the bits per sample");
677     return;
678   }
679   int channel_count = A2DP_GetTrackChannelCount(p_buf->codec_info);
680   if (channel_count == -1) {
681     log::error("cannot get the channel count");
682     return;
683   }
684   int channel_type = A2DP_GetSinkTrackChannelType(p_buf->codec_info);
685   if (channel_type == -1) {
686     log::error("cannot get the Sink channel type");
687     return;
688   }
689   btif_a2dp_sink_cb.sample_rate = sample_rate;
690   btif_a2dp_sink_cb.bits_per_sample = bits_per_sample;
691   btif_a2dp_sink_cb.channel_count = channel_count;
692 
693   btif_a2dp_sink_cb.rx_flush = false;
694   log::verbose("reset to Sink role");
695 
696   bta_av_co_save_codec(p_buf->peer_address, p_buf->codec_info);
697   log::info("codec = {}", A2DP_CodecInfoString(p_buf->codec_info));
698 
699   btif_a2dp_sink_cb.decoder_interface = A2DP_GetDecoderInterface(p_buf->codec_info);
700 
701   if (btif_a2dp_sink_cb.decoder_interface == nullptr) {
702     log::error("cannot stream audio: no source decoder interface");
703     return;
704   }
705 
706   if (!btif_a2dp_sink_cb.decoder_interface->decoder_init(btif_a2dp_sink_on_decode_complete)) {
707     log::error("failed to initialize decoder");
708     return;
709   }
710 
711   if (btif_a2dp_sink_cb.decoder_interface->decoder_configure != nullptr) {
712     btif_a2dp_sink_cb.decoder_interface->decoder_configure(p_buf->codec_info);
713   }
714 
715   log::verbose("create audio track");
716   btif_a2dp_sink_cb.audio_track =
717 #ifdef __ANDROID__
718           BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count);
719 #else
720           NULL;
721 #endif
722   if (btif_a2dp_sink_cb.audio_track == nullptr) {
723     log::error("track creation failed");
724     return;
725   }
726 }
727 
btif_a2dp_sink_enqueue_buf(BT_HDR * p_pkt)728 uint8_t btif_a2dp_sink_enqueue_buf(BT_HDR* p_pkt) {
729   LockGuard lock(g_mutex);
730   if (btif_a2dp_sink_cb.rx_flush) { /* Flush enabled, do not enqueue */
731     return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
732   }
733 
734   log::verbose("+");
735   /* Allocate and queue this buffer */
736   BT_HDR* p_msg = reinterpret_cast<BT_HDR*>(osi_malloc(sizeof(*p_msg) + p_pkt->len));
737   memcpy(p_msg, p_pkt, sizeof(*p_msg));
738   p_msg->offset = 0;
739   memcpy(p_msg->data, p_pkt->data + p_pkt->offset, p_pkt->len);
740   fixed_queue_enqueue(btif_a2dp_sink_cb.rx_audio_queue, p_msg);
741 
742   if (fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) == MAX_INPUT_A2DP_FRAME_QUEUE_SZ) {
743     osi_free(fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue));
744     uint8_t ret = fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
745     return ret;
746   }
747 
748   // Avoid other checks if alarm has already been initialized.
749   if (btif_a2dp_sink_cb.decode_alarm == nullptr &&
750       fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) >= MAX_A2DP_DELAYED_START_FRAME_COUNT) {
751     log::verbose("Initiate decoding. Current focus state:{}", btif_a2dp_sink_cb.rx_focus_state);
752     if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_GRANTED) {
753       btif_a2dp_sink_audio_handle_start_decoding();
754     }
755   }
756 
757   return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
758 }
759 
btif_a2dp_sink_audio_rx_flush_req()760 void btif_a2dp_sink_audio_rx_flush_req() {
761   log::info("");
762   if (fixed_queue_is_empty(btif_a2dp_sink_cb.rx_audio_queue)) {
763     /* Queue is already empty */
764     return;
765   }
766 
767   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
768   p_buf->event = BTIF_MEDIA_SINK_AUDIO_RX_FLUSH;
769   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
770                                              base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
771 }
772 
btif_a2dp_sink_debug_dump(int)773 void btif_a2dp_sink_debug_dump(int /* fd */) {
774   // Nothing to do
775 }
776 
btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state)777 void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state) {
778   log::info("");
779   tBTIF_MEDIA_SINK_FOCUS_UPDATE* p_buf = reinterpret_cast<tBTIF_MEDIA_SINK_FOCUS_UPDATE*>(
780           osi_malloc(sizeof(tBTIF_MEDIA_SINK_FOCUS_UPDATE)));
781   p_buf->focus_state = state;
782   p_buf->hdr.event = BTIF_MEDIA_SINK_SET_FOCUS_STATE;
783   btif_a2dp_sink_cb.worker_thread.DoInThread(
784           FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
785 }
786 
btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state)787 static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state) {
788   log::info("state={}", state);
789   LockGuard lock(g_mutex);
790 
791   log::verbose("setting focus state to {}", state);
792   btif_a2dp_sink_cb.rx_focus_state = state;
793   if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_NOT_GRANTED) {
794     fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
795     btif_a2dp_sink_cb.rx_flush = true;
796   } else if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_GRANTED) {
797     btif_a2dp_sink_cb.rx_flush = false;
798   }
799 }
800 
btif_a2dp_sink_set_audio_track_gain(float gain)801 void btif_a2dp_sink_set_audio_track_gain(float gain) {
802   log::debug("set gain to {:f}", gain);
803   LockGuard lock(g_mutex);
804 
805 #ifdef __ANDROID__
806   BtifAvrcpSetAudioTrackGain(btif_a2dp_sink_cb.audio_track, gain);
807 #endif
808 }
809 
btif_a2dp_sink_get_audio_track(void)810 void* btif_a2dp_sink_get_audio_track(void) { return btif_a2dp_sink_cb.audio_track; }
811 
btif_a2dp_sink_clear_track_event_req()812 static void btif_a2dp_sink_clear_track_event_req() {
813   log::info("");
814   BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
815 
816   p_buf->event = BTIF_MEDIA_SINK_CLEAR_TRACK;
817   btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
818                                              base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
819 }
820 
btif_a2dp_sink_on_start_event()821 static void btif_a2dp_sink_on_start_event() {
822   log::info("");
823 
824   if ((btif_a2dp_sink_cb.decoder_interface != nullptr) &&
825       (btif_a2dp_sink_cb.decoder_interface->decoder_start != nullptr)) {
826     btif_a2dp_sink_cb.decoder_interface->decoder_start();
827   }
828 
829   return;
830 }
831 
btif_a2dp_sink_on_suspend_event()832 static void btif_a2dp_sink_on_suspend_event() {
833   log::info("");
834 
835   if ((btif_a2dp_sink_cb.decoder_interface != nullptr) &&
836       (btif_a2dp_sink_cb.decoder_interface->decoder_suspend != nullptr)) {
837     btif_a2dp_sink_cb.decoder_interface->decoder_suspend();
838   }
839 
840   return;
841 }
842