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_a2dp_control.h"
23 
24 #include <bluetooth/log.h>
25 #include <stdbool.h>
26 #include <stdint.h>
27 
28 #include "audio_a2dp_hw/include/audio_a2dp_hw.h"
29 #include "btif_a2dp_sink.h"
30 #include "btif_a2dp_source.h"
31 #include "btif_av.h"
32 #include "btif_av_co.h"
33 #include "btif_hf.h"
34 #include "types/raw_address.h"
35 #include "udrv/include/uipc.h"
36 
37 #define A2DP_DATA_READ_POLL_MS 10
38 
39 using namespace bluetooth;
40 
41 namespace fmt {
42 template <>
43 struct formatter<tA2DP_CTRL_CMD> : enum_formatter<tA2DP_CTRL_CMD> {};
44 template <>
45 struct formatter<tA2DP_CTRL_ACK> : enum_formatter<tA2DP_CTRL_ACK> {};
46 template <>
47 struct formatter<tUIPC_EVENT> : enum_formatter<tUIPC_EVENT> {};
48 }  // namespace fmt
49 
50 struct {
51   uint64_t total_bytes_read = 0;
52   uint16_t audio_delay = 0;
53   struct timespec timestamp = {};
54 } delay_report_stats;
55 
56 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
57 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
58 
59 /* We can have max one command pending */
60 static tA2DP_CTRL_CMD a2dp_cmd_pending = A2DP_CTRL_CMD_NONE;
61 std::unique_ptr<tUIPC_STATE> a2dp_uipc = nullptr;
62 
btif_a2dp_control_init(void)63 void btif_a2dp_control_init(void) {
64   a2dp_uipc = UIPC_Init();
65   UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, btif_a2dp_ctrl_cb, A2DP_CTRL_PATH);
66 }
67 
btif_a2dp_control_cleanup(void)68 void btif_a2dp_control_cleanup(void) {
69   /* This calls blocks until UIPC is fully closed */
70   if (a2dp_uipc != nullptr) {
71     UIPC_Close(*a2dp_uipc, UIPC_CH_ID_ALL);
72   }
73 }
74 
btif_a2dp_control_on_check_ready()75 static tA2DP_CTRL_ACK btif_a2dp_control_on_check_ready() {
76   if (btif_a2dp_source_media_task_is_shutting_down()) {
77     log::warn("A2DP command check ready while media task shutting down");
78     return A2DP_CTRL_ACK_FAILURE;
79   }
80 
81   /* check whether AV is ready to setup A2DP datapath */
82   if (btif_av_stream_ready(A2dpType::kSource) ||
83       btif_av_stream_started_ready(A2dpType::kSource)) {
84     return A2DP_CTRL_ACK_SUCCESS;
85   } else {
86     log::warn("A2DP command check ready while AV stream is not ready");
87     return A2DP_CTRL_ACK_FAILURE;
88   }
89 }
90 
btif_a2dp_control_on_start()91 static tA2DP_CTRL_ACK btif_a2dp_control_on_start() {
92   /*
93    * Don't send START request to stack while we are in a call.
94    * Some headsets such as "Sony MW600", don't allow AVDTP START
95    * while in a call, and respond with BAD_STATE.
96    */
97   if (!bluetooth::headset::IsCallIdle()) {
98     log::warn("A2DP command start while call state is busy");
99     return A2DP_CTRL_ACK_INCALL_FAILURE;
100   }
101 
102   if (btif_av_stream_ready(A2dpType::kSource)) {
103     /* Setup audio data channel listener */
104     UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb,
105               A2DP_DATA_PATH);
106 
107     /*
108      * Post start event and wait for audio path to open.
109      * If we are the source, the ACK will be sent after the start
110      * procedure is completed, othewise send it now.
111      */
112     btif_av_stream_start(A2dpType::kSource);
113     if (btif_av_get_peer_sep(A2dpType::kSource) == AVDT_TSEP_SRC)
114       return A2DP_CTRL_ACK_SUCCESS;
115   }
116 
117   if (btif_av_stream_started_ready(A2dpType::kSource)) {
118     /*
119      * Already started, setup audio data channel listener and ACK
120      * back immediately.
121      */
122     UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb,
123               A2DP_DATA_PATH);
124     return A2DP_CTRL_ACK_SUCCESS;
125   }
126   log::warn("A2DP command start while AV stream is not ready");
127   return A2DP_CTRL_ACK_FAILURE;
128 }
129 
btif_a2dp_control_on_stop()130 static tA2DP_CTRL_ACK btif_a2dp_control_on_stop() {
131   btif_av_stream_stop(RawAddress::kEmpty);
132   return A2DP_CTRL_ACK_SUCCESS;
133 }
134 
btif_a2dp_control_on_suspend()135 static void btif_a2dp_control_on_suspend() {
136   /* Local suspend */
137   if (btif_av_stream_started_ready(A2dpType::kSource)) {
138     btif_av_stream_suspend();
139     return;
140   }
141   /* If we are not in started state, just ack back ok and let
142    * audioflinger close the channel. This can happen if we are
143    * remotely suspended, clear REMOTE SUSPEND flag.
144    */
145   btif_av_clear_remote_suspend_flag(A2dpType::kSource);
146   btif_a2dp_command_ack(A2DP_CTRL_ACK_SUCCESS);
147 }
148 
btif_a2dp_control_on_get_input_audio_config()149 static void btif_a2dp_control_on_get_input_audio_config() {
150   tA2DP_SAMPLE_RATE sample_rate = btif_a2dp_sink_get_sample_rate();
151   tA2DP_CHANNEL_COUNT channel_count = btif_a2dp_sink_get_channel_count();
152 
153   btif_a2dp_command_ack(A2DP_CTRL_ACK_SUCCESS);
154   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
155             reinterpret_cast<uint8_t*>(&sample_rate),
156             sizeof(tA2DP_SAMPLE_RATE));
157   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0, &channel_count,
158             sizeof(tA2DP_CHANNEL_COUNT));
159 }
160 
btif_a2dp_control_on_get_output_audio_config()161 static void btif_a2dp_control_on_get_output_audio_config() {
162   btav_a2dp_codec_config_t codec_config;
163   btav_a2dp_codec_config_t codec_capability;
164   codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
165   codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
166   codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
167   codec_capability.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
168   codec_capability.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
169   codec_capability.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
170 
171   A2dpCodecConfig* current_codec = bta_av_get_a2dp_current_codec();
172   if (current_codec != nullptr) {
173     codec_config = current_codec->getCodecConfig();
174     codec_capability = current_codec->getCodecCapability();
175   }
176 
177   btif_a2dp_command_ack(A2DP_CTRL_ACK_SUCCESS);
178   // Send the current codec config
179   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
180             reinterpret_cast<const uint8_t*>(&codec_config.sample_rate),
181             sizeof(btav_a2dp_codec_sample_rate_t));
182   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
183             reinterpret_cast<const uint8_t*>(&codec_config.bits_per_sample),
184             sizeof(btav_a2dp_codec_bits_per_sample_t));
185   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
186             reinterpret_cast<const uint8_t*>(&codec_config.channel_mode),
187             sizeof(btav_a2dp_codec_channel_mode_t));
188   // Send the current codec capability
189   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
190             reinterpret_cast<const uint8_t*>(&codec_capability.sample_rate),
191             sizeof(btav_a2dp_codec_sample_rate_t));
192   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
193             reinterpret_cast<const uint8_t*>(&codec_capability.bits_per_sample),
194             sizeof(btav_a2dp_codec_bits_per_sample_t));
195   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
196             reinterpret_cast<const uint8_t*>(&codec_capability.channel_mode),
197             sizeof(btav_a2dp_codec_channel_mode_t));
198 }
199 
btif_a2dp_control_on_set_output_audio_config()200 static void btif_a2dp_control_on_set_output_audio_config() {
201   btav_a2dp_codec_config_t codec_config;
202   codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
203   codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
204   codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
205 
206   btif_a2dp_command_ack(A2DP_CTRL_ACK_SUCCESS);
207   // Send the current codec config
208   if (UIPC_Read(*a2dp_uipc, UIPC_CH_ID_AV_CTRL,
209                 reinterpret_cast<uint8_t*>(&codec_config.sample_rate),
210                 sizeof(btav_a2dp_codec_sample_rate_t)) !=
211       sizeof(btav_a2dp_codec_sample_rate_t)) {
212     log::error("Error reading sample rate from audio HAL");
213     return;
214   }
215   if (UIPC_Read(*a2dp_uipc, UIPC_CH_ID_AV_CTRL,
216                 reinterpret_cast<uint8_t*>(&codec_config.bits_per_sample),
217                 sizeof(btav_a2dp_codec_bits_per_sample_t)) !=
218       sizeof(btav_a2dp_codec_bits_per_sample_t)) {
219     log::error("Error reading bits per sample from audio HAL");
220     return;
221   }
222   if (UIPC_Read(*a2dp_uipc, UIPC_CH_ID_AV_CTRL,
223                 reinterpret_cast<uint8_t*>(&codec_config.channel_mode),
224                 sizeof(btav_a2dp_codec_channel_mode_t)) !=
225       sizeof(btav_a2dp_codec_channel_mode_t)) {
226     log::error("Error reading channel mode from audio HAL");
227     return;
228   }
229   log::verbose(
230       "A2DP_CTRL_SET_OUTPUT_AUDIO_CONFIG: sample_rate=0x{:x} "
231       "bits_per_sample=0x{:x} channel_mode=0x{:x}",
232       codec_config.sample_rate, codec_config.bits_per_sample,
233       codec_config.channel_mode);
234   btif_a2dp_source_feeding_update_req(codec_config);
235 }
236 
btif_a2dp_control_on_get_presentation_position()237 static void btif_a2dp_control_on_get_presentation_position() {
238   btif_a2dp_command_ack(A2DP_CTRL_ACK_SUCCESS);
239 
240   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
241             (uint8_t*)&(delay_report_stats.total_bytes_read), sizeof(uint64_t));
242   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0,
243             (uint8_t*)&(delay_report_stats.audio_delay), sizeof(uint16_t));
244 
245   uint32_t seconds = delay_report_stats.timestamp.tv_sec;
246   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0, (uint8_t*)&seconds,
247             sizeof(seconds));
248 
249   uint32_t nsec = delay_report_stats.timestamp.tv_nsec;
250   UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0, (uint8_t*)&nsec, sizeof(nsec));
251 }
252 
btif_a2dp_recv_ctrl_data(void)253 static void btif_a2dp_recv_ctrl_data(void) {
254   tA2DP_CTRL_CMD cmd = A2DP_CTRL_CMD_NONE;
255   int n;
256 
257   uint8_t read_cmd = 0; /* The read command size is one octet */
258   n = UIPC_Read(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, &read_cmd, 1);
259   cmd = static_cast<tA2DP_CTRL_CMD>(read_cmd);
260 
261   /* detach on ctrl channel means audioflinger process was terminated */
262   if (n == 0) {
263     log::warn("CTRL CH DETACHED");
264     UIPC_Close(*a2dp_uipc, UIPC_CH_ID_AV_CTRL);
265     return;
266   }
267 
268   // Don't log A2DP_CTRL_GET_PRESENTATION_POSITION by default, because it
269   // could be very chatty when audio is streaming.
270   if (cmd == A2DP_CTRL_GET_PRESENTATION_POSITION) {
271     log::verbose("a2dp-ctrl-cmd : {}", audio_a2dp_hw_dump_ctrl_event(cmd));
272   } else {
273     log::warn("a2dp-ctrl-cmd : {}", audio_a2dp_hw_dump_ctrl_event(cmd));
274   }
275 
276   a2dp_cmd_pending = cmd;
277   switch (cmd) {
278     case A2DP_CTRL_CMD_CHECK_READY:
279       btif_a2dp_command_ack(btif_a2dp_control_on_check_ready());
280       break;
281 
282     case A2DP_CTRL_CMD_START:
283       btif_a2dp_command_ack(btif_a2dp_control_on_start());
284       break;
285 
286     case A2DP_CTRL_CMD_STOP:
287       btif_a2dp_command_ack(btif_a2dp_control_on_stop());
288       break;
289 
290     case A2DP_CTRL_CMD_SUSPEND:
291       btif_a2dp_control_on_suspend();
292       break;
293 
294     case A2DP_CTRL_GET_INPUT_AUDIO_CONFIG:
295       btif_a2dp_control_on_get_input_audio_config();
296       break;
297 
298     case A2DP_CTRL_GET_OUTPUT_AUDIO_CONFIG:
299       btif_a2dp_control_on_get_output_audio_config();
300       break;
301 
302     case A2DP_CTRL_SET_OUTPUT_AUDIO_CONFIG:
303       btif_a2dp_control_on_set_output_audio_config();
304       break;
305 
306     case A2DP_CTRL_GET_PRESENTATION_POSITION:
307       btif_a2dp_control_on_get_presentation_position();
308       break;
309 
310     default:
311       log::error("UNSUPPORTED CMD ({})", cmd);
312       btif_a2dp_command_ack(A2DP_CTRL_ACK_FAILURE);
313       break;
314   }
315 
316   // Don't log A2DP_CTRL_GET_PRESENTATION_POSITION by default, because it
317   // could be very chatty when audio is streaming.
318   if (cmd == A2DP_CTRL_GET_PRESENTATION_POSITION) {
319     log::verbose("a2dp-ctrl-cmd : {} DONE", audio_a2dp_hw_dump_ctrl_event(cmd));
320   } else {
321     log::warn("a2dp-ctrl-cmd : {} DONE", audio_a2dp_hw_dump_ctrl_event(cmd));
322   }
323 }
324 
btif_a2dp_ctrl_cb(tUIPC_CH_ID,tUIPC_EVENT event)325 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID /* ch_id */, tUIPC_EVENT event) {
326   // Don't log UIPC_RX_DATA_READY_EVT by default, because it
327   // could be very chatty when audio is streaming.
328   if (event == UIPC_RX_DATA_READY_EVT) {
329     log::verbose("A2DP-CTRL-CHANNEL EVENT {}", dump_uipc_event(event));
330   } else {
331     log::warn("A2DP-CTRL-CHANNEL EVENT {}", dump_uipc_event(event));
332   }
333 
334   switch (event) {
335     case UIPC_OPEN_EVT:
336       break;
337 
338     case UIPC_CLOSE_EVT:
339       /* restart ctrl server unless we are shutting down */
340       if (btif_a2dp_source_media_task_is_running())
341         UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, btif_a2dp_ctrl_cb,
342                   A2DP_CTRL_PATH);
343       break;
344 
345     case UIPC_RX_DATA_READY_EVT:
346       btif_a2dp_recv_ctrl_data();
347       break;
348 
349     default:
350       log::error("### A2DP-CTRL-CHANNEL EVENT {} NOT HANDLED ###", event);
351       break;
352   }
353 }
354 
btif_a2dp_data_cb(tUIPC_CH_ID,tUIPC_EVENT event)355 static void btif_a2dp_data_cb(tUIPC_CH_ID /* ch_id */, tUIPC_EVENT event) {
356   log::warn("BTIF MEDIA (A2DP-DATA) EVENT {}", dump_uipc_event(event));
357 
358   switch (event) {
359     case UIPC_OPEN_EVT:
360       /*
361        * Read directly from media task from here on (keep callback for
362        * connection events.
363        */
364       UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO,
365                  UIPC_REG_REMOVE_ACTIVE_READSET, NULL);
366       UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO,
367                  reinterpret_cast<void*>(A2DP_DATA_READ_POLL_MS));
368 
369       if (btif_av_get_peer_sep(A2dpType::kSource) == AVDT_TSEP_SNK) {
370         /* Start the media task to encode the audio */
371         btif_a2dp_source_start_audio_req();
372       }
373 
374       /* ACK back when media task is fully started */
375       break;
376 
377     case UIPC_CLOSE_EVT:
378       log::verbose("## AUDIO PATH DETACHED ##");
379       btif_a2dp_command_ack(A2DP_CTRL_ACK_SUCCESS);
380       /* Post stop event and wait for audio path to stop */
381       btif_av_stream_stop(RawAddress::kEmpty);
382       break;
383 
384     default:
385       log::error("### A2DP-DATA EVENT {} NOT HANDLED ###", event);
386       break;
387   }
388 }
389 
btif_a2dp_command_ack(tA2DP_CTRL_ACK status)390 void btif_a2dp_command_ack(tA2DP_CTRL_ACK status) {
391   uint8_t ack = status;
392 
393   // Don't log A2DP_CTRL_GET_PRESENTATION_POSITION by default, because it
394   // could be very chatty when audio is streaming.
395   if (a2dp_cmd_pending == A2DP_CTRL_GET_PRESENTATION_POSITION) {
396     log::verbose("## a2dp ack : {}, status {} ##",
397                  audio_a2dp_hw_dump_ctrl_event(a2dp_cmd_pending), status);
398   } else {
399     log::warn("## a2dp ack : {}, status {} ##",
400               audio_a2dp_hw_dump_ctrl_event(a2dp_cmd_pending), status);
401   }
402 
403   /* Sanity check */
404   if (a2dp_cmd_pending == A2DP_CTRL_CMD_NONE) {
405     log::error("warning : no command pending, ignore ack");
406     return;
407   }
408 
409   /* Clear pending */
410   a2dp_cmd_pending = A2DP_CTRL_CMD_NONE;
411 
412   /* Acknowledge start request */
413   if (a2dp_uipc != nullptr) {
414     UIPC_Send(*a2dp_uipc, UIPC_CH_ID_AV_CTRL, 0, &ack, sizeof(ack));
415   }
416 }
417 
btif_a2dp_control_log_bytes_read(uint32_t bytes_read)418 void btif_a2dp_control_log_bytes_read(uint32_t bytes_read) {
419   delay_report_stats.total_bytes_read += bytes_read;
420   clock_gettime(CLOCK_MONOTONIC, &delay_report_stats.timestamp);
421 }
422 
btif_a2dp_control_set_audio_delay(uint16_t delay)423 void btif_a2dp_control_set_audio_delay(uint16_t delay) {
424   log::verbose("DELAY: {:.1f} ms", (float)delay / 10);
425   delay_report_stats.audio_delay = delay;
426 }
427 
btif_a2dp_control_reset_audio_delay(void)428 void btif_a2dp_control_reset_audio_delay(void) {
429   log::verbose("");
430   delay_report_stats.audio_delay = 0;
431   delay_report_stats.total_bytes_read = 0;
432   delay_report_stats.timestamp = {};
433 }
434