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