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 <base/bind.h>
23 #include <atomic>
24 #include <mutex>
25 #include <string>
26 
27 #include "bt_target.h"  // Must be first to define build configuration
28 
29 #include "btif/include/btif_a2dp_sink.h"
30 #include "btif/include/btif_av.h"
31 #include "btif/include/btif_av_co.h"
32 #include "btif/include/btif_avrcp_audio_track.h"
33 #include "btif/include/btif_util.h"  // CASE_RETURN_STR
34 #include "common/message_loop_thread.h"
35 #include "osi/include/alarm.h"
36 #include "osi/include/allocator.h"
37 #include "osi/include/fixed_queue.h"
38 #include "osi/include/log.h"
39 #include "osi/include/osi.h"  // UNUSED_ATTR
40 #include "stack/include/bt_types.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_RIGID hdr;
74   uint8_t codec_info[AVDT_CODEC_SIZE];
75 } tBTIF_MEDIA_SINK_DECODER_UPDATE;
76 
77 typedef struct {
78   BT_HDR_RIGID 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_RIGID* 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_RIGID * p_msg)351 static void btif_a2dp_sink_command_ready(BT_HDR_RIGID* 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,
402       base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
403 }
404 
btif_a2dp_sink_on_idle()405 void btif_a2dp_sink_on_idle() {
406   LOG_INFO("%s", __func__);
407   BT_HDR_RIGID* p_buf =
408       reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
409   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
410   btif_a2dp_sink_cb.worker_thread.DoInThread(
411       FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
412 
413   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) return;
414   btif_a2dp_sink_audio_handle_stop_decoding();
415   btif_a2dp_sink_clear_track_event_req();
416 }
417 
btif_a2dp_sink_on_stopped(UNUSED_ATTR tBTA_AV_SUSPEND * p_av_suspend)418 void btif_a2dp_sink_on_stopped(UNUSED_ATTR tBTA_AV_SUSPEND* p_av_suspend) {
419   LOG_INFO("%s", __func__);
420   BT_HDR_RIGID* p_buf =
421       reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
422   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
423   btif_a2dp_sink_cb.worker_thread.DoInThread(
424       FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
425 
426   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) return;
427   btif_a2dp_sink_audio_handle_stop_decoding();
428 }
429 
btif_a2dp_sink_on_suspended(UNUSED_ATTR tBTA_AV_SUSPEND * p_av_suspend)430 void btif_a2dp_sink_on_suspended(UNUSED_ATTR tBTA_AV_SUSPEND* p_av_suspend) {
431   LOG_INFO("%s", __func__);
432   BT_HDR_RIGID* p_buf =
433       reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
434   p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
435   btif_a2dp_sink_cb.worker_thread.DoInThread(
436       FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
437 
438   if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) return;
439   btif_a2dp_sink_audio_handle_stop_decoding();
440 }
441 
btif_a2dp_sink_on_start()442 bool btif_a2dp_sink_on_start() {
443   LOG_INFO("%s", __func__);
444 
445   BT_HDR_RIGID* p_buf =
446       reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
447   p_buf->event = BTIF_MEDIA_SINK_START;
448   btif_a2dp_sink_cb.worker_thread.DoInThread(
449       FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
450 
451   return true;
452 }
453 
btif_a2dp_sink_audio_handle_stop_decoding()454 static void btif_a2dp_sink_audio_handle_stop_decoding() {
455   LOG_INFO("%s", __func__);
456   alarm_t* old_alarm;
457   {
458     LockGuard lock(g_mutex);
459     btif_a2dp_sink_cb.rx_flush = true;
460     btif_a2dp_sink_audio_rx_flush_req();
461     old_alarm = btif_a2dp_sink_cb.decode_alarm;
462     btif_a2dp_sink_cb.decode_alarm = nullptr;
463   }
464 
465   // Drop the lock here, btif_decode_alarm_cb may in the process of being called
466   // while we alarm free leading to deadlock.
467   //
468   // alarm_free waits for btif_decode_alarm_cb which is waiting for g_mutex.
469   alarm_free(old_alarm);
470 
471   {
472     LockGuard lock(g_mutex);
473 #ifndef OS_GENERIC
474     BtifAvrcpAudioTrackPause(btif_a2dp_sink_cb.audio_track);
475 #endif
476   }
477 }
478 
btif_decode_alarm_cb(UNUSED_ATTR void * context)479 static void btif_decode_alarm_cb(UNUSED_ATTR void* context) {
480   LockGuard lock(g_mutex);
481   btif_a2dp_sink_cb.worker_thread.DoInThread(
482       FROM_HERE, base::BindOnce(btif_a2dp_sink_avk_handle_timer));
483 }
484 
btif_a2dp_sink_clear_track_event()485 static void btif_a2dp_sink_clear_track_event() {
486   LOG_INFO("%s", __func__);
487   LockGuard lock(g_mutex);
488 
489 #ifndef OS_GENERIC
490   BtifAvrcpAudioTrackStop(btif_a2dp_sink_cb.audio_track);
491   BtifAvrcpAudioTrackDelete(btif_a2dp_sink_cb.audio_track);
492 #endif
493   btif_a2dp_sink_cb.audio_track = nullptr;
494 }
495 
496 // Must be called while locked.
btif_a2dp_sink_audio_handle_start_decoding()497 static void btif_a2dp_sink_audio_handle_start_decoding() {
498   LOG_INFO("%s", __func__);
499   if (btif_a2dp_sink_cb.decode_alarm != nullptr)
500     return;  // Already started decoding
501 
502 #ifndef OS_GENERIC
503   BtifAvrcpAudioTrackStart(btif_a2dp_sink_cb.audio_track);
504 #endif
505 
506   btif_a2dp_sink_cb.decode_alarm = alarm_new_periodic("btif.a2dp_sink_decode");
507   if (btif_a2dp_sink_cb.decode_alarm == nullptr) {
508     LOG_ERROR("%s: unable to allocate decode alarm", __func__);
509     return;
510   }
511   alarm_set(btif_a2dp_sink_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK_MS,
512             btif_decode_alarm_cb, nullptr);
513 }
514 
btif_a2dp_sink_on_decode_complete(uint8_t * data,uint32_t len)515 static void btif_a2dp_sink_on_decode_complete(uint8_t* data, uint32_t len) {
516 #ifndef OS_GENERIC
517   BtifAvrcpAudioTrackWriteData(btif_a2dp_sink_cb.audio_track,
518                                reinterpret_cast<void*>(data), len);
519 #endif
520 }
521 
522 // Must be called while locked.
btif_a2dp_sink_handle_inc_media(BT_HDR * p_msg)523 static void btif_a2dp_sink_handle_inc_media(BT_HDR* p_msg) {
524   if ((btif_av_get_peer_sep() == AVDT_TSEP_SNK) ||
525       (btif_a2dp_sink_cb.rx_flush)) {
526     APPL_TRACE_DEBUG("%s: state changed happened in this tick", __func__);
527     return;
528   }
529 
530   CHECK(btif_a2dp_sink_cb.decoder_interface != nullptr);
531   if (!btif_a2dp_sink_cb.decoder_interface->decode_packet(p_msg)) {
532     LOG_ERROR("%s: decoding failed", __func__);
533   }
534 }
535 
btif_a2dp_sink_avk_handle_timer()536 static void btif_a2dp_sink_avk_handle_timer() {
537   LockGuard lock(g_mutex);
538 
539   BT_HDR* p_msg;
540   if (fixed_queue_is_empty(btif_a2dp_sink_cb.rx_audio_queue)) {
541     APPL_TRACE_DEBUG("%s: empty queue", __func__);
542     return;
543   }
544 
545   /* Don't do anything in case of focus not granted */
546   if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_NOT_GRANTED) {
547     APPL_TRACE_DEBUG("%s: skipping frames since focus is not present",
548                      __func__);
549     return;
550   }
551   /* Play only in BTIF_A2DP_SINK_FOCUS_GRANTED case */
552   if (btif_a2dp_sink_cb.rx_flush) {
553     fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
554     return;
555   }
556 
557   APPL_TRACE_DEBUG("%s: process frames begin", __func__);
558   while (true) {
559     p_msg = (BT_HDR*)fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue);
560     if (p_msg == NULL) {
561       break;
562     }
563     APPL_TRACE_DEBUG("%s: number of packets in queue %zu", __func__,
564                      fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue));
565 
566     /* Queue packet has less frames */
567     btif_a2dp_sink_handle_inc_media(p_msg);
568     osi_free(p_msg);
569   }
570   APPL_TRACE_DEBUG("%s: process frames end", __func__);
571 }
572 
573 /* when true media task discards any rx frames */
btif_a2dp_sink_set_rx_flush(bool enable)574 void btif_a2dp_sink_set_rx_flush(bool enable) {
575   LOG_INFO("%s: enable=%s", __func__, (enable) ? "true" : "false");
576   LockGuard lock(g_mutex);
577 
578   btif_a2dp_sink_cb.rx_flush = enable;
579 }
580 
btif_a2dp_sink_audio_rx_flush_event()581 static void btif_a2dp_sink_audio_rx_flush_event() {
582   LOG_INFO("%s", __func__);
583   LockGuard lock(g_mutex);
584   // Flush all received encoded audio buffers
585   fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
586 }
587 
btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE * p_buf)588 static void btif_a2dp_sink_decoder_update_event(
589     tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) {
590   LOG_INFO("%s", __func__);
591   LockGuard lock(g_mutex);
592   APPL_TRACE_DEBUG("%s: p_codec_info[%x:%x:%x:%x:%x:%x]", __func__,
593                    p_buf->codec_info[1], p_buf->codec_info[2],
594                    p_buf->codec_info[3], p_buf->codec_info[4],
595                    p_buf->codec_info[5], p_buf->codec_info[6]);
596 
597   int sample_rate = A2DP_GetTrackSampleRate(p_buf->codec_info);
598   if (sample_rate == -1) {
599     LOG_ERROR("%s: cannot get the track frequency", __func__);
600     return;
601   }
602   int bits_per_sample = A2DP_GetTrackBitsPerSample(p_buf->codec_info);
603   if (bits_per_sample == -1) {
604     LOG_ERROR("%s: cannot get the bits per sample", __func__);
605     return;
606   }
607   int channel_count = A2DP_GetTrackChannelCount(p_buf->codec_info);
608   if (channel_count == -1) {
609     LOG_ERROR("%s: cannot get the channel count", __func__);
610     return;
611   }
612   int channel_type = A2DP_GetSinkTrackChannelType(p_buf->codec_info);
613   if (channel_type == -1) {
614     LOG_ERROR("%s: cannot get the Sink channel type", __func__);
615     return;
616   }
617   btif_a2dp_sink_cb.sample_rate = sample_rate;
618   btif_a2dp_sink_cb.bits_per_sample = bits_per_sample;
619   btif_a2dp_sink_cb.channel_count = channel_count;
620 
621   btif_a2dp_sink_cb.rx_flush = false;
622   APPL_TRACE_DEBUG("%s: reset to Sink role", __func__);
623 
624   btif_a2dp_sink_cb.decoder_interface = bta_av_co_get_decoder_interface();
625   if (btif_a2dp_sink_cb.decoder_interface == nullptr) {
626     LOG_ERROR("%s: cannot stream audio: no source decoder interface", __func__);
627     return;
628   }
629 
630   if (!btif_a2dp_sink_cb.decoder_interface->decoder_init(
631           btif_a2dp_sink_on_decode_complete)) {
632     LOG_ERROR("%s: failed to initialize decoder", __func__);
633     return;
634   }
635 
636   if (btif_a2dp_sink_cb.decoder_interface->decoder_configure != nullptr) {
637     btif_a2dp_sink_cb.decoder_interface->decoder_configure(p_buf->codec_info);
638   }
639 
640   APPL_TRACE_DEBUG("%s: create audio track", __func__);
641   btif_a2dp_sink_cb.audio_track =
642 #ifndef OS_GENERIC
643       BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count);
644 #else
645       NULL;
646 #endif
647   if (btif_a2dp_sink_cb.audio_track == nullptr) {
648     LOG_ERROR("%s: track creation failed", __func__);
649     return;
650   }
651 }
652 
btif_a2dp_sink_enqueue_buf(BT_HDR * p_pkt)653 uint8_t btif_a2dp_sink_enqueue_buf(BT_HDR* p_pkt) {
654   LockGuard lock(g_mutex);
655   if (btif_a2dp_sink_cb.rx_flush) /* Flush enabled, do not enqueue */
656     return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
657 
658   if (fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) ==
659       MAX_INPUT_A2DP_FRAME_QUEUE_SZ) {
660     uint8_t ret = fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
661     osi_free(fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue));
662     return ret;
663   }
664 
665   BTIF_TRACE_VERBOSE("%s +", __func__);
666   /* Allocate and queue this buffer */
667   BT_HDR* p_msg =
668       reinterpret_cast<BT_HDR*>(osi_malloc(sizeof(*p_msg) + p_pkt->len));
669   memcpy(p_msg, p_pkt, sizeof(*p_msg));
670   p_msg->offset = 0;
671   memcpy(p_msg->data, p_pkt->data + p_pkt->offset, p_pkt->len);
672   fixed_queue_enqueue(btif_a2dp_sink_cb.rx_audio_queue, p_msg);
673   if (fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) ==
674       MAX_A2DP_DELAYED_START_FRAME_COUNT) {
675     BTIF_TRACE_DEBUG("%s: Initiate decoding", __func__);
676     btif_a2dp_sink_audio_handle_start_decoding();
677   }
678 
679   return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue);
680 }
681 
btif_a2dp_sink_audio_rx_flush_req()682 void btif_a2dp_sink_audio_rx_flush_req() {
683   LOG_INFO("%s", __func__);
684   if (fixed_queue_is_empty(btif_a2dp_sink_cb.rx_audio_queue)) {
685     /* Queue is already empty */
686     return;
687   }
688 
689   BT_HDR_RIGID* p_buf =
690       reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
691   p_buf->event = BTIF_MEDIA_SINK_AUDIO_RX_FLUSH;
692   btif_a2dp_sink_cb.worker_thread.DoInThread(
693       FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
694 }
695 
btif_a2dp_sink_debug_dump(UNUSED_ATTR int fd)696 void btif_a2dp_sink_debug_dump(UNUSED_ATTR int fd) {
697   // Nothing to do
698 }
699 
btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state)700 void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state) {
701   LOG_INFO("%s", __func__);
702   tBTIF_MEDIA_SINK_FOCUS_UPDATE* p_buf =
703       reinterpret_cast<tBTIF_MEDIA_SINK_FOCUS_UPDATE*>(
704           osi_malloc(sizeof(tBTIF_MEDIA_SINK_FOCUS_UPDATE)));
705   p_buf->focus_state = state;
706   p_buf->hdr.event = BTIF_MEDIA_SINK_SET_FOCUS_STATE;
707   btif_a2dp_sink_cb.worker_thread.DoInThread(
708       FROM_HERE,
709       base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
710 }
711 
btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state)712 static void btif_a2dp_sink_set_focus_state_event(
713     btif_a2dp_sink_focus_state_t state) {
714   LOG_INFO("%s: state=%d", __func__, state);
715   LockGuard lock(g_mutex);
716 
717   APPL_TRACE_DEBUG("%s: setting focus state to %d", __func__, state);
718   btif_a2dp_sink_cb.rx_focus_state = state;
719   if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_NOT_GRANTED) {
720     fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free);
721     btif_a2dp_sink_cb.rx_flush = true;
722   } else if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_GRANTED) {
723     btif_a2dp_sink_cb.rx_flush = false;
724   }
725 }
726 
btif_a2dp_sink_set_audio_track_gain(float gain)727 void btif_a2dp_sink_set_audio_track_gain(float gain) {
728   LOG_INFO("%s: set gain to %f", __func__, gain);
729   LockGuard lock(g_mutex);
730 
731 #ifndef OS_GENERIC
732   BtifAvrcpSetAudioTrackGain(btif_a2dp_sink_cb.audio_track, gain);
733 #endif
734 }
735 
btif_a2dp_sink_clear_track_event_req()736 static void btif_a2dp_sink_clear_track_event_req() {
737   LOG_INFO("%s", __func__);
738   BT_HDR_RIGID* p_buf =
739       reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
740 
741   p_buf->event = BTIF_MEDIA_SINK_CLEAR_TRACK;
742   btif_a2dp_sink_cb.worker_thread.DoInThread(
743       FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
744 }
745 
btif_a2dp_sink_on_start_event()746 static void btif_a2dp_sink_on_start_event() {
747   LOG_INFO("%s", __func__);
748 
749   if ((btif_a2dp_sink_cb.decoder_interface != nullptr) &&
750       (btif_a2dp_sink_cb.decoder_interface->decoder_start != nullptr)) {
751     btif_a2dp_sink_cb.decoder_interface->decoder_start();
752   }
753 
754   return;
755 }
756 
btif_a2dp_sink_on_suspend_event()757 static void btif_a2dp_sink_on_suspend_event() {
758   LOG_INFO("%s", __func__);
759 
760   if ((btif_a2dp_sink_cb.decoder_interface != nullptr) &&
761       (btif_a2dp_sink_cb.decoder_interface->decoder_suspend != nullptr)) {
762     btif_a2dp_sink_cb.decoder_interface->decoder_suspend();
763   }
764 
765   return;
766 }
767