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