1 /******************************************************************************
2 *
3 * Copyright (C) 2009-2012 Broadcom Corporation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 /******************************************************************************
20 **
21 ** Name: btif_media_task.c
22 **
23 ** Description: This is the multimedia module for the BTIF system. It
24 ** contains task implementations AV, HS and HF profiles
25 ** audio & video processing
26 **
27 ******************************************************************************/
28
29 #define LOG_TAG "bt_btif_media"
30
31 #include <assert.h>
32 #include <fcntl.h>
33 #include <limits.h>
34 #include <pthread.h>
35 #include <stdint.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <sys/stat.h>
39 #include <sys/time.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42
43 #include <hardware/bluetooth.h>
44
45 #include "a2d_api.h"
46 #include "a2d_int.h"
47 #include "a2d_sbc.h"
48 #include "audio_a2dp_hw.h"
49 #include "bt_target.h"
50 #include "bta_api.h"
51 #include "bta_av_api.h"
52 #include "bta_av_ci.h"
53 #include "bta_av_sbc.h"
54 #include "bta_sys.h"
55 #include "bta_sys_int.h"
56 #include "btif_av.h"
57 #include "btif_av_co.h"
58 #include "btif_media.h"
59 #include "btif_sm.h"
60 #include "btif_util.h"
61 #include "btu.h"
62 #include "bt_common.h"
63 #include "device/include/controller.h"
64 #include "l2c_api.h"
65 #include "osi/include/alarm.h"
66 #include "osi/include/fixed_queue.h"
67 #include "osi/include/log.h"
68 #include "osi/include/metrics.h"
69 #include "osi/include/mutex.h"
70 #include "osi/include/thread.h"
71
72 #if (BTA_AV_INCLUDED == TRUE)
73 #include "sbc_encoder.h"
74 #endif
75
76 #if (BTA_AV_SINK_INCLUDED == TRUE)
77 #include "oi_codec_sbc.h"
78 #include "oi_status.h"
79 #endif
80
81 #ifdef USE_AUDIO_TRACK
82 #include "btif_avrcp_audio_track.h"
83 #endif
84
85 #if (BTA_AV_SINK_INCLUDED == TRUE)
86 OI_CODEC_SBC_DECODER_CONTEXT context;
87 OI_UINT32 contextData[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)];
88 OI_INT16 pcmData[15*SBC_MAX_SAMPLES_PER_FRAME*SBC_MAX_CHANNELS];
89 #endif
90
91 /*****************************************************************************
92 ** Constants
93 *****************************************************************************/
94 #ifndef AUDIO_CHANNEL_OUT_MONO
95 #define AUDIO_CHANNEL_OUT_MONO 0x01
96 #endif
97
98 #ifndef AUDIO_CHANNEL_OUT_STEREO
99 #define AUDIO_CHANNEL_OUT_STEREO 0x03
100 #endif
101
102 /* BTIF media cmd event definition : BTIF_MEDIA_TASK_CMD */
103 enum
104 {
105 BTIF_MEDIA_START_AA_TX = 1,
106 BTIF_MEDIA_STOP_AA_TX,
107 BTIF_MEDIA_AA_RX_RDY,
108 BTIF_MEDIA_UIPC_RX_RDY,
109 BTIF_MEDIA_SBC_ENC_INIT,
110 BTIF_MEDIA_SBC_ENC_UPDATE,
111 BTIF_MEDIA_SBC_DEC_INIT,
112 BTIF_MEDIA_VIDEO_DEC_INIT,
113 BTIF_MEDIA_FLUSH_AA_TX,
114 BTIF_MEDIA_FLUSH_AA_RX,
115 BTIF_MEDIA_AUDIO_FEEDING_INIT,
116 BTIF_MEDIA_AUDIO_RECEIVING_INIT,
117 BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE,
118 BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK,
119 BTIF_MEDIA_AUDIO_SINK_SET_FOCUS_STATE
120 };
121
122 enum {
123 MEDIA_TASK_STATE_OFF = 0,
124 MEDIA_TASK_STATE_ON = 1,
125 MEDIA_TASK_STATE_SHUTTING_DOWN = 2
126 };
127
128 /* Macro to multiply the media task tick */
129 #ifndef BTIF_MEDIA_NUM_TICK
130 #define BTIF_MEDIA_NUM_TICK 1
131 #endif
132
133 /* Media task tick in milliseconds, must be set to multiple of
134 (1000/TICKS_PER_SEC) (10) */
135
136 #define BTIF_MEDIA_TIME_TICK (20 * BTIF_MEDIA_NUM_TICK)
137 #define A2DP_DATA_READ_POLL_MS (BTIF_MEDIA_TIME_TICK / 2)
138 #define BTIF_SINK_MEDIA_TIME_TICK_MS (20 * BTIF_MEDIA_NUM_TICK)
139
140
141 /* buffer pool */
142 #define BTIF_MEDIA_AA_BUF_SIZE BT_DEFAULT_BUFFER_SIZE
143
144 /* offset */
145 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
146 #define BTIF_MEDIA_AA_SBC_OFFSET (AVDT_MEDIA_OFFSET + BTA_AV_SBC_HDR_SIZE + 1)
147 #else
148 #define BTIF_MEDIA_AA_SBC_OFFSET (AVDT_MEDIA_OFFSET + BTA_AV_SBC_HDR_SIZE)
149 #endif
150
151 /* Define the bitrate step when trying to match bitpool value */
152 #ifndef BTIF_MEDIA_BITRATE_STEP
153 #define BTIF_MEDIA_BITRATE_STEP 5
154 #endif
155
156 #ifndef BTIF_A2DP_DEFAULT_BITRATE
157 /* High quality quality setting @ 44.1 khz */
158 #define BTIF_A2DP_DEFAULT_BITRATE 328
159 #endif
160
161 #ifndef BTIF_A2DP_NON_EDR_MAX_RATE
162 #define BTIF_A2DP_NON_EDR_MAX_RATE 229
163 #endif
164
165 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
166 /* A2DP header will contain a CP header of size 1 */
167 #define A2DP_HDR_SIZE 2
168 #else
169 #define A2DP_HDR_SIZE 1
170 #endif
171 #define MAX_SBC_HQ_FRAME_SIZE_44_1 119
172 #define MAX_SBC_HQ_FRAME_SIZE_48 115
173
174 /* 2DH5 payload size of 679 bytes - (4 bytes L2CAP Header + 12 bytes AVDTP Header) */
175 #define MAX_2MBPS_AVDTP_MTU 663
176 #define USEC_PER_SEC 1000000L
177 #define TPUT_STATS_INTERVAL_US (3000*1000)
178
179 /**
180 * CONGESTION COMPENSATION CTRL ::
181 *
182 * Thus setting controls how many buffers we will hold in media task
183 * during temp link congestion. Together with the stack buffer queues
184 * it controls much temporary a2dp link congestion we can
185 * compensate for. It however also depends on the default run level of sinks
186 * jitterbuffers. Depending on type of sink this would vary.
187 * Ideally the (SRC) max tx buffer capacity should equal the sinks
188 * jitterbuffer runlevel including any intermediate buffers on the way
189 * towards the sinks codec.
190 */
191 #ifndef MAX_PCM_FRAME_NUM_PER_TICK
192 #define MAX_PCM_FRAME_NUM_PER_TICK 14
193 #endif
194 #define MAX_PCM_ITER_NUM_PER_TICK 3
195
196 /**
197 * The typical runlevel of the tx queue size is ~1 buffer
198 * but due to link flow control or thread preemption in lower
199 * layers we might need to temporarily buffer up data.
200 */
201 #define MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ (MAX_PCM_FRAME_NUM_PER_TICK * 2)
202
203 /* In case of A2DP SINK, we will delay start by 5 AVDTP Packets*/
204 #define MAX_A2DP_DELAYED_START_FRAME_COUNT 5
205 #define PACKET_PLAYED_PER_TICK_48 8
206 #define PACKET_PLAYED_PER_TICK_44 7
207 #define PACKET_PLAYED_PER_TICK_32 5
208 #define PACKET_PLAYED_PER_TICK_16 3
209
210 /* Readability constants */
211 #define SBC_FRAME_HEADER_SIZE_BYTES 4 // A2DP Spec v1.3, 12.4, Table 12.12
212 #define SBC_SCALE_FACTOR_BITS 4 // A2DP Spec v1.3, 12.4, Table 12.13
213
214 typedef struct {
215 // Counter for total updates
216 size_t total_updates;
217
218 // Last update timestamp (in us)
219 uint64_t last_update_us;
220
221 // Counter for overdue scheduling
222 size_t overdue_scheduling_count;
223
224 // Accumulated overdue scheduling deviations (in us)
225 uint64_t total_overdue_scheduling_delta_us;
226
227 // Max. overdue scheduling delta time (in us)
228 uint64_t max_overdue_scheduling_delta_us;
229
230 // Counter for premature scheduling
231 size_t premature_scheduling_count;
232
233 // Accumulated premature scheduling deviations (in us)
234 uint64_t total_premature_scheduling_delta_us;
235
236 // Max. premature scheduling delta time (in us)
237 uint64_t max_premature_scheduling_delta_us;
238
239 // Counter for exact scheduling
240 size_t exact_scheduling_count;
241
242 // Accumulated and counted scheduling time (in us)
243 uint64_t total_scheduling_time_us;
244 } scheduling_stats_t;
245
246 typedef struct {
247 uint64_t session_start_us;
248
249 scheduling_stats_t tx_queue_enqueue_stats;
250 scheduling_stats_t tx_queue_dequeue_stats;
251
252 size_t tx_queue_total_frames;
253 size_t tx_queue_max_frames_per_packet;
254
255 uint64_t tx_queue_total_queueing_time_us;
256 uint64_t tx_queue_max_queueing_time_us;
257
258 size_t tx_queue_total_readbuf_calls;
259 uint64_t tx_queue_last_readbuf_us;
260
261 size_t tx_queue_total_flushed_messages;
262 uint64_t tx_queue_last_flushed_us;
263
264 size_t tx_queue_total_dropped_messages;
265 size_t tx_queue_dropouts;
266 uint64_t tx_queue_last_dropouts_us;
267
268 size_t media_read_total_underflow_bytes;
269 size_t media_read_total_underflow_count;
270 uint64_t media_read_last_underflow_us;
271
272 size_t media_read_total_underrun_bytes;
273 size_t media_read_total_underrun_count;
274 uint64_t media_read_last_underrun_us;
275
276 size_t media_read_total_expected_frames;
277 size_t media_read_max_expected_frames;
278 size_t media_read_expected_count;
279
280 size_t media_read_total_limited_frames;
281 size_t media_read_max_limited_frames;
282 size_t media_read_limited_count;
283 } btif_media_stats_t;
284
285 typedef struct
286 {
287 UINT16 num_frames_to_be_processed;
288 UINT16 len;
289 UINT16 offset;
290 UINT16 layer_specific;
291 } tBT_SBC_HDR;
292
293 typedef struct
294 {
295 UINT32 aa_frame_counter;
296 INT32 aa_feed_counter;
297 INT32 aa_feed_residue;
298 UINT32 counter;
299 UINT32 bytes_per_tick; /* pcm bytes read each media task tick */
300 } tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE;
301
302 typedef union
303 {
304 tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE pcm;
305 } tBTIF_AV_MEDIA_FEEDINGS_STATE;
306
307 typedef struct
308 {
309 #if (BTA_AV_INCLUDED == TRUE)
310 fixed_queue_t *TxAaQ;
311 fixed_queue_t *RxSbcQ;
312 UINT16 TxAaMtuSize;
313 UINT32 timestamp;
314 UINT8 TxTranscoding;
315 tBTIF_AV_FEEDING_MODE feeding_mode;
316 tBTIF_AV_MEDIA_FEEDINGS media_feeding;
317 tBTIF_AV_MEDIA_FEEDINGS_STATE media_feeding_state;
318 SBC_ENC_PARAMS encoder;
319 UINT8 busy_level;
320 void* av_sm_hdl;
321 UINT8 a2dp_cmd_pending; /* we can have max one command pending */
322 BOOLEAN tx_flush; /* discards any outgoing data when true */
323 BOOLEAN rx_flush; /* discards any incoming data when true */
324 UINT8 peer_sep;
325 BOOLEAN data_channel_open;
326 UINT8 frames_to_process;
327 UINT8 tx_sbc_frames;
328
329 UINT32 sample_rate;
330 UINT8 channel_count;
331 #ifdef USE_AUDIO_TRACK
332 btif_media_audio_focus_state rx_audio_focus_state;
333 void *audio_track;
334 #endif
335 alarm_t *media_alarm;
336 alarm_t *decode_alarm;
337 btif_media_stats_t stats;
338 #endif
339 } tBTIF_MEDIA_CB;
340
341 typedef struct {
342 long long rx;
343 long long rx_tot;
344 long long tx;
345 long long tx_tot;
346 long long ts_prev_us;
347 } t_stat;
348
349 static UINT64 last_frame_us = 0;
350
351 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
352 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
353 static void btif_a2dp_encoder_update(void);
354 #if (BTA_AV_SINK_INCLUDED == TRUE)
355 extern OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
356 const OI_BYTE **frameData,
357 unsigned long *frameBytes,
358 OI_INT16 *pcmData,
359 unsigned long *pcmBytes);
360 extern OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
361 unsigned long *decoderData,
362 unsigned long decoderDataBytes,
363 OI_UINT8 maxChannels,
364 OI_UINT8 pcmStride,
365 OI_BOOL enhanced);
366 #endif
367 static void btif_media_flush_q(fixed_queue_t *p_q);
368 static void btif_media_task_aa_handle_stop_decoding(void );
369 static void btif_media_task_aa_rx_flush(void);
370
371 static UINT8 calculate_max_frames_per_packet();
372 static const char *dump_media_event(UINT16 event);
373 static void btif_media_thread_init(void *context);
374 static void btif_media_thread_cleanup(void *context);
375 static void btif_media_thread_handle_cmd(fixed_queue_t *queue, void *context);
376
377 /* Handle incoming media packets A2DP SINK streaming*/
378 #if (BTA_AV_SINK_INCLUDED == TRUE)
379 static void btif_media_task_handle_inc_media(tBT_SBC_HDR*p_msg);
380 #endif
381
382 #if (BTA_AV_INCLUDED == TRUE)
383 static void btif_media_send_aa_frame(uint64_t timestamp_us);
384 static void btif_media_task_feeding_state_reset(void);
385 static void btif_media_task_aa_start_tx(void);
386 static void btif_media_task_aa_stop_tx(void);
387 static void btif_media_task_enc_init(BT_HDR *p_msg);
388 static void btif_media_task_enc_update(BT_HDR *p_msg);
389 static void btif_media_task_audio_feeding_init(BT_HDR *p_msg);
390 static void btif_media_task_aa_tx_flush(BT_HDR *p_msg);
391 static void btif_media_aa_prep_2_send(UINT8 nb_frame, uint64_t timestamp_us);
392 #if (BTA_AV_SINK_INCLUDED == TRUE)
393 static void btif_media_task_aa_handle_decoder_reset(BT_HDR *p_msg);
394 static void btif_media_task_aa_handle_clear_track(void);
395 #endif
396 static void btif_media_task_aa_handle_start_decoding(void);
397 #endif
398 BOOLEAN btif_media_task_clear_track(void);
399
400 static void btif_media_task_aa_handle_timer(UNUSED_ATTR void *context);
401 static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context);
402 extern BOOLEAN btif_hf_is_call_idle();
403
404 static tBTIF_MEDIA_CB btif_media_cb;
405 static int media_task_running = MEDIA_TASK_STATE_OFF;
406
407 static fixed_queue_t *btif_media_cmd_msg_queue;
408 static thread_t *worker_thread;
409
410 /*****************************************************************************
411 ** Misc helper functions
412 *****************************************************************************/
413
update_scheduling_stats(scheduling_stats_t * stats,uint64_t now_us,uint64_t expected_delta)414 static void update_scheduling_stats(scheduling_stats_t *stats,
415 uint64_t now_us, uint64_t expected_delta)
416 {
417 uint64_t last_us = stats->last_update_us;
418
419 stats->total_updates++;
420 stats->last_update_us = now_us;
421
422 if (last_us == 0)
423 return; // First update: expected delta doesn't apply
424
425 uint64_t deadline_us = last_us + expected_delta;
426 if (deadline_us < now_us) {
427 // Overdue scheduling
428 uint64_t delta_us = now_us - deadline_us;
429 // Ignore extreme outliers
430 if (delta_us < 10 * expected_delta) {
431 if (stats->max_overdue_scheduling_delta_us < delta_us)
432 stats->max_overdue_scheduling_delta_us = delta_us;
433 stats->total_overdue_scheduling_delta_us += delta_us;
434 stats->overdue_scheduling_count++;
435 stats->total_scheduling_time_us += now_us - last_us;
436 }
437 } else if (deadline_us > now_us) {
438 // Premature scheduling
439 uint64_t delta_us = deadline_us - now_us;
440 // Ignore extreme outliers
441 if (delta_us < 10 * expected_delta) {
442 if (stats->max_premature_scheduling_delta_us < delta_us)
443 stats->max_premature_scheduling_delta_us = delta_us;
444 stats->total_premature_scheduling_delta_us += delta_us;
445 stats->premature_scheduling_count++;
446 stats->total_scheduling_time_us += now_us - last_us;
447 }
448 } else {
449 // On-time scheduling
450 stats->exact_scheduling_count++;
451 stats->total_scheduling_time_us += now_us - last_us;
452 }
453 }
454
time_now_us()455 static UINT64 time_now_us()
456 {
457 struct timespec ts_now;
458 clock_gettime(CLOCK_BOOTTIME, &ts_now);
459 return ((UINT64)ts_now.tv_sec * USEC_PER_SEC) + ((UINT64)ts_now.tv_nsec / 1000);
460 }
461
log_tstamps_us(char * comment,uint64_t now_us)462 static void log_tstamps_us(char *comment, uint64_t now_us)
463 {
464 static uint64_t prev_us = 0;
465 APPL_TRACE_DEBUG("[%s] ts %08llu, diff : %08llu, queue sz %d", comment, now_us, now_us - prev_us,
466 fixed_queue_length(btif_media_cb.TxAaQ));
467 prev_us = now_us;
468 }
469
dump_media_event(UINT16 event)470 UNUSED_ATTR static const char *dump_media_event(UINT16 event)
471 {
472 switch (event)
473 {
474 CASE_RETURN_STR(BTIF_MEDIA_START_AA_TX)
475 CASE_RETURN_STR(BTIF_MEDIA_STOP_AA_TX)
476 CASE_RETURN_STR(BTIF_MEDIA_AA_RX_RDY)
477 CASE_RETURN_STR(BTIF_MEDIA_UIPC_RX_RDY)
478 CASE_RETURN_STR(BTIF_MEDIA_SBC_ENC_INIT)
479 CASE_RETURN_STR(BTIF_MEDIA_SBC_ENC_UPDATE)
480 CASE_RETURN_STR(BTIF_MEDIA_SBC_DEC_INIT)
481 CASE_RETURN_STR(BTIF_MEDIA_VIDEO_DEC_INIT)
482 CASE_RETURN_STR(BTIF_MEDIA_FLUSH_AA_TX)
483 CASE_RETURN_STR(BTIF_MEDIA_FLUSH_AA_RX)
484 CASE_RETURN_STR(BTIF_MEDIA_AUDIO_FEEDING_INIT)
485 CASE_RETURN_STR(BTIF_MEDIA_AUDIO_RECEIVING_INIT)
486 CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE)
487 CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK)
488 CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_SET_FOCUS_STATE)
489
490 default:
491 return "UNKNOWN MEDIA EVENT";
492 }
493 }
494
btm_read_rssi_cb(void * data)495 static void btm_read_rssi_cb(void *data)
496 {
497 assert(data);
498
499 tBTM_RSSI_RESULTS *result = (tBTM_RSSI_RESULTS*)data;
500 if (result->status != BTM_SUCCESS)
501 {
502 LOG_ERROR(LOG_TAG, "%s unable to read remote RSSI (status %d)",
503 __func__, result->status);
504 return;
505 }
506
507 char temp_buffer[20] = {0};
508 LOG_WARN(LOG_TAG, "%s device: %s, rssi: %d", __func__,
509 bdaddr_to_string((bt_bdaddr_t *)result->rem_bda, temp_buffer,
510 sizeof(temp_buffer)),
511 result->rssi);
512 }
513
514 /*****************************************************************************
515 ** A2DP CTRL PATH
516 *****************************************************************************/
517
dump_a2dp_ctrl_event(UINT8 event)518 static const char* dump_a2dp_ctrl_event(UINT8 event)
519 {
520 switch (event)
521 {
522 CASE_RETURN_STR(A2DP_CTRL_CMD_NONE)
523 CASE_RETURN_STR(A2DP_CTRL_CMD_CHECK_READY)
524 CASE_RETURN_STR(A2DP_CTRL_CMD_START)
525 CASE_RETURN_STR(A2DP_CTRL_CMD_STOP)
526 CASE_RETURN_STR(A2DP_CTRL_CMD_SUSPEND)
527 CASE_RETURN_STR(A2DP_CTRL_CMD_OFFLOAD_START)
528
529 default:
530 return "UNKNOWN MSG ID";
531 }
532 }
533
btif_audiopath_detached(void)534 static void btif_audiopath_detached(void)
535 {
536 APPL_TRACE_EVENT("## AUDIO PATH DETACHED ##");
537
538 /* send stop request only if we are actively streaming and haven't received
539 a stop request. Potentially audioflinger detached abnormally */
540 if (alarm_is_scheduled(btif_media_cb.media_alarm)) {
541 /* post stop event and wait for audio path to stop */
542 btif_dispatch_sm_event(BTIF_AV_STOP_STREAM_REQ_EVT, NULL, 0);
543 }
544 }
545
a2dp_cmd_acknowledge(int status)546 static void a2dp_cmd_acknowledge(int status)
547 {
548 UINT8 ack = status;
549
550 APPL_TRACE_EVENT("## a2dp ack : %s, status %d ##",
551 dump_a2dp_ctrl_event(btif_media_cb.a2dp_cmd_pending), status);
552
553 /* sanity check */
554 if (btif_media_cb.a2dp_cmd_pending == A2DP_CTRL_CMD_NONE)
555 {
556 APPL_TRACE_ERROR("warning : no command pending, ignore ack");
557 return;
558 }
559
560 /* clear pending */
561 btif_media_cb.a2dp_cmd_pending = A2DP_CTRL_CMD_NONE;
562
563 /* acknowledge start request */
564 UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, &ack, 1);
565 }
566
567
btif_recv_ctrl_data(void)568 static void btif_recv_ctrl_data(void)
569 {
570 UINT8 cmd = 0;
571 int n;
572 n = UIPC_Read(UIPC_CH_ID_AV_CTRL, NULL, &cmd, 1);
573
574 /* detach on ctrl channel means audioflinger process was terminated */
575 if (n == 0)
576 {
577 APPL_TRACE_EVENT("CTRL CH DETACHED");
578 UIPC_Close(UIPC_CH_ID_AV_CTRL);
579 /* we can operate only on datachannel, if af client wants to
580 do send additional commands the ctrl channel would be reestablished */
581 //btif_audiopath_detached();
582 return;
583 }
584
585 APPL_TRACE_DEBUG("a2dp-ctrl-cmd : %s", dump_a2dp_ctrl_event(cmd));
586
587 btif_media_cb.a2dp_cmd_pending = cmd;
588
589 switch (cmd)
590 {
591 case A2DP_CTRL_CMD_CHECK_READY:
592
593 if (media_task_running == MEDIA_TASK_STATE_SHUTTING_DOWN)
594 {
595 APPL_TRACE_WARNING("%s: A2DP command %s while media task shutting down",
596 __func__, dump_a2dp_ctrl_event(cmd));
597 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
598 return;
599 }
600
601 /* check whether av is ready to setup a2dp datapath */
602 if ((btif_av_stream_ready() == TRUE) || (btif_av_stream_started_ready() == TRUE))
603 {
604 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
605 }
606 else
607 {
608 APPL_TRACE_WARNING("%s: A2DP command %s while AV stream is not ready",
609 __func__, dump_a2dp_ctrl_event(cmd));
610 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
611 }
612 break;
613
614 case A2DP_CTRL_CMD_START:
615 /* Don't sent START request to stack while we are in call.
616 Some headsets like the Sony MW600, don't allow AVDTP START
617 in call and respond BAD_STATE. */
618 if (!btif_hf_is_call_idle())
619 {
620 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_INCALL_FAILURE);
621 break;
622 }
623
624 if (alarm_is_scheduled(btif_media_cb.media_alarm))
625 {
626 APPL_TRACE_WARNING("%s: A2DP command %s when media alarm already scheduled",
627 __func__, dump_a2dp_ctrl_event(cmd));
628 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
629 break;
630 }
631
632 if (btif_av_stream_ready() == TRUE)
633 {
634 /* setup audio data channel listener */
635 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
636
637 /* post start event and wait for audio path to open */
638 btif_dispatch_sm_event(BTIF_AV_START_STREAM_REQ_EVT, NULL, 0);
639
640 #if (BTA_AV_SINK_INCLUDED == TRUE)
641 if (btif_media_cb.peer_sep == AVDT_TSEP_SRC)
642 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
643 #endif
644 }
645 else if (btif_av_stream_started_ready())
646 {
647 /* already started, setup audio data channel listener
648 and ack back immediately */
649 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
650
651 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
652 }
653 else
654 {
655 APPL_TRACE_WARNING("%s: A2DP command %s while AV stream is not ready",
656 __func__, dump_a2dp_ctrl_event(cmd));
657 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
658 break;
659 }
660 break;
661
662 case A2DP_CTRL_CMD_STOP:
663 if (btif_media_cb.peer_sep == AVDT_TSEP_SNK &&
664 (!alarm_is_scheduled(btif_media_cb.media_alarm)))
665 {
666 /* we are already stopped, just ack back */
667 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
668 break;
669 }
670
671 btif_dispatch_sm_event(BTIF_AV_STOP_STREAM_REQ_EVT, NULL, 0);
672 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
673 break;
674
675 case A2DP_CTRL_CMD_SUSPEND:
676 /* local suspend */
677 if (btif_av_stream_started_ready())
678 {
679 btif_dispatch_sm_event(BTIF_AV_SUSPEND_STREAM_REQ_EVT, NULL, 0);
680 }
681 else
682 {
683 /* if we are not in started state, just ack back ok and let
684 audioflinger close the channel. This can happen if we are
685 remotely suspended, clear REMOTE SUSPEND Flag */
686 btif_av_clear_remote_suspend_flag();
687 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
688 }
689 break;
690
691 case A2DP_CTRL_GET_AUDIO_CONFIG:
692 {
693 uint32_t sample_rate = btif_media_cb.sample_rate;
694 uint8_t channel_count = btif_media_cb.channel_count;
695
696 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
697 UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, (UINT8 *)&sample_rate, 4);
698 UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, &channel_count, 1);
699 break;
700 }
701
702 case A2DP_CTRL_CMD_OFFLOAD_START:
703 btif_dispatch_sm_event(BTIF_AV_OFFLOAD_START_REQ_EVT, NULL, 0);
704 break;
705
706 default:
707 APPL_TRACE_ERROR("UNSUPPORTED CMD (%d)", cmd);
708 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
709 break;
710 }
711 APPL_TRACE_DEBUG("a2dp-ctrl-cmd : %s DONE", dump_a2dp_ctrl_event(cmd));
712 }
713
btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)714 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event)
715 {
716 UNUSED(ch_id);
717
718 APPL_TRACE_DEBUG("A2DP-CTRL-CHANNEL EVENT %s", dump_uipc_event(event));
719
720 switch (event)
721 {
722 case UIPC_OPEN_EVT:
723 /* fetch av statemachine handle */
724 btif_media_cb.av_sm_hdl = btif_av_get_sm_handle();
725 break;
726
727 case UIPC_CLOSE_EVT:
728 /* restart ctrl server unless we are shutting down */
729 if (media_task_running == MEDIA_TASK_STATE_ON)
730 UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
731 break;
732
733 case UIPC_RX_DATA_READY_EVT:
734 btif_recv_ctrl_data();
735 break;
736
737 default :
738 APPL_TRACE_ERROR("### A2DP-CTRL-CHANNEL EVENT %d NOT HANDLED ###", event);
739 break;
740 }
741 }
742
btif_a2dp_data_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)743 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event)
744 {
745 UNUSED(ch_id);
746
747 APPL_TRACE_DEBUG("BTIF MEDIA (A2DP-DATA) EVENT %s", dump_uipc_event(event));
748
749 switch (event)
750 {
751 case UIPC_OPEN_EVT:
752
753 /* read directly from media task from here on (keep callback for
754 connection events */
755 UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL);
756 UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO,
757 (void *)A2DP_DATA_READ_POLL_MS);
758
759 if (btif_media_cb.peer_sep == AVDT_TSEP_SNK) {
760 /* Start the media task to encode SBC */
761 btif_media_task_start_aa_req();
762
763 /* make sure we update any changed sbc encoder params */
764 btif_a2dp_encoder_update();
765 }
766 btif_media_cb.data_channel_open = TRUE;
767
768 /* ack back when media task is fully started */
769 break;
770
771 case UIPC_CLOSE_EVT:
772 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
773 btif_audiopath_detached();
774 btif_media_cb.data_channel_open = FALSE;
775 break;
776
777 default :
778 APPL_TRACE_ERROR("### A2DP-DATA EVENT %d NOT HANDLED ###", event);
779 break;
780 }
781 }
782
783
784 /*****************************************************************************
785 ** BTIF ADAPTATION
786 *****************************************************************************/
787
btif_media_task_get_sbc_rate(void)788 static UINT16 btif_media_task_get_sbc_rate(void)
789 {
790 UINT16 rate = BTIF_A2DP_DEFAULT_BITRATE;
791
792 /* restrict bitrate if a2dp link is non-edr */
793 if (!btif_av_is_peer_edr())
794 {
795 rate = BTIF_A2DP_NON_EDR_MAX_RATE;
796 APPL_TRACE_DEBUG("non-edr a2dp sink detected, restrict rate to %d", rate);
797 }
798
799 return rate;
800 }
801
btif_a2dp_encoder_init(void)802 static void btif_a2dp_encoder_init(void)
803 {
804 UINT16 minmtu;
805 tBTIF_MEDIA_INIT_AUDIO msg;
806 tA2D_SBC_CIE sbc_config;
807
808 /* lookup table for converting channel mode */
809 UINT16 codec_mode_tbl[5] = { SBC_JOINT_STEREO, SBC_STEREO, SBC_DUAL, 0, SBC_MONO };
810
811 /* lookup table for converting number of blocks */
812 UINT16 codec_block_tbl[5] = { 16, 12, 8, 0, 4 };
813
814 /* lookup table to convert freq */
815 UINT16 freq_block_tbl[5] = { SBC_sf48000, SBC_sf44100, SBC_sf32000, 0, SBC_sf16000 };
816
817 APPL_TRACE_DEBUG("btif_a2dp_encoder_init");
818
819 /* Retrieve the current SBC configuration (default if currently not used) */
820 bta_av_co_audio_get_sbc_config(&sbc_config, &minmtu);
821 msg.NumOfSubBands = (sbc_config.num_subbands == A2D_SBC_IE_SUBBAND_4) ? 4 : 8;
822 msg.NumOfBlocks = codec_block_tbl[sbc_config.block_len >> 5];
823 msg.AllocationMethod = (sbc_config.alloc_mthd == A2D_SBC_IE_ALLOC_MD_L) ? SBC_LOUDNESS : SBC_SNR;
824 msg.ChannelMode = codec_mode_tbl[sbc_config.ch_mode >> 1];
825 msg.SamplingFreq = freq_block_tbl[sbc_config.samp_freq >> 5];
826 msg.MtuSize = minmtu;
827
828 APPL_TRACE_EVENT("msg.ChannelMode %x", msg.ChannelMode);
829
830 /* Init the media task to encode SBC properly */
831 btif_media_task_enc_init_req(&msg);
832 }
833
btif_a2dp_encoder_update(void)834 static void btif_a2dp_encoder_update(void)
835 {
836 UINT16 minmtu;
837 tA2D_SBC_CIE sbc_config;
838 tBTIF_MEDIA_UPDATE_AUDIO msg;
839 UINT8 pref_min;
840 UINT8 pref_max;
841
842 APPL_TRACE_DEBUG("btif_a2dp_encoder_update");
843
844 /* Retrieve the current SBC configuration (default if currently not used) */
845 bta_av_co_audio_get_sbc_config(&sbc_config, &minmtu);
846
847 APPL_TRACE_DEBUG("btif_a2dp_encoder_update: Common min_bitpool:%d(0x%x) max_bitpool:%d(0x%x)",
848 sbc_config.min_bitpool, sbc_config.min_bitpool,
849 sbc_config.max_bitpool, sbc_config.max_bitpool);
850
851 if (sbc_config.min_bitpool > sbc_config.max_bitpool)
852 {
853 APPL_TRACE_ERROR("btif_a2dp_encoder_update: ERROR btif_a2dp_encoder_update min_bitpool > max_bitpool");
854 }
855
856 /* check if remote sink has a preferred bitpool range */
857 if (bta_av_co_get_remote_bitpool_pref(&pref_min, &pref_max) == TRUE)
858 {
859 /* adjust our preferred bitpool with the remote preference if within
860 our capable range */
861
862 if (pref_min < sbc_config.min_bitpool)
863 pref_min = sbc_config.min_bitpool;
864
865 if (pref_max > sbc_config.max_bitpool)
866 pref_max = sbc_config.max_bitpool;
867
868 msg.MinBitPool = pref_min;
869 msg.MaxBitPool = pref_max;
870
871 if ((pref_min != sbc_config.min_bitpool) || (pref_max != sbc_config.max_bitpool))
872 {
873 APPL_TRACE_EVENT("## adjusted our bitpool range to peer pref [%d:%d] ##",
874 pref_min, pref_max);
875 }
876 }
877 else
878 {
879 msg.MinBitPool = sbc_config.min_bitpool;
880 msg.MaxBitPool = sbc_config.max_bitpool;
881 }
882
883 msg.MinMtuSize = minmtu;
884
885 /* Update the media task to encode SBC properly */
886 btif_media_task_enc_update_req(&msg);
887 }
888
btif_a2dp_start_media_task(void)889 bool btif_a2dp_start_media_task(void)
890 {
891 if (media_task_running != MEDIA_TASK_STATE_OFF)
892 {
893 APPL_TRACE_ERROR("warning : media task already running");
894 return false;
895 }
896
897 APPL_TRACE_EVENT("## A2DP START MEDIA THREAD ##");
898
899 btif_media_cmd_msg_queue = fixed_queue_new(SIZE_MAX);
900
901 /* start a2dp media task */
902 worker_thread = thread_new("media_worker");
903 if (worker_thread == NULL)
904 goto error_exit;
905
906 fixed_queue_register_dequeue(btif_media_cmd_msg_queue,
907 thread_get_reactor(worker_thread),
908 btif_media_thread_handle_cmd,
909 NULL);
910
911 thread_post(worker_thread, btif_media_thread_init, NULL);
912 APPL_TRACE_EVENT("## A2DP MEDIA THREAD STARTED ##");
913
914 return true;
915
916 error_exit:;
917 APPL_TRACE_ERROR("%s unable to start up media thread", __func__);
918 return false;
919 }
920
btif_a2dp_stop_media_task(void)921 void btif_a2dp_stop_media_task(void)
922 {
923 APPL_TRACE_EVENT("## A2DP STOP MEDIA THREAD ##");
924
925 // Stop timer
926 alarm_free(btif_media_cb.media_alarm);
927 btif_media_cb.media_alarm = NULL;
928
929 // Exit thread
930 fixed_queue_free(btif_media_cmd_msg_queue, NULL);
931 btif_media_cmd_msg_queue = NULL;
932 thread_post(worker_thread, btif_media_thread_cleanup, NULL);
933 thread_free(worker_thread);
934 worker_thread = NULL;
935 }
936
937 /*****************************************************************************
938 **
939 ** Function btif_a2dp_on_init
940 **
941 ** Description
942 **
943 ** Returns
944 **
945 *******************************************************************************/
946
btif_a2dp_on_init(void)947 void btif_a2dp_on_init(void)
948 {
949 #ifdef USE_AUDIO_TRACK
950 btif_media_cb.rx_audio_focus_state = BTIF_MEDIA_FOCUS_NOT_GRANTED;
951 btif_media_cb.audio_track = NULL;
952 #endif
953 }
954
955
956 /*****************************************************************************
957 **
958 ** Function btif_a2dp_setup_codec
959 **
960 ** Description
961 **
962 ** Returns
963 **
964 *******************************************************************************/
965
btif_a2dp_setup_codec(void)966 void btif_a2dp_setup_codec(void)
967 {
968 tBTIF_AV_MEDIA_FEEDINGS media_feeding;
969 tBTIF_STATUS status;
970
971 APPL_TRACE_EVENT("## A2DP SETUP CODEC ##");
972
973 mutex_global_lock();
974
975 /* for now hardcode 44.1 khz 16 bit stereo PCM format */
976 media_feeding.cfg.pcm.sampling_freq = BTIF_A2DP_SRC_SAMPLING_RATE;
977 media_feeding.cfg.pcm.bit_per_sample = BTIF_A2DP_SRC_BIT_DEPTH;
978 media_feeding.cfg.pcm.num_channel = BTIF_A2DP_SRC_NUM_CHANNELS;
979 media_feeding.format = BTIF_AV_CODEC_PCM;
980
981 if (bta_av_co_audio_set_codec(&media_feeding, &status))
982 {
983 tBTIF_MEDIA_INIT_AUDIO_FEEDING mfeed;
984
985 /* Init the encoding task */
986 btif_a2dp_encoder_init();
987
988 /* Build the media task configuration */
989 mfeed.feeding = media_feeding;
990 mfeed.feeding_mode = BTIF_AV_FEEDING_ASYNCHRONOUS;
991 /* Send message to Media task to configure transcoding */
992 btif_media_task_audio_feeding_init_req(&mfeed);
993 }
994
995 mutex_global_unlock();
996 }
997
998
999 /*****************************************************************************
1000 **
1001 ** Function btif_a2dp_on_idle
1002 **
1003 ** Description
1004 **
1005 ** Returns
1006 **
1007 *******************************************************************************/
1008
btif_a2dp_on_idle(void)1009 void btif_a2dp_on_idle(void)
1010 {
1011 APPL_TRACE_EVENT("## ON A2DP IDLE ## peer_sep = %d", btif_media_cb.peer_sep);
1012 if (btif_media_cb.peer_sep == AVDT_TSEP_SNK)
1013 {
1014 /* Make sure media task is stopped */
1015 btif_media_task_stop_aa_req();
1016 }
1017
1018 bta_av_co_init();
1019 #if (BTA_AV_SINK_INCLUDED == TRUE)
1020 if (btif_media_cb.peer_sep == AVDT_TSEP_SRC)
1021 {
1022 btif_media_cb.rx_flush = TRUE;
1023 btif_media_task_aa_rx_flush_req();
1024 btif_media_task_aa_handle_stop_decoding();
1025 btif_media_task_clear_track();
1026 APPL_TRACE_DEBUG("Stopped BT track");
1027 }
1028 #endif
1029 }
1030
1031 /*****************************************************************************
1032 **
1033 ** Function btif_a2dp_on_open
1034 **
1035 ** Description
1036 **
1037 ** Returns
1038 **
1039 *******************************************************************************/
1040
btif_a2dp_on_open(void)1041 void btif_a2dp_on_open(void)
1042 {
1043 APPL_TRACE_EVENT("## ON A2DP OPEN ##");
1044
1045 /* always use callback to notify socket events */
1046 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
1047 }
1048
1049 /*******************************************************************************
1050 **
1051 ** Function btif_media_task_clear_track
1052 **
1053 ** Description
1054 **
1055 ** Returns TRUE is success
1056 **
1057 *******************************************************************************/
btif_media_task_clear_track(void)1058 BOOLEAN btif_media_task_clear_track(void)
1059 {
1060 BT_HDR *p_buf = osi_malloc(sizeof(BT_HDR));
1061
1062 p_buf->event = BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK;
1063 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1064
1065 return TRUE;
1066 }
1067
1068 /*****************************************************************************
1069 **
1070 ** Function btif_reset_decoder
1071 **
1072 ** Description
1073 **
1074 ** Returns
1075 **
1076 *******************************************************************************/
1077
btif_reset_decoder(UINT8 * p_av)1078 void btif_reset_decoder(UINT8 *p_av)
1079 {
1080 tBTIF_MEDIA_SINK_CFG_UPDATE *p_buf =
1081 osi_malloc(sizeof(tBTIF_MEDIA_SINK_CFG_UPDATE));
1082
1083 APPL_TRACE_EVENT("btif_reset_decoder");
1084 APPL_TRACE_DEBUG("btif_reset_decoder p_codec_info[%x:%x:%x:%x:%x:%x]",
1085 p_av[1], p_av[2], p_av[3],
1086 p_av[4], p_av[5], p_av[6]);
1087
1088 memcpy(p_buf->codec_info,p_av, AVDT_CODEC_SIZE);
1089 p_buf->hdr.event = BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE;
1090
1091 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1092 }
1093
1094 /*****************************************************************************
1095 **
1096 ** Function btif_a2dp_on_started
1097 **
1098 ** Description
1099 **
1100 ** Returns
1101 **
1102 *******************************************************************************/
1103
btif_a2dp_on_started(tBTA_AV_START * p_av,BOOLEAN pending_start)1104 BOOLEAN btif_a2dp_on_started(tBTA_AV_START *p_av, BOOLEAN pending_start)
1105 {
1106 BOOLEAN ack = FALSE;
1107
1108 APPL_TRACE_EVENT("## ON A2DP STARTED ##");
1109
1110 if (p_av == NULL)
1111 {
1112 /* ack back a local start request */
1113 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
1114 return TRUE;
1115 }
1116
1117 if (p_av->status == BTA_AV_SUCCESS)
1118 {
1119 if (p_av->suspending == FALSE)
1120 {
1121 if (p_av->initiator)
1122 {
1123 if (pending_start) {
1124 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
1125 ack = TRUE;
1126 }
1127 }
1128 else
1129 {
1130 /* we were remotely started, make sure codec
1131 is setup before datapath is started */
1132 btif_a2dp_setup_codec();
1133 }
1134
1135 /* media task is autostarted upon a2dp audiopath connection */
1136 }
1137 }
1138 else if (pending_start)
1139 {
1140 APPL_TRACE_WARNING("%s: A2DP start request failed: status = %d",
1141 __func__, p_av->status);
1142 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
1143 ack = TRUE;
1144 }
1145 return ack;
1146 }
1147
1148
1149 /*****************************************************************************
1150 **
1151 ** Function btif_a2dp_ack_fail
1152 **
1153 ** Description
1154 **
1155 ** Returns
1156 **
1157 *******************************************************************************/
1158
btif_a2dp_ack_fail(void)1159 void btif_a2dp_ack_fail(void)
1160 {
1161 APPL_TRACE_EVENT("## A2DP_CTRL_ACK_FAILURE ##");
1162 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
1163 }
1164
1165 /*****************************************************************************
1166 **
1167 ** Function btif_a2dp_on_stopped
1168 **
1169 ** Description
1170 **
1171 ** Returns
1172 **
1173 *******************************************************************************/
1174
btif_a2dp_on_stopped(tBTA_AV_SUSPEND * p_av)1175 void btif_a2dp_on_stopped(tBTA_AV_SUSPEND *p_av)
1176 {
1177 APPL_TRACE_EVENT("## ON A2DP STOPPED ##");
1178 if (btif_media_cb.peer_sep == AVDT_TSEP_SRC) /* Handling for A2DP SINK cases*/
1179 {
1180 btif_media_cb.rx_flush = TRUE;
1181 btif_media_task_aa_rx_flush_req();
1182 btif_media_task_aa_handle_stop_decoding();
1183 #ifndef USE_AUDIO_TRACK
1184 UIPC_Close(UIPC_CH_ID_AV_AUDIO);
1185 #endif
1186 btif_media_cb.data_channel_open = FALSE;
1187 return;
1188 }
1189 /* allow using this api for other than suspend */
1190 if (p_av != NULL)
1191 {
1192 if (p_av->status != BTA_AV_SUCCESS)
1193 {
1194 APPL_TRACE_EVENT("AV STOP FAILED (%d)", p_av->status);
1195
1196 if (p_av->initiator) {
1197 APPL_TRACE_WARNING("%s: A2DP stop request failed: status = %d",
1198 __func__, p_av->status);
1199 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
1200 }
1201 return;
1202 }
1203 }
1204
1205 /* ensure tx frames are immediately suspended */
1206 btif_media_cb.tx_flush = 1;
1207
1208 /* request to stop media task */
1209 btif_media_task_aa_tx_flush_req();
1210 btif_media_task_stop_aa_req();
1211
1212 /* once stream is fully stopped we will ack back */
1213 }
1214
1215
1216 /*****************************************************************************
1217 **
1218 ** Function btif_a2dp_on_suspended
1219 **
1220 ** Description
1221 **
1222 ** Returns
1223 **
1224 *******************************************************************************/
1225
btif_a2dp_on_suspended(tBTA_AV_SUSPEND * p_av)1226 void btif_a2dp_on_suspended(tBTA_AV_SUSPEND *p_av)
1227 {
1228 APPL_TRACE_EVENT("## ON A2DP SUSPENDED ##");
1229 if (btif_media_cb.peer_sep == AVDT_TSEP_SRC)
1230 {
1231 btif_media_cb.rx_flush = TRUE;
1232 btif_media_task_aa_rx_flush_req();
1233 btif_media_task_aa_handle_stop_decoding();
1234 #ifndef USE_AUDIO_TRACK
1235 UIPC_Close(UIPC_CH_ID_AV_AUDIO);
1236 #endif
1237 return;
1238 }
1239
1240 /* check for status failures */
1241 if (p_av->status != BTA_AV_SUCCESS)
1242 {
1243 if (p_av->initiator == TRUE) {
1244 APPL_TRACE_WARNING("%s: A2DP suspend request failed: status = %d",
1245 __func__, p_av->status);
1246 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
1247 }
1248 }
1249
1250 /* once stream is fully stopped we will ack back */
1251
1252 /* ensure tx frames are immediately flushed */
1253 btif_media_cb.tx_flush = 1;
1254
1255 /* stop timer tick */
1256 btif_media_task_stop_aa_req();
1257 }
1258
1259
1260 /*****************************************************************************
1261 **
1262 ** Function btif_a2dp_on_offload_started
1263 **
1264 ** Description
1265 **
1266 ** Returns
1267 **
1268 *******************************************************************************/
btif_a2dp_on_offload_started(tBTA_AV_STATUS status)1269 void btif_a2dp_on_offload_started(tBTA_AV_STATUS status)
1270 {
1271 tA2DP_CTRL_ACK ack;
1272 APPL_TRACE_EVENT("%s status %d", __func__, status);
1273
1274 switch (status) {
1275 case BTA_AV_SUCCESS:
1276 ack = A2DP_CTRL_ACK_SUCCESS;
1277 break;
1278
1279 case BTA_AV_FAIL_RESOURCES:
1280 APPL_TRACE_ERROR("%s FAILED UNSUPPORTED", __func__);
1281 ack = A2DP_CTRL_ACK_UNSUPPORTED;
1282 break;
1283 default:
1284 APPL_TRACE_ERROR("%s FAILED: status = %d", __func__, status);
1285 ack = A2DP_CTRL_ACK_FAILURE;
1286 break;
1287 }
1288 a2dp_cmd_acknowledge(ack);
1289 }
1290
1291 /* when true media task discards any rx frames */
btif_a2dp_set_rx_flush(BOOLEAN enable)1292 void btif_a2dp_set_rx_flush(BOOLEAN enable)
1293 {
1294 APPL_TRACE_EVENT("## DROP RX %d ##", enable);
1295 btif_media_cb.rx_flush = enable;
1296 }
1297
1298 /* when true media task discards any tx frames */
btif_a2dp_set_tx_flush(BOOLEAN enable)1299 void btif_a2dp_set_tx_flush(BOOLEAN enable)
1300 {
1301 APPL_TRACE_EVENT("## DROP TX %d ##", enable);
1302 btif_media_cb.tx_flush = enable;
1303 }
1304
1305 #ifdef USE_AUDIO_TRACK
btif_a2dp_set_audio_focus_state(btif_media_audio_focus_state state)1306 void btif_a2dp_set_audio_focus_state(btif_media_audio_focus_state state)
1307 {
1308 tBTIF_MEDIA_SINK_FOCUS_UPDATE *p_buf =
1309 osi_malloc(sizeof(tBTIF_MEDIA_SINK_FOCUS_UPDATE));
1310
1311 APPL_TRACE_EVENT("%s", __func__);
1312
1313 p_buf->focus_state = state;
1314 p_buf->hdr.event = BTIF_MEDIA_AUDIO_SINK_SET_FOCUS_STATE;
1315 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1316 }
1317
btif_a2dp_set_audio_track_gain(float gain)1318 void btif_a2dp_set_audio_track_gain(float gain)
1319 {
1320 APPL_TRACE_DEBUG("%s set gain to %f", __func__, gain);
1321 BtifAvrcpSetAudioTrackGain(btif_media_cb.audio_track, gain);
1322 }
1323 #endif
1324
1325 #if (BTA_AV_SINK_INCLUDED == TRUE)
btif_media_task_avk_handle_timer(UNUSED_ATTR void * context)1326 static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context)
1327 {
1328 tBT_SBC_HDR *p_msg;
1329 int num_sbc_frames;
1330 int num_frames_to_process;
1331
1332 if (fixed_queue_is_empty(btif_media_cb.RxSbcQ))
1333 {
1334 APPL_TRACE_DEBUG(" QUE EMPTY ");
1335 }
1336 else
1337 {
1338 #ifdef USE_AUDIO_TRACK
1339 /* Don't Do anything in case of Not granted */
1340 if (btif_media_cb.rx_audio_focus_state == BTIF_MEDIA_FOCUS_NOT_GRANTED)
1341 {
1342 APPL_TRACE_DEBUG("%s skipping frames since focus is not present.", __func__);
1343 return;
1344 }
1345 /* play only in BTIF_MEDIA_FOCUS_GRANTED case */
1346 #endif
1347 if (btif_media_cb.rx_flush == TRUE)
1348 {
1349 btif_media_flush_q(btif_media_cb.RxSbcQ);
1350 return;
1351 }
1352
1353 num_frames_to_process = btif_media_cb.frames_to_process;
1354 APPL_TRACE_DEBUG(" Process Frames + ");
1355
1356 do
1357 {
1358 p_msg = (tBT_SBC_HDR *)fixed_queue_try_peek_first(btif_media_cb.RxSbcQ);
1359 if (p_msg == NULL)
1360 return;
1361 num_sbc_frames = p_msg->num_frames_to_be_processed; /* num of frames in Que Packets */
1362 APPL_TRACE_DEBUG(" Frames left in topmost packet %d", num_sbc_frames);
1363 APPL_TRACE_DEBUG(" Remaining frames to process in tick %d", num_frames_to_process);
1364 APPL_TRACE_DEBUG(" Num of Packets in Que %d",
1365 fixed_queue_length(btif_media_cb.RxSbcQ));
1366
1367 if ( num_sbc_frames > num_frames_to_process) /* Que Packet has more frames*/
1368 {
1369 p_msg->num_frames_to_be_processed= num_frames_to_process;
1370 btif_media_task_handle_inc_media(p_msg);
1371 p_msg->num_frames_to_be_processed = num_sbc_frames - num_frames_to_process;
1372 num_frames_to_process = 0;
1373 break;
1374 }
1375 else /* Que packet has less frames */
1376 {
1377 btif_media_task_handle_inc_media(p_msg);
1378 p_msg = (tBT_SBC_HDR *)fixed_queue_try_dequeue(btif_media_cb.RxSbcQ);
1379 if( p_msg == NULL )
1380 {
1381 APPL_TRACE_ERROR("Insufficient data in que ");
1382 break;
1383 }
1384 num_frames_to_process = num_frames_to_process - p_msg->num_frames_to_be_processed;
1385 osi_free(p_msg);
1386 }
1387 } while(num_frames_to_process > 0);
1388
1389 APPL_TRACE_DEBUG(" Process Frames - ");
1390 }
1391 }
1392 #else
btif_media_task_avk_handle_timer(UNUSED_ATTR void * context)1393 static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context) {}
1394 #endif
1395
btif_media_task_aa_handle_timer(UNUSED_ATTR void * context)1396 static void btif_media_task_aa_handle_timer(UNUSED_ATTR void *context)
1397 {
1398 uint64_t timestamp_us = time_now_us();
1399 log_tstamps_us("media task tx timer", timestamp_us);
1400
1401 #if (BTA_AV_INCLUDED == TRUE)
1402 if (alarm_is_scheduled(btif_media_cb.media_alarm))
1403 {
1404 btif_media_send_aa_frame(timestamp_us);
1405 }
1406 else
1407 {
1408 APPL_TRACE_ERROR("ERROR Media task Scheduled after Suspend");
1409 }
1410 #endif
1411 }
1412
1413 #if (BTA_AV_INCLUDED == TRUE)
btif_media_task_aa_handle_uipc_rx_rdy(void)1414 static void btif_media_task_aa_handle_uipc_rx_rdy(void)
1415 {
1416 /* process all the UIPC data */
1417 btif_media_aa_prep_2_send(0xFF, time_now_us());
1418
1419 /* send it */
1420 LOG_VERBOSE(LOG_TAG, "%s calls bta_av_ci_src_data_ready", __func__);
1421 bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
1422 }
1423 #endif
1424
btif_media_thread_init(UNUSED_ATTR void * context)1425 static void btif_media_thread_init(UNUSED_ATTR void *context) {
1426 // Check to make sure the platform has 8 bits/byte since
1427 // we're using that in frame size calculations now.
1428 assert(CHAR_BIT == 8);
1429
1430 memset(&btif_media_cb, 0, sizeof(btif_media_cb));
1431 btif_media_cb.stats.session_start_us = time_now_us();
1432
1433 UIPC_Init(NULL);
1434
1435 #if (BTA_AV_INCLUDED == TRUE)
1436 btif_media_cb.TxAaQ = fixed_queue_new(SIZE_MAX);
1437 btif_media_cb.RxSbcQ = fixed_queue_new(SIZE_MAX);
1438 UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
1439 #endif
1440
1441 raise_priority_a2dp(TASK_HIGH_MEDIA);
1442 media_task_running = MEDIA_TASK_STATE_ON;
1443 }
1444
btif_media_thread_cleanup(UNUSED_ATTR void * context)1445 static void btif_media_thread_cleanup(UNUSED_ATTR void *context) {
1446 /* make sure no channels are restarted while shutting down */
1447 media_task_running = MEDIA_TASK_STATE_SHUTTING_DOWN;
1448
1449 /* this calls blocks until uipc is fully closed */
1450 UIPC_Close(UIPC_CH_ID_ALL);
1451
1452 #if (BTA_AV_INCLUDED == TRUE)
1453 fixed_queue_free(btif_media_cb.TxAaQ, NULL);
1454 btif_media_cb.TxAaQ = NULL;
1455 fixed_queue_free(btif_media_cb.RxSbcQ, NULL);
1456 btif_media_cb.RxSbcQ = NULL;
1457 #endif
1458
1459 /* Clear media task flag */
1460 media_task_running = MEDIA_TASK_STATE_OFF;
1461 }
1462
1463 /*******************************************************************************
1464 **
1465 ** Function btif_media_task_send_cmd_evt
1466 **
1467 ** Description
1468 **
1469 ** Returns TRUE is success
1470 **
1471 *******************************************************************************/
btif_media_task_send_cmd_evt(UINT16 Evt)1472 BOOLEAN btif_media_task_send_cmd_evt(UINT16 Evt)
1473 {
1474 BT_HDR *p_buf = osi_malloc(sizeof(BT_HDR));
1475
1476 p_buf->event = Evt;
1477 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1478
1479 return TRUE;
1480 }
1481
1482 /*******************************************************************************
1483 **
1484 ** Function btif_media_flush_q
1485 **
1486 ** Description
1487 **
1488 ** Returns void
1489 **
1490 *******************************************************************************/
btif_media_flush_q(fixed_queue_t * p_q)1491 static void btif_media_flush_q(fixed_queue_t *p_q)
1492 {
1493 while (! fixed_queue_is_empty(p_q))
1494 {
1495 osi_free(fixed_queue_try_dequeue(p_q));
1496 }
1497 }
1498
btif_media_thread_handle_cmd(fixed_queue_t * queue,UNUSED_ATTR void * context)1499 static void btif_media_thread_handle_cmd(fixed_queue_t *queue, UNUSED_ATTR void *context)
1500 {
1501 BT_HDR *p_msg = (BT_HDR *)fixed_queue_dequeue(queue);
1502 LOG_VERBOSE(LOG_TAG, "btif_media_thread_handle_cmd : %d %s", p_msg->event,
1503 dump_media_event(p_msg->event));
1504
1505 switch (p_msg->event)
1506 {
1507 #if (BTA_AV_INCLUDED == TRUE)
1508 case BTIF_MEDIA_START_AA_TX:
1509 btif_media_task_aa_start_tx();
1510 break;
1511 case BTIF_MEDIA_STOP_AA_TX:
1512 btif_media_task_aa_stop_tx();
1513 break;
1514 case BTIF_MEDIA_SBC_ENC_INIT:
1515 btif_media_task_enc_init(p_msg);
1516 break;
1517 case BTIF_MEDIA_SBC_ENC_UPDATE:
1518 btif_media_task_enc_update(p_msg);
1519 break;
1520 case BTIF_MEDIA_AUDIO_FEEDING_INIT:
1521 btif_media_task_audio_feeding_init(p_msg);
1522 break;
1523 case BTIF_MEDIA_FLUSH_AA_TX:
1524 btif_media_task_aa_tx_flush(p_msg);
1525 break;
1526 case BTIF_MEDIA_UIPC_RX_RDY:
1527 btif_media_task_aa_handle_uipc_rx_rdy();
1528 break;
1529 #ifdef USE_AUDIO_TRACK
1530 case BTIF_MEDIA_AUDIO_SINK_SET_FOCUS_STATE:
1531 if(!btif_av_is_connected())
1532 break;
1533 btif_media_cb.rx_audio_focus_state = ((tBTIF_MEDIA_SINK_FOCUS_UPDATE *)p_msg)->focus_state;
1534 APPL_TRACE_DEBUG("Setting focus state to %d ",btif_media_cb.rx_audio_focus_state);
1535 break;
1536 #endif
1537 case BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE:
1538 #if (BTA_AV_SINK_INCLUDED == TRUE)
1539 btif_media_task_aa_handle_decoder_reset(p_msg);
1540 #endif
1541 break;
1542 case BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK:
1543 #if (BTA_AV_SINK_INCLUDED == TRUE)
1544 btif_media_task_aa_handle_clear_track();
1545 #endif
1546 break;
1547 case BTIF_MEDIA_FLUSH_AA_RX:
1548 btif_media_task_aa_rx_flush();
1549 break;
1550 #endif
1551 default:
1552 APPL_TRACE_ERROR("ERROR in %s unknown event %d", __func__, p_msg->event);
1553 }
1554 osi_free(p_msg);
1555 LOG_VERBOSE(LOG_TAG, "%s: %s DONE", __func__, dump_media_event(p_msg->event));
1556 }
1557
1558 #if (BTA_AV_SINK_INCLUDED == TRUE)
1559 /*******************************************************************************
1560 **
1561 ** Function btif_media_task_handle_inc_media
1562 **
1563 ** Description
1564 **
1565 ** Returns void
1566 **
1567 *******************************************************************************/
btif_media_task_handle_inc_media(tBT_SBC_HDR * p_msg)1568 static void btif_media_task_handle_inc_media(tBT_SBC_HDR*p_msg)
1569 {
1570 UINT8 *sbc_start_frame = ((UINT8*)(p_msg + 1) + p_msg->offset + 1);
1571 int count;
1572 UINT32 pcmBytes, availPcmBytes;
1573 OI_INT16 *pcmDataPointer = pcmData; /*Will be overwritten on next packet receipt*/
1574 OI_STATUS status;
1575 int num_sbc_frames = p_msg->num_frames_to_be_processed;
1576 UINT32 sbc_frame_len = p_msg->len - 1;
1577 availPcmBytes = sizeof(pcmData);
1578
1579 if ((btif_media_cb.peer_sep == AVDT_TSEP_SNK) || (btif_media_cb.rx_flush))
1580 {
1581 APPL_TRACE_DEBUG(" State Changed happened in this tick ");
1582 return;
1583 }
1584 #ifndef USE_AUDIO_TRACK
1585 // ignore data if no one is listening
1586 if (!btif_media_cb.data_channel_open)
1587 {
1588 APPL_TRACE_ERROR("%s Channel not open, returning", __func__);
1589 return;
1590 }
1591 #endif
1592 APPL_TRACE_DEBUG("%s Number of sbc frames %d, frame_len %d",
1593 __func__, num_sbc_frames, sbc_frame_len);
1594
1595 for(count = 0; count < num_sbc_frames && sbc_frame_len != 0; count ++)
1596 {
1597 pcmBytes = availPcmBytes;
1598 status = OI_CODEC_SBC_DecodeFrame(&context, (const OI_BYTE**)&sbc_start_frame,
1599 (OI_UINT32 *)&sbc_frame_len,
1600 (OI_INT16 *)pcmDataPointer,
1601 (OI_UINT32 *)&pcmBytes);
1602 if (!OI_SUCCESS(status)) {
1603 APPL_TRACE_ERROR("Decoding failure: %d\n", status);
1604 break;
1605 }
1606 availPcmBytes -= pcmBytes;
1607 pcmDataPointer += pcmBytes/2;
1608 p_msg->offset += (p_msg->len - 1) - sbc_frame_len;
1609 p_msg->len = sbc_frame_len + 1;
1610 }
1611
1612 #ifdef USE_AUDIO_TRACK
1613 BtifAvrcpAudioTrackWriteData(
1614 btif_media_cb.audio_track, (void*)pcmData, (sizeof(pcmData) - availPcmBytes));
1615 #else
1616 UIPC_Send(UIPC_CH_ID_AV_AUDIO, 0, (UINT8 *)pcmData, (sizeof(pcmData) - availPcmBytes));
1617 #endif
1618 }
1619 #endif
1620
1621 #if (BTA_AV_INCLUDED == TRUE)
1622 /*******************************************************************************
1623 **
1624 ** Function btif_media_task_enc_init_req
1625 **
1626 ** Description
1627 **
1628 ** Returns TRUE is success
1629 **
1630 *******************************************************************************/
btif_media_task_enc_init_req(tBTIF_MEDIA_INIT_AUDIO * p_msg)1631 BOOLEAN btif_media_task_enc_init_req(tBTIF_MEDIA_INIT_AUDIO *p_msg)
1632 {
1633 tBTIF_MEDIA_INIT_AUDIO *p_buf = osi_malloc(sizeof(tBTIF_MEDIA_INIT_AUDIO));
1634
1635 memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO));
1636 p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_INIT;
1637 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1638
1639 return TRUE;
1640 }
1641
1642 /*******************************************************************************
1643 **
1644 ** Function btif_media_task_enc_update_req
1645 **
1646 ** Description
1647 **
1648 ** Returns TRUE is success
1649 **
1650 *******************************************************************************/
btif_media_task_enc_update_req(tBTIF_MEDIA_UPDATE_AUDIO * p_msg)1651 BOOLEAN btif_media_task_enc_update_req(tBTIF_MEDIA_UPDATE_AUDIO *p_msg)
1652 {
1653 tBTIF_MEDIA_UPDATE_AUDIO *p_buf =
1654 osi_malloc(sizeof(tBTIF_MEDIA_UPDATE_AUDIO));
1655
1656 memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_UPDATE_AUDIO));
1657 p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_UPDATE;
1658 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1659
1660 return TRUE;
1661 }
1662
1663 /*******************************************************************************
1664 **
1665 ** Function btif_media_task_audio_feeding_init_req
1666 **
1667 ** Description
1668 **
1669 ** Returns TRUE is success
1670 **
1671 *******************************************************************************/
btif_media_task_audio_feeding_init_req(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_msg)1672 BOOLEAN btif_media_task_audio_feeding_init_req(tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_msg)
1673 {
1674 tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_buf =
1675 osi_malloc(sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING));
1676
1677 memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING));
1678 p_buf->hdr.event = BTIF_MEDIA_AUDIO_FEEDING_INIT;
1679 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1680
1681 return TRUE;
1682 }
1683
1684 /*******************************************************************************
1685 **
1686 ** Function btif_media_task_start_aa_req
1687 **
1688 ** Description
1689 **
1690 ** Returns TRUE is success
1691 **
1692 *******************************************************************************/
btif_media_task_start_aa_req(void)1693 BOOLEAN btif_media_task_start_aa_req(void)
1694 {
1695 BT_HDR *p_buf = osi_malloc(sizeof(BT_HDR));
1696
1697 p_buf->event = BTIF_MEDIA_START_AA_TX;
1698 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1699
1700 return TRUE;
1701 }
1702
1703 /*******************************************************************************
1704 **
1705 ** Function btif_media_task_stop_aa_req
1706 **
1707 ** Description
1708 **
1709 ** Returns TRUE is success
1710 **
1711 *******************************************************************************/
btif_media_task_stop_aa_req(void)1712 BOOLEAN btif_media_task_stop_aa_req(void)
1713 {
1714 BT_HDR *p_buf = osi_malloc(sizeof(BT_HDR));
1715
1716 p_buf->event = BTIF_MEDIA_STOP_AA_TX;
1717
1718 /*
1719 * Explicitly check whether the btif_media_cmd_msg_queue is not NULL to
1720 * avoid a race condition during shutdown of the Bluetooth stack.
1721 * This race condition is triggered when A2DP audio is streaming on
1722 * shutdown:
1723 * "btif_a2dp_on_stopped() -> btif_media_task_stop_aa_req()" is called
1724 * to stop the particular audio stream, and this happens right after
1725 * the "cleanup() -> btif_a2dp_stop_media_task()" processing during
1726 * the shutdown of the Bluetooth stack.
1727 */
1728 if (btif_media_cmd_msg_queue != NULL)
1729 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1730
1731 return TRUE;
1732 }
1733 /*******************************************************************************
1734 **
1735 ** Function btif_media_task_aa_rx_flush_req
1736 **
1737 ** Description
1738 **
1739 ** Returns TRUE is success
1740 **
1741 *******************************************************************************/
btif_media_task_aa_rx_flush_req(void)1742 BOOLEAN btif_media_task_aa_rx_flush_req(void)
1743 {
1744 if (fixed_queue_is_empty(btif_media_cb.RxSbcQ)) /* Que is already empty */
1745 return TRUE;
1746
1747 BT_HDR *p_buf = osi_malloc(sizeof(BT_HDR));
1748 p_buf->event = BTIF_MEDIA_FLUSH_AA_RX;
1749 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1750
1751 return TRUE;
1752 }
1753
1754 /*******************************************************************************
1755 **
1756 ** Function btif_media_task_aa_tx_flush_req
1757 **
1758 ** Description
1759 **
1760 ** Returns TRUE is success
1761 **
1762 *******************************************************************************/
btif_media_task_aa_tx_flush_req(void)1763 BOOLEAN btif_media_task_aa_tx_flush_req(void)
1764 {
1765 BT_HDR *p_buf = osi_malloc(sizeof(BT_HDR));
1766
1767 p_buf->event = BTIF_MEDIA_FLUSH_AA_TX;
1768
1769 /*
1770 * Explicitly check whether the btif_media_cmd_msg_queue is not NULL to
1771 * avoid a race condition during shutdown of the Bluetooth stack.
1772 * This race condition is triggered when A2DP audio is streaming on
1773 * shutdown:
1774 * "btif_a2dp_on_stopped() -> btif_media_task_aa_tx_flush_req()" is called
1775 * to stop the particular audio stream, and this happens right after
1776 * the "cleanup() -> btif_a2dp_stop_media_task()" processing during
1777 * the shutdown of the Bluetooth stack.
1778 */
1779 if (btif_media_cmd_msg_queue != NULL)
1780 fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1781
1782 return TRUE;
1783 }
1784 /*******************************************************************************
1785 **
1786 ** Function btif_media_task_aa_rx_flush
1787 **
1788 ** Description
1789 **
1790 ** Returns void
1791 **
1792 *******************************************************************************/
btif_media_task_aa_rx_flush(void)1793 static void btif_media_task_aa_rx_flush(void)
1794 {
1795 /* Flush all enqueued GKI SBC buffers (encoded) */
1796 APPL_TRACE_DEBUG("btif_media_task_aa_rx_flush");
1797
1798 btif_media_flush_q(btif_media_cb.RxSbcQ);
1799 }
1800
1801
1802 /*******************************************************************************
1803 **
1804 ** Function btif_media_task_aa_tx_flush
1805 **
1806 ** Description
1807 **
1808 ** Returns void
1809 **
1810 *******************************************************************************/
btif_media_task_aa_tx_flush(BT_HDR * p_msg)1811 static void btif_media_task_aa_tx_flush(BT_HDR *p_msg)
1812 {
1813 UNUSED(p_msg);
1814
1815 /* Flush all enqueued GKI music buffers (encoded) */
1816 APPL_TRACE_DEBUG("btif_media_task_aa_tx_flush");
1817
1818 btif_media_cb.media_feeding_state.pcm.counter = 0;
1819 btif_media_cb.media_feeding_state.pcm.aa_feed_residue = 0;
1820
1821 btif_media_cb.stats.tx_queue_total_flushed_messages +=
1822 fixed_queue_length(btif_media_cb.TxAaQ);
1823 btif_media_cb.stats.tx_queue_last_flushed_us = time_now_us();
1824 btif_media_flush_q(btif_media_cb.TxAaQ);
1825
1826 UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REQ_RX_FLUSH, NULL);
1827 }
1828
1829 /*******************************************************************************
1830 **
1831 ** Function btif_media_task_enc_init
1832 **
1833 ** Description Initialize encoding task
1834 **
1835 ** Returns void
1836 **
1837 *******************************************************************************/
btif_media_task_enc_init(BT_HDR * p_msg)1838 static void btif_media_task_enc_init(BT_HDR *p_msg)
1839 {
1840 tBTIF_MEDIA_INIT_AUDIO *pInitAudio = (tBTIF_MEDIA_INIT_AUDIO *) p_msg;
1841
1842 APPL_TRACE_DEBUG("btif_media_task_enc_init");
1843
1844 btif_media_cb.timestamp = 0;
1845
1846 /* SBC encoder config (enforced even if not used) */
1847 btif_media_cb.encoder.s16ChannelMode = pInitAudio->ChannelMode;
1848 btif_media_cb.encoder.s16NumOfSubBands = pInitAudio->NumOfSubBands;
1849 btif_media_cb.encoder.s16NumOfBlocks = pInitAudio->NumOfBlocks;
1850 btif_media_cb.encoder.s16AllocationMethod = pInitAudio->AllocationMethod;
1851 btif_media_cb.encoder.s16SamplingFreq = pInitAudio->SamplingFreq;
1852
1853 btif_media_cb.encoder.u16BitRate = btif_media_task_get_sbc_rate();
1854
1855 /* Default transcoding is PCM to SBC, modified by feeding configuration */
1856 btif_media_cb.TxTranscoding = BTIF_MEDIA_TRSCD_PCM_2_SBC;
1857 btif_media_cb.TxAaMtuSize = ((BTIF_MEDIA_AA_BUF_SIZE-BTIF_MEDIA_AA_SBC_OFFSET-sizeof(BT_HDR))
1858 < pInitAudio->MtuSize) ? (BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET
1859 - sizeof(BT_HDR)) : pInitAudio->MtuSize;
1860
1861 APPL_TRACE_EVENT("btif_media_task_enc_init busy %d, mtu %d, peer mtu %d",
1862 btif_media_cb.busy_level, btif_media_cb.TxAaMtuSize, pInitAudio->MtuSize);
1863 APPL_TRACE_EVENT(" ch mode %d, subnd %d, nb blk %d, alloc %d, rate %d, freq %d",
1864 btif_media_cb.encoder.s16ChannelMode, btif_media_cb.encoder.s16NumOfSubBands,
1865 btif_media_cb.encoder.s16NumOfBlocks,
1866 btif_media_cb.encoder.s16AllocationMethod, btif_media_cb.encoder.u16BitRate,
1867 btif_media_cb.encoder.s16SamplingFreq);
1868
1869 /* Reset entirely the SBC encoder */
1870 SBC_Encoder_Init(&(btif_media_cb.encoder));
1871
1872 btif_media_cb.tx_sbc_frames = calculate_max_frames_per_packet();
1873
1874 APPL_TRACE_DEBUG("%s bit pool %d", __func__, btif_media_cb.encoder.s16BitPool);
1875 }
1876
1877 /*******************************************************************************
1878 **
1879 ** Function btif_media_task_enc_update
1880 **
1881 ** Description Update encoding task
1882 **
1883 ** Returns void
1884 **
1885 *******************************************************************************/
1886
btif_media_task_enc_update(BT_HDR * p_msg)1887 static void btif_media_task_enc_update(BT_HDR *p_msg)
1888 {
1889 tBTIF_MEDIA_UPDATE_AUDIO * pUpdateAudio = (tBTIF_MEDIA_UPDATE_AUDIO *) p_msg;
1890 SBC_ENC_PARAMS *pstrEncParams = &btif_media_cb.encoder;
1891 UINT16 s16SamplingFreq;
1892 SINT16 s16BitPool = 0;
1893 SINT16 s16BitRate;
1894 SINT16 s16FrameLen;
1895 UINT8 protect = 0;
1896
1897 APPL_TRACE_DEBUG("%s : minmtu %d, maxbp %d minbp %d", __func__,
1898 pUpdateAudio->MinMtuSize, pUpdateAudio->MaxBitPool,
1899 pUpdateAudio->MinBitPool);
1900
1901 if (!pstrEncParams->s16NumOfSubBands)
1902 {
1903 APPL_TRACE_WARNING("%s SubBands are set to 0, resetting to max (%d)",
1904 __func__, SBC_MAX_NUM_OF_SUBBANDS);
1905 pstrEncParams->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS;
1906 }
1907
1908 if (!pstrEncParams->s16NumOfBlocks)
1909 {
1910 APPL_TRACE_WARNING("%s Blocks are set to 0, resetting to max (%d)",
1911 __func__, SBC_MAX_NUM_OF_BLOCKS);
1912 pstrEncParams->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS;
1913 }
1914
1915 if (!pstrEncParams->s16NumOfChannels)
1916 {
1917 APPL_TRACE_WARNING("%s Channels are set to 0, resetting to max (%d)",
1918 __func__, SBC_MAX_NUM_OF_CHANNELS);
1919 pstrEncParams->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS;
1920 }
1921
1922 btif_media_cb.TxAaMtuSize = ((BTIF_MEDIA_AA_BUF_SIZE -
1923 BTIF_MEDIA_AA_SBC_OFFSET - sizeof(BT_HDR))
1924 < pUpdateAudio->MinMtuSize) ? (BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET
1925 - sizeof(BT_HDR)) : pUpdateAudio->MinMtuSize;
1926
1927 /* Set the initial target bit rate */
1928 pstrEncParams->u16BitRate = btif_media_task_get_sbc_rate();
1929
1930 if (pstrEncParams->s16SamplingFreq == SBC_sf16000)
1931 s16SamplingFreq = 16000;
1932 else if (pstrEncParams->s16SamplingFreq == SBC_sf32000)
1933 s16SamplingFreq = 32000;
1934 else if (pstrEncParams->s16SamplingFreq == SBC_sf44100)
1935 s16SamplingFreq = 44100;
1936 else
1937 s16SamplingFreq = 48000;
1938
1939 do {
1940 if (pstrEncParams->s16NumOfBlocks == 0 ||
1941 pstrEncParams->s16NumOfSubBands == 0 ||
1942 pstrEncParams->s16NumOfChannels == 0) {
1943 APPL_TRACE_ERROR("%s - Avoiding division by zero...", __func__);
1944 APPL_TRACE_ERROR("%s - block=%d, subBands=%d, channels=%d",
1945 __func__,
1946 pstrEncParams->s16NumOfBlocks,
1947 pstrEncParams->s16NumOfSubBands,
1948 pstrEncParams->s16NumOfChannels);
1949 break;
1950 }
1951
1952 if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) ||
1953 (pstrEncParams->s16ChannelMode == SBC_STEREO)) {
1954 s16BitPool = (SINT16)((pstrEncParams->u16BitRate *
1955 pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq)
1956 - ((32 + (4 * pstrEncParams->s16NumOfSubBands *
1957 pstrEncParams->s16NumOfChannels)
1958 + ((pstrEncParams->s16ChannelMode - 2) *
1959 pstrEncParams->s16NumOfSubBands))
1960 / pstrEncParams->s16NumOfBlocks));
1961
1962 s16FrameLen = 4 + (4*pstrEncParams->s16NumOfSubBands *
1963 pstrEncParams->s16NumOfChannels) / 8
1964 + (((pstrEncParams->s16ChannelMode - 2) *
1965 pstrEncParams->s16NumOfSubBands)
1966 + (pstrEncParams->s16NumOfBlocks * s16BitPool)) / 8;
1967
1968 s16BitRate = (8 * s16FrameLen * s16SamplingFreq)
1969 / (pstrEncParams->s16NumOfSubBands *
1970 pstrEncParams->s16NumOfBlocks * 1000);
1971
1972 if (s16BitRate > pstrEncParams->u16BitRate)
1973 s16BitPool--;
1974
1975 if (pstrEncParams->s16NumOfSubBands == 8)
1976 s16BitPool = (s16BitPool > 255) ? 255 : s16BitPool;
1977 else
1978 s16BitPool = (s16BitPool > 128) ? 128 : s16BitPool;
1979 } else {
1980 s16BitPool = (SINT16)(((pstrEncParams->s16NumOfSubBands *
1981 pstrEncParams->u16BitRate * 1000)
1982 / (s16SamplingFreq * pstrEncParams->s16NumOfChannels))
1983 - (((32 / pstrEncParams->s16NumOfChannels) +
1984 (4 * pstrEncParams->s16NumOfSubBands))
1985 / pstrEncParams->s16NumOfBlocks));
1986
1987 pstrEncParams->s16BitPool =
1988 (s16BitPool > (16 * pstrEncParams->s16NumOfSubBands)) ?
1989 (16 * pstrEncParams->s16NumOfSubBands) : s16BitPool;
1990 }
1991
1992 if (s16BitPool < 0)
1993 s16BitPool = 0;
1994
1995 APPL_TRACE_EVENT("%s bitpool candidate : %d (%d kbps)", __func__,
1996 s16BitPool, pstrEncParams->u16BitRate);
1997
1998 if (s16BitPool > pUpdateAudio->MaxBitPool) {
1999 APPL_TRACE_DEBUG("%s computed bitpool too large (%d)", __func__,
2000 s16BitPool);
2001 /* Decrease bitrate */
2002 btif_media_cb.encoder.u16BitRate -= BTIF_MEDIA_BITRATE_STEP;
2003 /* Record that we have decreased the bitrate */
2004 protect |= 1;
2005 } else if (s16BitPool < pUpdateAudio->MinBitPool) {
2006 APPL_TRACE_WARNING("%s computed bitpool too small (%d)", __func__,
2007 s16BitPool);
2008
2009 /* Increase bitrate */
2010 UINT16 previous_u16BitRate = btif_media_cb.encoder.u16BitRate;
2011 btif_media_cb.encoder.u16BitRate += BTIF_MEDIA_BITRATE_STEP;
2012 /* Record that we have increased the bitrate */
2013 protect |= 2;
2014 /* Check over-flow */
2015 if (btif_media_cb.encoder.u16BitRate < previous_u16BitRate)
2016 protect |= 3;
2017 } else {
2018 break;
2019 }
2020 /* In case we have already increased and decreased the bitrate, just stop */
2021 if (protect == 3) {
2022 APPL_TRACE_ERROR("%s could not find bitpool in range", __func__);
2023 break;
2024 }
2025 } while (1);
2026
2027 /* Finally update the bitpool in the encoder structure */
2028 pstrEncParams->s16BitPool = s16BitPool;
2029
2030 APPL_TRACE_DEBUG("%s final bit rate %d, final bit pool %d", __func__,
2031 btif_media_cb.encoder.u16BitRate,
2032 btif_media_cb.encoder.s16BitPool);
2033
2034 /* make sure we reinitialize encoder with new settings */
2035 SBC_Encoder_Init(&(btif_media_cb.encoder));
2036
2037 btif_media_cb.tx_sbc_frames = calculate_max_frames_per_packet();
2038 }
2039
2040 /*******************************************************************************
2041 **
2042 ** Function btif_media_task_pcm2sbc_init
2043 **
2044 ** Description Init encoding task for PCM to SBC according to feeding
2045 **
2046 ** Returns void
2047 **
2048 *******************************************************************************/
btif_media_task_pcm2sbc_init(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_feeding)2049 static void btif_media_task_pcm2sbc_init(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_feeding)
2050 {
2051 BOOLEAN reconfig_needed = FALSE;
2052
2053 APPL_TRACE_DEBUG("PCM feeding:");
2054 APPL_TRACE_DEBUG("sampling_freq:%d", p_feeding->feeding.cfg.pcm.sampling_freq);
2055 APPL_TRACE_DEBUG("num_channel:%d", p_feeding->feeding.cfg.pcm.num_channel);
2056 APPL_TRACE_DEBUG("bit_per_sample:%d", p_feeding->feeding.cfg.pcm.bit_per_sample);
2057
2058 /* Check the PCM feeding sampling_freq */
2059 switch (p_feeding->feeding.cfg.pcm.sampling_freq)
2060 {
2061 case 8000:
2062 case 12000:
2063 case 16000:
2064 case 24000:
2065 case 32000:
2066 case 48000:
2067 /* For these sampling_freq the AV connection must be 48000 */
2068 if (btif_media_cb.encoder.s16SamplingFreq != SBC_sf48000)
2069 {
2070 /* Reconfiguration needed at 48000 */
2071 APPL_TRACE_DEBUG("SBC Reconfiguration needed at 48000");
2072 btif_media_cb.encoder.s16SamplingFreq = SBC_sf48000;
2073 reconfig_needed = TRUE;
2074 }
2075 break;
2076
2077 case 11025:
2078 case 22050:
2079 case 44100:
2080 /* For these sampling_freq the AV connection must be 44100 */
2081 if (btif_media_cb.encoder.s16SamplingFreq != SBC_sf44100)
2082 {
2083 /* Reconfiguration needed at 44100 */
2084 APPL_TRACE_DEBUG("SBC Reconfiguration needed at 44100");
2085 btif_media_cb.encoder.s16SamplingFreq = SBC_sf44100;
2086 reconfig_needed = TRUE;
2087 }
2088 break;
2089 default:
2090 APPL_TRACE_DEBUG("Feeding PCM sampling_freq unsupported");
2091 break;
2092 }
2093
2094 /* Some AV Headsets do not support Mono => always ask for Stereo */
2095 if (btif_media_cb.encoder.s16ChannelMode == SBC_MONO)
2096 {
2097 APPL_TRACE_DEBUG("SBC Reconfiguration needed in Stereo");
2098 btif_media_cb.encoder.s16ChannelMode = SBC_JOINT_STEREO;
2099 reconfig_needed = TRUE;
2100 }
2101
2102 if (reconfig_needed != FALSE)
2103 {
2104 APPL_TRACE_DEBUG("btif_media_task_pcm2sbc_init :: mtu %d", btif_media_cb.TxAaMtuSize);
2105 APPL_TRACE_DEBUG("ch mode %d, nbsubd %d, nb %d, alloc %d, rate %d, freq %d",
2106 btif_media_cb.encoder.s16ChannelMode,
2107 btif_media_cb.encoder.s16NumOfSubBands, btif_media_cb.encoder.s16NumOfBlocks,
2108 btif_media_cb.encoder.s16AllocationMethod, btif_media_cb.encoder.u16BitRate,
2109 btif_media_cb.encoder.s16SamplingFreq);
2110
2111 SBC_Encoder_Init(&(btif_media_cb.encoder));
2112 }
2113 else
2114 {
2115 APPL_TRACE_DEBUG("btif_media_task_pcm2sbc_init no SBC reconfig needed");
2116 }
2117 }
2118
2119
2120 /*******************************************************************************
2121 **
2122 ** Function btif_media_task_audio_feeding_init
2123 **
2124 ** Description Initialize the audio path according to the feeding format
2125 **
2126 ** Returns void
2127 **
2128 *******************************************************************************/
btif_media_task_audio_feeding_init(BT_HDR * p_msg)2129 static void btif_media_task_audio_feeding_init(BT_HDR *p_msg)
2130 {
2131 tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_feeding = (tBTIF_MEDIA_INIT_AUDIO_FEEDING *) p_msg;
2132
2133 APPL_TRACE_DEBUG("btif_media_task_audio_feeding_init format:%d", p_feeding->feeding.format);
2134
2135 /* Save Media Feeding information */
2136 btif_media_cb.feeding_mode = p_feeding->feeding_mode;
2137 btif_media_cb.media_feeding = p_feeding->feeding;
2138
2139 /* Handle different feeding formats */
2140 switch (p_feeding->feeding.format)
2141 {
2142 case BTIF_AV_CODEC_PCM:
2143 btif_media_cb.TxTranscoding = BTIF_MEDIA_TRSCD_PCM_2_SBC;
2144 btif_media_task_pcm2sbc_init(p_feeding);
2145 break;
2146
2147 default :
2148 APPL_TRACE_ERROR("unknown feeding format %d", p_feeding->feeding.format);
2149 break;
2150 }
2151 }
2152
btif_a2dp_get_track_frequency(UINT8 frequency)2153 int btif_a2dp_get_track_frequency(UINT8 frequency) {
2154 int freq = 48000;
2155 switch (frequency) {
2156 case A2D_SBC_IE_SAMP_FREQ_16:
2157 freq = 16000;
2158 break;
2159 case A2D_SBC_IE_SAMP_FREQ_32:
2160 freq = 32000;
2161 break;
2162 case A2D_SBC_IE_SAMP_FREQ_44:
2163 freq = 44100;
2164 break;
2165 case A2D_SBC_IE_SAMP_FREQ_48:
2166 freq = 48000;
2167 break;
2168 }
2169 return freq;
2170 }
2171
btif_a2dp_get_track_channel_count(UINT8 channeltype)2172 int btif_a2dp_get_track_channel_count(UINT8 channeltype) {
2173 int count = 1;
2174 switch (channeltype) {
2175 case A2D_SBC_IE_CH_MD_MONO:
2176 count = 1;
2177 break;
2178 case A2D_SBC_IE_CH_MD_DUAL:
2179 case A2D_SBC_IE_CH_MD_STEREO:
2180 case A2D_SBC_IE_CH_MD_JOINT:
2181 count = 2;
2182 break;
2183 }
2184 return count;
2185 }
2186
2187 #ifdef USE_AUDIO_TRACK
a2dp_get_track_channel_type(UINT8 channeltype)2188 int a2dp_get_track_channel_type(UINT8 channeltype) {
2189 int count = 1;
2190 switch (channeltype) {
2191 case A2D_SBC_IE_CH_MD_MONO:
2192 count = 1;
2193 break;
2194 case A2D_SBC_IE_CH_MD_DUAL:
2195 case A2D_SBC_IE_CH_MD_STEREO:
2196 case A2D_SBC_IE_CH_MD_JOINT:
2197 count = 3;
2198 break;
2199 }
2200 return count;
2201 }
2202 #endif
2203
btif_a2dp_set_peer_sep(UINT8 sep)2204 void btif_a2dp_set_peer_sep(UINT8 sep) {
2205 btif_media_cb.peer_sep = sep;
2206 }
2207
btif_decode_alarm_cb(UNUSED_ATTR void * context)2208 static void btif_decode_alarm_cb(UNUSED_ATTR void *context) {
2209 if(worker_thread != NULL)
2210 thread_post(worker_thread, btif_media_task_avk_handle_timer, NULL);
2211 }
2212
btif_media_task_aa_handle_stop_decoding(void)2213 static void btif_media_task_aa_handle_stop_decoding(void) {
2214 alarm_free(btif_media_cb.decode_alarm);
2215 btif_media_cb.decode_alarm = NULL;
2216 #ifdef USE_AUDIO_TRACK
2217 BtifAvrcpAudioTrackPause(btif_media_cb.audio_track);
2218 #endif
2219 }
2220
btif_media_task_aa_handle_start_decoding(void)2221 static void btif_media_task_aa_handle_start_decoding(void) {
2222 if (btif_media_cb.decode_alarm)
2223 return;
2224 #ifdef USE_AUDIO_TRACK
2225 BtifAvrcpAudioTrackStart(btif_media_cb.audio_track);
2226 #endif
2227 btif_media_cb.decode_alarm = alarm_new_periodic("btif.media_decode");
2228 if (!btif_media_cb.decode_alarm) {
2229 LOG_ERROR(LOG_TAG, "%s unable to allocate decode alarm.", __func__);
2230 return;
2231 }
2232
2233 alarm_set(btif_media_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK_MS,
2234 btif_decode_alarm_cb, NULL);
2235 }
2236
2237 #if (BTA_AV_SINK_INCLUDED == TRUE)
2238
btif_media_task_aa_handle_clear_track(void)2239 static void btif_media_task_aa_handle_clear_track (void)
2240 {
2241 APPL_TRACE_DEBUG("btif_media_task_aa_handle_clear_track");
2242 #ifdef USE_AUDIO_TRACK
2243 BtifAvrcpAudioTrackStop(btif_media_cb.audio_track);
2244 BtifAvrcpAudioTrackDelete(btif_media_cb.audio_track);
2245 btif_media_cb.audio_track = NULL;
2246 #endif
2247 }
2248
2249 /*******************************************************************************
2250 **
2251 ** Function btif_media_task_aa_handle_decoder_reset
2252 **
2253 ** Description
2254 **
2255 ** Returns void
2256 **
2257 *******************************************************************************/
btif_media_task_aa_handle_decoder_reset(BT_HDR * p_msg)2258 static void btif_media_task_aa_handle_decoder_reset(BT_HDR *p_msg)
2259 {
2260 tBTIF_MEDIA_SINK_CFG_UPDATE *p_buf = (tBTIF_MEDIA_SINK_CFG_UPDATE*) p_msg;
2261 tA2D_STATUS a2d_status;
2262 tA2D_SBC_CIE sbc_cie;
2263 OI_STATUS status;
2264 UINT32 freq_multiple = 48*20; /* frequency multiple for 20ms of data , initialize with 48K*/
2265 UINT32 num_blocks = 16;
2266 UINT32 num_subbands = 8;
2267
2268 APPL_TRACE_DEBUG("btif_media_task_aa_handle_decoder_reset p_codec_info[%x:%x:%x:%x:%x:%x]",
2269 p_buf->codec_info[1], p_buf->codec_info[2], p_buf->codec_info[3],
2270 p_buf->codec_info[4], p_buf->codec_info[5], p_buf->codec_info[6]);
2271
2272 a2d_status = A2D_ParsSbcInfo(&sbc_cie, p_buf->codec_info, FALSE);
2273 if (a2d_status != A2D_SUCCESS)
2274 {
2275 APPL_TRACE_ERROR("ERROR dump_codec_info A2D_ParsSbcInfo fail:%d", a2d_status);
2276 return;
2277 }
2278
2279 btif_media_cb.sample_rate = btif_a2dp_get_track_frequency(sbc_cie.samp_freq);
2280 btif_media_cb.channel_count = btif_a2dp_get_track_channel_count(sbc_cie.ch_mode);
2281
2282 btif_media_cb.rx_flush = FALSE;
2283 APPL_TRACE_DEBUG("Reset to sink role");
2284 status = OI_CODEC_SBC_DecoderReset(&context, contextData, sizeof(contextData), 2, 2, FALSE);
2285 if (!OI_SUCCESS(status)) {
2286 APPL_TRACE_ERROR("OI_CODEC_SBC_DecoderReset failed with error code %d\n", status);
2287 }
2288
2289 #ifdef USE_AUDIO_TRACK
2290 APPL_TRACE_DEBUG("%s A2dpSink: sbc Create Track", __func__);
2291 btif_media_cb.audio_track =
2292 BtifAvrcpAudioTrackCreate(btif_a2dp_get_track_frequency(sbc_cie.samp_freq),
2293 a2dp_get_track_channel_type(sbc_cie.ch_mode));
2294 if (btif_media_cb.audio_track == NULL) {
2295 APPL_TRACE_ERROR("%s A2dpSink: Track creation fails!!!", __func__);
2296 return;
2297 }
2298 #else
2299 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
2300 #endif
2301
2302 switch (sbc_cie.samp_freq)
2303 {
2304 case A2D_SBC_IE_SAMP_FREQ_16:
2305 APPL_TRACE_DEBUG("\tsamp_freq:%d (16000)", sbc_cie.samp_freq);
2306 freq_multiple = 16*20;
2307 break;
2308 case A2D_SBC_IE_SAMP_FREQ_32:
2309 APPL_TRACE_DEBUG("\tsamp_freq:%d (32000)", sbc_cie.samp_freq);
2310 freq_multiple = 32*20;
2311 break;
2312 case A2D_SBC_IE_SAMP_FREQ_44:
2313 APPL_TRACE_DEBUG("\tsamp_freq:%d (44100)", sbc_cie.samp_freq);
2314 freq_multiple = 441*2;
2315 break;
2316 case A2D_SBC_IE_SAMP_FREQ_48:
2317 APPL_TRACE_DEBUG("\tsamp_freq:%d (48000)", sbc_cie.samp_freq);
2318 freq_multiple = 48*20;
2319 break;
2320 default:
2321 APPL_TRACE_DEBUG(" Unknown Frequency ");
2322 break;
2323 }
2324
2325 switch (sbc_cie.ch_mode)
2326 {
2327 case A2D_SBC_IE_CH_MD_MONO:
2328 APPL_TRACE_DEBUG("\tch_mode:%d (Mono)", sbc_cie.ch_mode);
2329 break;
2330 case A2D_SBC_IE_CH_MD_DUAL:
2331 APPL_TRACE_DEBUG("\tch_mode:%d (DUAL)", sbc_cie.ch_mode);
2332 break;
2333 case A2D_SBC_IE_CH_MD_STEREO:
2334 APPL_TRACE_DEBUG("\tch_mode:%d (STEREO)", sbc_cie.ch_mode);
2335 break;
2336 case A2D_SBC_IE_CH_MD_JOINT:
2337 APPL_TRACE_DEBUG("\tch_mode:%d (JOINT)", sbc_cie.ch_mode);
2338 break;
2339 default:
2340 APPL_TRACE_DEBUG(" Unknown Mode ");
2341 break;
2342 }
2343
2344 switch (sbc_cie.block_len)
2345 {
2346 case A2D_SBC_IE_BLOCKS_4:
2347 APPL_TRACE_DEBUG("\tblock_len:%d (4)", sbc_cie.block_len);
2348 num_blocks = 4;
2349 break;
2350 case A2D_SBC_IE_BLOCKS_8:
2351 APPL_TRACE_DEBUG("\tblock_len:%d (8)", sbc_cie.block_len);
2352 num_blocks = 8;
2353 break;
2354 case A2D_SBC_IE_BLOCKS_12:
2355 APPL_TRACE_DEBUG("\tblock_len:%d (12)", sbc_cie.block_len);
2356 num_blocks = 12;
2357 break;
2358 case A2D_SBC_IE_BLOCKS_16:
2359 APPL_TRACE_DEBUG("\tblock_len:%d (16)", sbc_cie.block_len);
2360 num_blocks = 16;
2361 break;
2362 default:
2363 APPL_TRACE_DEBUG(" Unknown BlockLen ");
2364 break;
2365 }
2366
2367 switch (sbc_cie.num_subbands)
2368 {
2369 case A2D_SBC_IE_SUBBAND_4:
2370 APPL_TRACE_DEBUG("\tnum_subbands:%d (4)", sbc_cie.num_subbands);
2371 num_subbands = 4;
2372 break;
2373 case A2D_SBC_IE_SUBBAND_8:
2374 APPL_TRACE_DEBUG("\tnum_subbands:%d (8)", sbc_cie.num_subbands);
2375 num_subbands = 8;
2376 break;
2377 default:
2378 APPL_TRACE_DEBUG(" Unknown SubBands ");
2379 break;
2380 }
2381
2382 switch (sbc_cie.alloc_mthd)
2383 {
2384 case A2D_SBC_IE_ALLOC_MD_S:
2385 APPL_TRACE_DEBUG("\talloc_mthd:%d (SNR)", sbc_cie.alloc_mthd);
2386 break;
2387 case A2D_SBC_IE_ALLOC_MD_L:
2388 APPL_TRACE_DEBUG("\talloc_mthd:%d (Loudness)", sbc_cie.alloc_mthd);
2389 break;
2390 default:
2391 APPL_TRACE_DEBUG(" Unknown Allocation Method");
2392 break;
2393 }
2394
2395 APPL_TRACE_DEBUG("\tBit pool Min:%d Max:%d", sbc_cie.min_bitpool, sbc_cie.max_bitpool);
2396
2397 btif_media_cb.frames_to_process = ((freq_multiple)/(num_blocks*num_subbands)) + 1;
2398 APPL_TRACE_DEBUG(" Frames to be processed in 20 ms %d",btif_media_cb.frames_to_process);
2399 }
2400 #endif
2401
2402 /*******************************************************************************
2403 **
2404 ** Function btif_media_task_feeding_state_reset
2405 **
2406 ** Description Reset the media feeding state
2407 **
2408 ** Returns void
2409 **
2410 *******************************************************************************/
btif_media_task_feeding_state_reset(void)2411 static void btif_media_task_feeding_state_reset(void)
2412 {
2413 /* By default, just clear the entire state */
2414 memset(&btif_media_cb.media_feeding_state, 0, sizeof(btif_media_cb.media_feeding_state));
2415
2416 if (btif_media_cb.TxTranscoding == BTIF_MEDIA_TRSCD_PCM_2_SBC)
2417 {
2418 btif_media_cb.media_feeding_state.pcm.bytes_per_tick =
2419 (btif_media_cb.media_feeding.cfg.pcm.sampling_freq *
2420 btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8 *
2421 btif_media_cb.media_feeding.cfg.pcm.num_channel *
2422 BTIF_MEDIA_TIME_TICK)/1000;
2423
2424 APPL_TRACE_WARNING("pcm bytes per tick %d",
2425 (int)btif_media_cb.media_feeding_state.pcm.bytes_per_tick);
2426 }
2427 }
2428
btif_media_task_alarm_cb(UNUSED_ATTR void * context)2429 static void btif_media_task_alarm_cb(UNUSED_ATTR void *context) {
2430 thread_post(worker_thread, btif_media_task_aa_handle_timer, NULL);
2431 }
2432
2433 /*******************************************************************************
2434 **
2435 ** Function btif_media_task_aa_start_tx
2436 **
2437 ** Description Start media task encoding
2438 **
2439 ** Returns void
2440 **
2441 *******************************************************************************/
btif_media_task_aa_start_tx(void)2442 static void btif_media_task_aa_start_tx(void)
2443 {
2444 APPL_TRACE_DEBUG("%s media_alarm %srunning, feeding mode %d", __func__,
2445 alarm_is_scheduled(btif_media_cb.media_alarm)? "" : "not ",
2446 btif_media_cb.feeding_mode);
2447
2448 last_frame_us = 0;
2449
2450 /* Reset the media feeding state */
2451 btif_media_task_feeding_state_reset();
2452
2453 APPL_TRACE_EVENT("starting timer %dms", BTIF_MEDIA_TIME_TICK);
2454
2455 alarm_free(btif_media_cb.media_alarm);
2456 btif_media_cb.media_alarm = alarm_new_periodic("btif.media_task");
2457 if (!btif_media_cb.media_alarm) {
2458 LOG_ERROR(LOG_TAG, "%s unable to allocate media alarm.", __func__);
2459 return;
2460 }
2461
2462 alarm_set(btif_media_cb.media_alarm, BTIF_MEDIA_TIME_TICK,
2463 btif_media_task_alarm_cb, NULL);
2464 }
2465
2466 /*******************************************************************************
2467 **
2468 ** Function btif_media_task_aa_stop_tx
2469 **
2470 ** Description Stop media task encoding
2471 **
2472 ** Returns void
2473 **
2474 *******************************************************************************/
btif_media_task_aa_stop_tx(void)2475 static void btif_media_task_aa_stop_tx(void)
2476 {
2477 APPL_TRACE_DEBUG("%s media_alarm is %srunning", __func__,
2478 alarm_is_scheduled(btif_media_cb.media_alarm)? "" : "not ");
2479
2480 const bool send_ack = alarm_is_scheduled(btif_media_cb.media_alarm);
2481
2482 /* Stop the timer first */
2483 alarm_free(btif_media_cb.media_alarm);
2484 btif_media_cb.media_alarm = NULL;
2485
2486 UIPC_Close(UIPC_CH_ID_AV_AUDIO);
2487
2488 /* Try to send acknowldegment once the media stream is
2489 stopped. This will make sure that the A2DP HAL layer is
2490 un-blocked on wait for acknowledgment for the sent command.
2491 This resolves a corner cases AVDTP SUSPEND collision
2492 when the DUT and the remote device issue SUSPEND simultaneously
2493 and due to the processing of the SUSPEND request from the remote,
2494 the media path is torn down. If the A2DP HAL happens to wait
2495 for ACK for the initiated SUSPEND, it would never receive it casuing
2496 a block/wait. Due to this acknowledgement, the A2DP HAL is guranteed
2497 to get the ACK for any pending command in such cases. */
2498
2499 if (send_ack)
2500 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
2501
2502 /* audio engine stopped, reset tx suspended flag */
2503 btif_media_cb.tx_flush = 0;
2504 last_frame_us = 0;
2505
2506 /* Reset the media feeding state */
2507 btif_media_task_feeding_state_reset();
2508 }
2509
get_frame_length()2510 static UINT32 get_frame_length()
2511 {
2512 UINT32 frame_len = 0;
2513 APPL_TRACE_DEBUG("%s channel mode: %d, sub-band: %d, number of block: %d, \
2514 bitpool: %d, sampling frequency: %d, num channels: %d",
2515 __func__,
2516 btif_media_cb.encoder.s16ChannelMode,
2517 btif_media_cb.encoder.s16NumOfSubBands,
2518 btif_media_cb.encoder.s16NumOfBlocks,
2519 btif_media_cb.encoder.s16BitPool,
2520 btif_media_cb.encoder.s16SamplingFreq,
2521 btif_media_cb.encoder.s16NumOfChannels);
2522
2523 switch (btif_media_cb.encoder.s16ChannelMode) {
2524 case SBC_MONO:
2525 /* FALLTHROUGH */
2526 case SBC_DUAL:
2527 frame_len = SBC_FRAME_HEADER_SIZE_BYTES +
2528 ((UINT32)(SBC_SCALE_FACTOR_BITS * btif_media_cb.encoder.s16NumOfSubBands *
2529 btif_media_cb.encoder.s16NumOfChannels) / CHAR_BIT) +
2530 ((UINT32)(btif_media_cb.encoder.s16NumOfBlocks *
2531 btif_media_cb.encoder.s16NumOfChannels *
2532 btif_media_cb.encoder.s16BitPool) / CHAR_BIT);
2533 break;
2534 case SBC_STEREO:
2535 frame_len = SBC_FRAME_HEADER_SIZE_BYTES +
2536 ((UINT32)(SBC_SCALE_FACTOR_BITS * btif_media_cb.encoder.s16NumOfSubBands *
2537 btif_media_cb.encoder.s16NumOfChannels) / CHAR_BIT) +
2538 ((UINT32)(btif_media_cb.encoder.s16NumOfBlocks *
2539 btif_media_cb.encoder.s16BitPool) / CHAR_BIT);
2540 break;
2541 case SBC_JOINT_STEREO:
2542 frame_len = SBC_FRAME_HEADER_SIZE_BYTES +
2543 ((UINT32)(SBC_SCALE_FACTOR_BITS * btif_media_cb.encoder.s16NumOfSubBands *
2544 btif_media_cb.encoder.s16NumOfChannels) / CHAR_BIT) +
2545 ((UINT32)(btif_media_cb.encoder.s16NumOfSubBands +
2546 (btif_media_cb.encoder.s16NumOfBlocks *
2547 btif_media_cb.encoder.s16BitPool)) / CHAR_BIT);
2548 break;
2549 default:
2550 APPL_TRACE_DEBUG("%s Invalid channel number: %d",
2551 __func__, btif_media_cb.encoder.s16ChannelMode);
2552 break;
2553 }
2554 APPL_TRACE_DEBUG("%s calculated frame length: %d", __func__, frame_len);
2555 return frame_len;
2556 }
2557
calculate_max_frames_per_packet()2558 static UINT8 calculate_max_frames_per_packet()
2559 {
2560 UINT16 result = 0;
2561 UINT16 effective_mtu_size = btif_media_cb.TxAaMtuSize;
2562 UINT32 frame_len;
2563
2564 APPL_TRACE_DEBUG("%s original AVDTP MTU size: %d", __func__, btif_media_cb.TxAaMtuSize);
2565 if (btif_av_is_peer_edr() && (btif_av_peer_supports_3mbps() == FALSE)) {
2566 // This condition would be satisfied only if the remote device is
2567 // EDR and supports only 2 Mbps, but the effective AVDTP MTU size
2568 // exceeds the 2DH5 packet size.
2569 APPL_TRACE_DEBUG("%s The remote devce is EDR but does not support 3 Mbps", __func__);
2570
2571 if (effective_mtu_size > MAX_2MBPS_AVDTP_MTU) {
2572 APPL_TRACE_WARNING("%s Restricting AVDTP MTU size to %d",
2573 __func__, MAX_2MBPS_AVDTP_MTU);
2574 effective_mtu_size = MAX_2MBPS_AVDTP_MTU;
2575 btif_media_cb.TxAaMtuSize = effective_mtu_size;
2576 }
2577 }
2578
2579 if (!btif_media_cb.encoder.s16NumOfSubBands) {
2580 APPL_TRACE_ERROR("%s SubBands are set to 0, resetting to %d",
2581 __func__, SBC_MAX_NUM_OF_SUBBANDS);
2582 btif_media_cb.encoder.s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS;
2583 }
2584 if (!btif_media_cb.encoder.s16NumOfBlocks) {
2585 APPL_TRACE_ERROR("%s Blocks are set to 0, resetting to %d",
2586 __func__, SBC_MAX_NUM_OF_BLOCKS);
2587 btif_media_cb.encoder.s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS;
2588 }
2589 if (!btif_media_cb.encoder.s16NumOfChannels) {
2590 APPL_TRACE_ERROR("%s Channels are set to 0, resetting to %d",
2591 __func__, SBC_MAX_NUM_OF_CHANNELS);
2592 btif_media_cb.encoder.s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS;
2593 }
2594
2595 frame_len = get_frame_length();
2596
2597 APPL_TRACE_DEBUG("%s Effective Tx MTU to be considered: %d",
2598 __func__, effective_mtu_size);
2599
2600 switch (btif_media_cb.encoder.s16SamplingFreq) {
2601 case SBC_sf44100:
2602 if (frame_len == 0) {
2603 APPL_TRACE_ERROR("%s Calculating frame length, \
2604 resetting it to default 119", __func__);
2605 frame_len = MAX_SBC_HQ_FRAME_SIZE_44_1;
2606 }
2607 result = (effective_mtu_size - A2DP_HDR_SIZE) / frame_len;
2608 APPL_TRACE_DEBUG("%s Max number of SBC frames: %d", __func__, result);
2609 break;
2610
2611 case SBC_sf48000:
2612 if (frame_len == 0) {
2613 APPL_TRACE_ERROR("%s Calculating frame length, \
2614 resetting it to default 115", __func__);
2615 frame_len = MAX_SBC_HQ_FRAME_SIZE_48;
2616 }
2617 result = (effective_mtu_size - A2DP_HDR_SIZE) / frame_len;
2618 APPL_TRACE_DEBUG("%s Max number of SBC frames: %d", __func__, result);
2619 break;
2620
2621 default:
2622 APPL_TRACE_ERROR("%s Max number of SBC frames: %d", __func__, result);
2623 break;
2624
2625 }
2626 return result;
2627 }
2628
2629 /*******************************************************************************
2630 **
2631 ** Function btif_get_num_aa_frame_iteration
2632 **
2633 ** Description returns number of frames to send and number of iterations
2634 ** to be used. num_of_ietrations and num_of_frames parameters
2635 ** are used as output param for returning the respective values
2636 **
2637 ** Returns void
2638 **
2639 *******************************************************************************/
btif_get_num_aa_frame_iteration(UINT8 * num_of_iterations,UINT8 * num_of_frames)2640 static void btif_get_num_aa_frame_iteration(UINT8 *num_of_iterations, UINT8 *num_of_frames)
2641 {
2642 UINT8 nof = 0;
2643 UINT8 noi = 1;
2644
2645 switch (btif_media_cb.TxTranscoding)
2646 {
2647 case BTIF_MEDIA_TRSCD_PCM_2_SBC:
2648 {
2649 UINT32 projected_nof = 0;
2650 UINT32 pcm_bytes_per_frame = btif_media_cb.encoder.s16NumOfSubBands *
2651 btif_media_cb.encoder.s16NumOfBlocks *
2652 btif_media_cb.media_feeding.cfg.pcm.num_channel *
2653 btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8;
2654 APPL_TRACE_DEBUG("%s pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
2655
2656 UINT32 us_this_tick = BTIF_MEDIA_TIME_TICK * 1000;
2657 UINT64 now_us = time_now_us();
2658 if (last_frame_us != 0)
2659 us_this_tick = (now_us - last_frame_us);
2660 last_frame_us = now_us;
2661
2662 btif_media_cb.media_feeding_state.pcm.counter +=
2663 btif_media_cb.media_feeding_state.pcm.bytes_per_tick *
2664 us_this_tick / (BTIF_MEDIA_TIME_TICK * 1000);
2665
2666 /* calculate nbr of frames pending for this media tick */
2667 projected_nof = btif_media_cb.media_feeding_state.pcm.counter / pcm_bytes_per_frame;
2668 if (projected_nof > btif_media_cb.stats.media_read_max_expected_frames)
2669 btif_media_cb.stats.media_read_max_expected_frames = projected_nof;
2670 btif_media_cb.stats.media_read_total_expected_frames += projected_nof;
2671 btif_media_cb.stats.media_read_expected_count++;
2672 if (projected_nof > MAX_PCM_FRAME_NUM_PER_TICK)
2673 {
2674 APPL_TRACE_WARNING("%s() - Limiting frames to be sent from %d to %d"
2675 , __FUNCTION__, projected_nof, MAX_PCM_FRAME_NUM_PER_TICK);
2676 size_t delta = projected_nof - MAX_PCM_FRAME_NUM_PER_TICK;
2677 btif_media_cb.stats.media_read_limited_count++;
2678 btif_media_cb.stats.media_read_total_limited_frames += delta;
2679 if (delta > btif_media_cb.stats.media_read_max_limited_frames)
2680 btif_media_cb.stats.media_read_max_limited_frames = delta;
2681 projected_nof = MAX_PCM_FRAME_NUM_PER_TICK;
2682 }
2683
2684 APPL_TRACE_DEBUG("%s frames for available PCM data %u", __func__, projected_nof);
2685
2686 if (btif_av_is_peer_edr())
2687 {
2688 if (!btif_media_cb.tx_sbc_frames)
2689 {
2690 APPL_TRACE_ERROR("%s tx_sbc_frames not updated, update from here", __func__);
2691 btif_media_cb.tx_sbc_frames = calculate_max_frames_per_packet();
2692 }
2693
2694 nof = btif_media_cb.tx_sbc_frames;
2695 if (!nof) {
2696 APPL_TRACE_ERROR("%s Number of frames not updated, set calculated values",
2697 __func__);
2698 nof = projected_nof;
2699 noi = 1;
2700 } else {
2701 if (nof < projected_nof)
2702 {
2703 noi = projected_nof / nof; // number of iterations would vary
2704 if (noi > MAX_PCM_ITER_NUM_PER_TICK)
2705 {
2706 APPL_TRACE_ERROR("%s ## Audio Congestion (iterations:%d > max (%d))",
2707 __func__, noi, MAX_PCM_ITER_NUM_PER_TICK);
2708 noi = MAX_PCM_ITER_NUM_PER_TICK;
2709 btif_media_cb.media_feeding_state.pcm.counter
2710 = noi * nof * pcm_bytes_per_frame;
2711 }
2712 projected_nof = nof;
2713 } else {
2714 noi = 1; // number of iterations is 1
2715 APPL_TRACE_DEBUG("%s reducing frames for available PCM data", __func__);
2716 nof = projected_nof;
2717 }
2718 }
2719 } else {
2720 // For BR cases nof will be same as the value retrieved at projected_nof
2721 APPL_TRACE_DEBUG("%s headset BR, number of frames %u", __func__, nof);
2722 if (projected_nof > MAX_PCM_FRAME_NUM_PER_TICK)
2723 {
2724 APPL_TRACE_ERROR("%s ## Audio Congestion (frames: %d > max (%d))",
2725 __func__, projected_nof, MAX_PCM_FRAME_NUM_PER_TICK);
2726 projected_nof = MAX_PCM_FRAME_NUM_PER_TICK;
2727 btif_media_cb.media_feeding_state.pcm.counter =
2728 noi * projected_nof * pcm_bytes_per_frame;
2729 }
2730 nof = projected_nof;
2731 }
2732 btif_media_cb.media_feeding_state.pcm.counter -= noi * nof * pcm_bytes_per_frame;
2733 APPL_TRACE_DEBUG("%s effective num of frames %u, iterations %u", __func__, nof, noi);
2734 }
2735 break;
2736
2737 default:
2738 APPL_TRACE_ERROR("%s Unsupported transcoding format 0x%x",
2739 __func__, btif_media_cb.TxTranscoding);
2740 nof = 0;
2741 noi = 0;
2742 break;
2743 }
2744 *num_of_frames = nof;
2745 *num_of_iterations = noi;
2746 }
2747
2748 /*******************************************************************************
2749 **
2750 ** Function btif_media_sink_enque_buf
2751 **
2752 ** Description This function is called by the av_co to fill A2DP Sink Queue
2753 **
2754 **
2755 ** Returns size of the queue
2756 *******************************************************************************/
btif_media_sink_enque_buf(BT_HDR * p_pkt)2757 UINT8 btif_media_sink_enque_buf(BT_HDR *p_pkt)
2758 {
2759 if (btif_media_cb.rx_flush == TRUE) /* Flush enabled, do not enque */
2760 return fixed_queue_length(btif_media_cb.RxSbcQ);
2761 if (fixed_queue_length(btif_media_cb.RxSbcQ) == MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ)
2762 {
2763 UINT8 ret = fixed_queue_length(btif_media_cb.RxSbcQ);
2764 osi_free(fixed_queue_try_dequeue(btif_media_cb.RxSbcQ));
2765 return ret;
2766 }
2767
2768 BTIF_TRACE_VERBOSE("%s +", __func__);
2769 /* allocate and Queue this buffer */
2770 tBT_SBC_HDR *p_msg =
2771 (tBT_SBC_HDR *)osi_malloc(sizeof(tBT_SBC_HDR) + p_pkt->offset +
2772 p_pkt->len);
2773 memcpy((UINT8 *)(p_msg + 1), (UINT8 *)(p_pkt + 1) + p_pkt->offset,
2774 p_pkt->len);
2775 p_msg->num_frames_to_be_processed = (*((UINT8 *)(p_pkt + 1) + p_pkt->offset))& 0x0f;
2776 p_msg->len = p_pkt->len;
2777 p_msg->offset = 0;
2778 p_msg->layer_specific = p_pkt->layer_specific;
2779 BTIF_TRACE_VERBOSE("%s frames to process %d, len %d ",
2780 __func__, p_msg->num_frames_to_be_processed,p_msg->len);
2781 fixed_queue_enqueue(btif_media_cb.RxSbcQ, p_msg);
2782 if (fixed_queue_length(btif_media_cb.RxSbcQ) == MAX_A2DP_DELAYED_START_FRAME_COUNT) {
2783 BTIF_TRACE_DEBUG(" Initiate Decoding ");
2784 btif_media_task_aa_handle_start_decoding();
2785 }
2786
2787 return fixed_queue_length(btif_media_cb.RxSbcQ);
2788 }
2789
2790 /*******************************************************************************
2791 **
2792 ** Function btif_media_aa_readbuf
2793 **
2794 ** Description This function is called by the av_co to get the next buffer to send
2795 **
2796 **
2797 ** Returns void
2798 *******************************************************************************/
btif_media_aa_readbuf(void)2799 BT_HDR *btif_media_aa_readbuf(void)
2800 {
2801 uint64_t now_us = time_now_us();
2802 BT_HDR *p_buf = fixed_queue_try_dequeue(btif_media_cb.TxAaQ);
2803
2804 btif_media_cb.stats.tx_queue_total_readbuf_calls++;
2805 btif_media_cb.stats.tx_queue_last_readbuf_us = now_us;
2806 if (p_buf != NULL) {
2807 // Update the statistics
2808 update_scheduling_stats(&btif_media_cb.stats.tx_queue_dequeue_stats,
2809 now_us, BTIF_SINK_MEDIA_TIME_TICK_MS * 1000);
2810 }
2811
2812 return p_buf;
2813 }
2814
2815 /*******************************************************************************
2816 **
2817 ** Function btif_media_aa_read_feeding
2818 **
2819 ** Description
2820 **
2821 ** Returns void
2822 **
2823 *******************************************************************************/
2824
btif_media_aa_read_feeding(tUIPC_CH_ID channel_id)2825 BOOLEAN btif_media_aa_read_feeding(tUIPC_CH_ID channel_id)
2826 {
2827 UINT16 event;
2828 UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands * \
2829 btif_media_cb.encoder.s16NumOfBlocks;
2830 UINT32 read_size;
2831 UINT16 sbc_sampling = 48000;
2832 UINT32 src_samples;
2833 UINT16 bytes_needed = blocm_x_subband * btif_media_cb.encoder.s16NumOfChannels * \
2834 btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8;
2835 static UINT16 up_sampled_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS
2836 * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * 2];
2837 static UINT16 read_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS
2838 * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS];
2839 UINT32 src_size_used;
2840 UINT32 dst_size_used;
2841 BOOLEAN fract_needed;
2842 INT32 fract_max;
2843 INT32 fract_threshold;
2844 UINT32 nb_byte_read;
2845
2846 /* Get the SBC sampling rate */
2847 switch (btif_media_cb.encoder.s16SamplingFreq)
2848 {
2849 case SBC_sf48000:
2850 sbc_sampling = 48000;
2851 break;
2852 case SBC_sf44100:
2853 sbc_sampling = 44100;
2854 break;
2855 case SBC_sf32000:
2856 sbc_sampling = 32000;
2857 break;
2858 case SBC_sf16000:
2859 sbc_sampling = 16000;
2860 break;
2861 }
2862
2863 if (sbc_sampling == btif_media_cb.media_feeding.cfg.pcm.sampling_freq) {
2864 read_size = bytes_needed - btif_media_cb.media_feeding_state.pcm.aa_feed_residue;
2865 nb_byte_read = UIPC_Read(channel_id, &event,
2866 ((UINT8 *)btif_media_cb.encoder.as16PcmBuffer) +
2867 btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2868 read_size);
2869 if (nb_byte_read == read_size) {
2870 btif_media_cb.media_feeding_state.pcm.aa_feed_residue = 0;
2871 return TRUE;
2872 } else {
2873 APPL_TRACE_WARNING("### UNDERFLOW :: ONLY READ %d BYTES OUT OF %d ###",
2874 nb_byte_read, read_size);
2875 btif_media_cb.media_feeding_state.pcm.aa_feed_residue += nb_byte_read;
2876 btif_media_cb.stats.media_read_total_underflow_bytes += (read_size - nb_byte_read);
2877 btif_media_cb.stats.media_read_total_underflow_count++;
2878 btif_media_cb.stats.media_read_last_underflow_us = time_now_us();
2879 return FALSE;
2880 }
2881 }
2882
2883 /* Some Feeding PCM frequencies require to split the number of sample */
2884 /* to read. */
2885 /* E.g 128/6=21.3333 => read 22 and 21 and 21 => max = 2; threshold = 0*/
2886 fract_needed = FALSE; /* Default */
2887 switch (btif_media_cb.media_feeding.cfg.pcm.sampling_freq)
2888 {
2889 case 32000:
2890 case 8000:
2891 fract_needed = TRUE;
2892 fract_max = 2; /* 0, 1 and 2 */
2893 fract_threshold = 0; /* Add one for the first */
2894 break;
2895 case 16000:
2896 fract_needed = TRUE;
2897 fract_max = 2; /* 0, 1 and 2 */
2898 fract_threshold = 1; /* Add one for the first two frames*/
2899 break;
2900 }
2901
2902 /* Compute number of sample to read from source */
2903 src_samples = blocm_x_subband;
2904 src_samples *= btif_media_cb.media_feeding.cfg.pcm.sampling_freq;
2905 src_samples /= sbc_sampling;
2906
2907 /* The previous division may have a remainder not null */
2908 if (fract_needed)
2909 {
2910 if (btif_media_cb.media_feeding_state.pcm.aa_feed_counter <= fract_threshold)
2911 {
2912 src_samples++; /* for every read before threshold add one sample */
2913 }
2914
2915 /* do nothing if counter >= threshold */
2916 btif_media_cb.media_feeding_state.pcm.aa_feed_counter++; /* one more read */
2917 if (btif_media_cb.media_feeding_state.pcm.aa_feed_counter > fract_max)
2918 {
2919 btif_media_cb.media_feeding_state.pcm.aa_feed_counter = 0;
2920 }
2921 }
2922
2923 /* Compute number of bytes to read from source */
2924 read_size = src_samples;
2925 read_size *= btif_media_cb.media_feeding.cfg.pcm.num_channel;
2926 read_size *= (btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8);
2927
2928 /* Read Data from UIPC channel */
2929 nb_byte_read = UIPC_Read(channel_id, &event, (UINT8 *)read_buffer, read_size);
2930
2931 //tput_mon(TRUE, nb_byte_read, FALSE);
2932
2933 if (nb_byte_read < read_size)
2934 {
2935 APPL_TRACE_WARNING("### UNDERRUN :: ONLY READ %d BYTES OUT OF %d ###",
2936 nb_byte_read, read_size);
2937 btif_media_cb.stats.media_read_total_underrun_bytes += (read_size - nb_byte_read);
2938 btif_media_cb.stats.media_read_total_underrun_count++;
2939 btif_media_cb.stats.media_read_last_underrun_us = time_now_us();
2940
2941 if (nb_byte_read == 0)
2942 return FALSE;
2943
2944 if(btif_media_cb.feeding_mode == BTIF_AV_FEEDING_ASYNCHRONOUS)
2945 {
2946 /* Fill the unfilled part of the read buffer with silence (0) */
2947 memset(((UINT8 *)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
2948 nb_byte_read = read_size;
2949 }
2950 }
2951
2952 /* Initialize PCM up-sampling engine */
2953 bta_av_sbc_init_up_sample(btif_media_cb.media_feeding.cfg.pcm.sampling_freq,
2954 sbc_sampling, btif_media_cb.media_feeding.cfg.pcm.bit_per_sample,
2955 btif_media_cb.media_feeding.cfg.pcm.num_channel);
2956
2957 /* re-sample read buffer */
2958 /* The output PCM buffer will be stereo, 16 bit per sample */
2959 dst_size_used = bta_av_sbc_up_sample((UINT8 *)read_buffer,
2960 (UINT8 *)up_sampled_buffer + btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2961 nb_byte_read,
2962 sizeof(up_sampled_buffer) - btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2963 &src_size_used);
2964
2965 /* update the residue */
2966 btif_media_cb.media_feeding_state.pcm.aa_feed_residue += dst_size_used;
2967
2968 /* only copy the pcm sample when we have up-sampled enough PCM */
2969 if(btif_media_cb.media_feeding_state.pcm.aa_feed_residue >= bytes_needed)
2970 {
2971 /* Copy the output pcm samples in SBC encoding buffer */
2972 memcpy((UINT8 *)btif_media_cb.encoder.as16PcmBuffer,
2973 (UINT8 *)up_sampled_buffer,
2974 bytes_needed);
2975 /* update the residue */
2976 btif_media_cb.media_feeding_state.pcm.aa_feed_residue -= bytes_needed;
2977
2978 if (btif_media_cb.media_feeding_state.pcm.aa_feed_residue != 0)
2979 {
2980 memcpy((UINT8 *)up_sampled_buffer,
2981 (UINT8 *)up_sampled_buffer + bytes_needed,
2982 btif_media_cb.media_feeding_state.pcm.aa_feed_residue);
2983 }
2984 return TRUE;
2985 }
2986
2987 return FALSE;
2988 }
2989
2990 /*******************************************************************************
2991 **
2992 ** Function btif_media_aa_prep_sbc_2_send
2993 **
2994 ** Description
2995 **
2996 ** Returns void
2997 **
2998 *******************************************************************************/
btif_media_aa_prep_sbc_2_send(UINT8 nb_frame,uint64_t timestamp_us)2999 static void btif_media_aa_prep_sbc_2_send(UINT8 nb_frame,
3000 uint64_t timestamp_us)
3001 {
3002 uint8_t remain_nb_frame = nb_frame;
3003 UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands *
3004 btif_media_cb.encoder.s16NumOfBlocks;
3005
3006 while (nb_frame) {
3007 BT_HDR *p_buf = osi_malloc(BTIF_MEDIA_AA_BUF_SIZE);
3008
3009 /* Init buffer */
3010 p_buf->offset = BTIF_MEDIA_AA_SBC_OFFSET;
3011 p_buf->len = 0;
3012 p_buf->layer_specific = 0;
3013
3014 do
3015 {
3016 /* Write @ of allocated buffer in encoder.pu8Packet */
3017 btif_media_cb.encoder.pu8Packet = (UINT8 *) (p_buf + 1) + p_buf->offset + p_buf->len;
3018 /* Fill allocated buffer with 0 */
3019 memset(btif_media_cb.encoder.as16PcmBuffer, 0, blocm_x_subband
3020 * btif_media_cb.encoder.s16NumOfChannels);
3021
3022 /* Read PCM data and upsample them if needed */
3023 if (btif_media_aa_read_feeding(UIPC_CH_ID_AV_AUDIO))
3024 {
3025 SBC_Encoder(&(btif_media_cb.encoder));
3026
3027 /* Update SBC frame length */
3028 p_buf->len += btif_media_cb.encoder.u16PacketLength;
3029 nb_frame--;
3030 p_buf->layer_specific++;
3031 }
3032 else
3033 {
3034 APPL_TRACE_WARNING("btif_media_aa_prep_sbc_2_send underflow %d, %d",
3035 nb_frame, btif_media_cb.media_feeding_state.pcm.aa_feed_residue);
3036 btif_media_cb.media_feeding_state.pcm.counter += nb_frame *
3037 btif_media_cb.encoder.s16NumOfSubBands *
3038 btif_media_cb.encoder.s16NumOfBlocks *
3039 btif_media_cb.media_feeding.cfg.pcm.num_channel *
3040 btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8;
3041 /* no more pcm to read */
3042 nb_frame = 0;
3043
3044 /* break read loop if timer was stopped (media task stopped) */
3045 if (! alarm_is_scheduled(btif_media_cb.media_alarm))
3046 {
3047 osi_free(p_buf);
3048 return;
3049 }
3050 }
3051
3052 } while (((p_buf->len + btif_media_cb.encoder.u16PacketLength) < btif_media_cb.TxAaMtuSize)
3053 && (p_buf->layer_specific < 0x0F) && nb_frame);
3054
3055 if(p_buf->len)
3056 {
3057 /* timestamp of the media packet header represent the TS of the first SBC frame
3058 i.e the timestamp before including this frame */
3059 *((UINT32 *) (p_buf + 1)) = btif_media_cb.timestamp;
3060
3061 btif_media_cb.timestamp += p_buf->layer_specific * blocm_x_subband;
3062
3063 if (btif_media_cb.tx_flush)
3064 {
3065 APPL_TRACE_DEBUG("### tx suspended, discarded frame ###");
3066
3067 btif_media_cb.stats.tx_queue_total_flushed_messages +=
3068 fixed_queue_length(btif_media_cb.TxAaQ);
3069 btif_media_cb.stats.tx_queue_last_flushed_us =
3070 timestamp_us;
3071 btif_media_flush_q(btif_media_cb.TxAaQ);
3072
3073 osi_free(p_buf);
3074 return;
3075 }
3076
3077 /* Enqueue the encoded SBC frame in AA Tx Queue */
3078 update_scheduling_stats(&btif_media_cb.stats.tx_queue_enqueue_stats,
3079 timestamp_us,
3080 BTIF_SINK_MEDIA_TIME_TICK_MS * 1000);
3081 uint8_t done_nb_frame = remain_nb_frame - nb_frame;
3082 remain_nb_frame = nb_frame;
3083 btif_media_cb.stats.tx_queue_total_frames += done_nb_frame;
3084 if (done_nb_frame > btif_media_cb.stats.tx_queue_max_frames_per_packet)
3085 btif_media_cb.stats.tx_queue_max_frames_per_packet = done_nb_frame;
3086 fixed_queue_enqueue(btif_media_cb.TxAaQ, p_buf);
3087 }
3088 else
3089 {
3090 osi_free(p_buf);
3091 }
3092 }
3093 }
3094
3095
3096 /*******************************************************************************
3097 **
3098 ** Function btif_media_aa_prep_2_send
3099 **
3100 ** Description
3101 **
3102 ** Returns void
3103 **
3104 *******************************************************************************/
3105
btif_media_aa_prep_2_send(UINT8 nb_frame,uint64_t timestamp_us)3106 static void btif_media_aa_prep_2_send(UINT8 nb_frame, uint64_t timestamp_us)
3107 {
3108 // Check for TX queue overflow
3109
3110 if (nb_frame > MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ)
3111 nb_frame = MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ;
3112
3113 if (fixed_queue_length(btif_media_cb.TxAaQ) > (MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ - nb_frame))
3114 {
3115 APPL_TRACE_WARNING("%s() - TX queue buffer count %d/%d", __func__,
3116 fixed_queue_length(btif_media_cb.TxAaQ),
3117 MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ - nb_frame);
3118 // Keep track of drop-outs
3119 btif_media_cb.stats.tx_queue_dropouts++;
3120 btif_media_cb.stats.tx_queue_last_dropouts_us = timestamp_us;
3121
3122 // Flush all queued buffers...
3123 while (fixed_queue_length(btif_media_cb.TxAaQ)) {
3124 btif_media_cb.stats.tx_queue_total_dropped_messages++;
3125 osi_free(fixed_queue_try_dequeue(btif_media_cb.TxAaQ));
3126 }
3127
3128 // Request RSSI for log purposes if we had to flush buffers
3129 bt_bdaddr_t peer_bda = btif_av_get_addr();
3130 BTM_ReadRSSI(peer_bda.address, btm_read_rssi_cb);
3131 }
3132
3133 // Transcode frame
3134
3135 switch (btif_media_cb.TxTranscoding)
3136 {
3137 case BTIF_MEDIA_TRSCD_PCM_2_SBC:
3138 btif_media_aa_prep_sbc_2_send(nb_frame, timestamp_us);
3139 break;
3140
3141 default:
3142 APPL_TRACE_ERROR("%s unsupported transcoding format 0x%x", __func__, btif_media_cb.TxTranscoding);
3143 break;
3144 }
3145 }
3146
3147 /*******************************************************************************
3148 **
3149 ** Function btif_media_send_aa_frame
3150 **
3151 ** Description
3152 **
3153 ** Returns void
3154 **
3155 *******************************************************************************/
btif_media_send_aa_frame(uint64_t timestamp_us)3156 static void btif_media_send_aa_frame(uint64_t timestamp_us)
3157 {
3158 UINT8 nb_frame_2_send = 0;
3159 UINT8 nb_iterations = 0;
3160
3161 btif_get_num_aa_frame_iteration(&nb_iterations, &nb_frame_2_send);
3162
3163 if (nb_frame_2_send != 0) {
3164 for (UINT8 counter = 0; counter < nb_iterations; counter++)
3165 {
3166 /* format and queue buffer to send */
3167 btif_media_aa_prep_2_send(nb_frame_2_send, timestamp_us);
3168 }
3169 }
3170
3171 LOG_VERBOSE(LOG_TAG, "%s Sent %d frames per iteration, %d iterations",
3172 __func__, nb_frame_2_send, nb_iterations);
3173 bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
3174 }
3175
3176 #endif /* BTA_AV_INCLUDED == TRUE */
3177
3178 /*******************************************************************************
3179 **
3180 ** Function dump_codec_info
3181 **
3182 ** Description Decode and display codec_info (for debug)
3183 **
3184 ** Returns void
3185 **
3186 *******************************************************************************/
dump_codec_info(unsigned char * p_codec)3187 void dump_codec_info(unsigned char *p_codec)
3188 {
3189 tA2D_STATUS a2d_status;
3190 tA2D_SBC_CIE sbc_cie;
3191
3192 a2d_status = A2D_ParsSbcInfo(&sbc_cie, p_codec, FALSE);
3193 if (a2d_status != A2D_SUCCESS)
3194 {
3195 APPL_TRACE_ERROR("ERROR dump_codec_info A2D_ParsSbcInfo fail:%d", a2d_status);
3196 return;
3197 }
3198
3199 APPL_TRACE_DEBUG("dump_codec_info");
3200
3201 if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_16)
3202 { APPL_TRACE_DEBUG("\tsamp_freq:%d (16000)", sbc_cie.samp_freq);}
3203 else if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_32)
3204 { APPL_TRACE_DEBUG("\tsamp_freq:%d (32000)", sbc_cie.samp_freq);}
3205 else if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_44)
3206 { APPL_TRACE_DEBUG("\tsamp_freq:%d (44.100)", sbc_cie.samp_freq);}
3207 else if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_48)
3208 { APPL_TRACE_DEBUG("\tsamp_freq:%d (48000)", sbc_cie.samp_freq);}
3209 else
3210 { APPL_TRACE_DEBUG("\tBAD samp_freq:%d", sbc_cie.samp_freq);}
3211
3212 if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_MONO)
3213 { APPL_TRACE_DEBUG("\tch_mode:%d (Mono)", sbc_cie.ch_mode);}
3214 else if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_DUAL)
3215 { APPL_TRACE_DEBUG("\tch_mode:%d (Dual)", sbc_cie.ch_mode);}
3216 else if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_STEREO)
3217 { APPL_TRACE_DEBUG("\tch_mode:%d (Stereo)", sbc_cie.ch_mode);}
3218 else if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_JOINT)
3219 { APPL_TRACE_DEBUG("\tch_mode:%d (Joint)", sbc_cie.ch_mode);}
3220 else
3221 { APPL_TRACE_DEBUG("\tBAD ch_mode:%d", sbc_cie.ch_mode);}
3222
3223 if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_4)
3224 { APPL_TRACE_DEBUG("\tblock_len:%d (4)", sbc_cie.block_len);}
3225 else if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_8)
3226 { APPL_TRACE_DEBUG("\tblock_len:%d (8)", sbc_cie.block_len);}
3227 else if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_12)
3228 { APPL_TRACE_DEBUG("\tblock_len:%d (12)", sbc_cie.block_len);}
3229 else if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_16)
3230 { APPL_TRACE_DEBUG("\tblock_len:%d (16)", sbc_cie.block_len);}
3231 else
3232 { APPL_TRACE_DEBUG("\tBAD block_len:%d", sbc_cie.block_len);}
3233
3234 if (sbc_cie.num_subbands == A2D_SBC_IE_SUBBAND_4)
3235 { APPL_TRACE_DEBUG("\tnum_subbands:%d (4)", sbc_cie.num_subbands);}
3236 else if (sbc_cie.num_subbands == A2D_SBC_IE_SUBBAND_8)
3237 { APPL_TRACE_DEBUG("\tnum_subbands:%d (8)", sbc_cie.num_subbands);}
3238 else
3239 { APPL_TRACE_DEBUG("\tBAD num_subbands:%d", sbc_cie.num_subbands);}
3240
3241 if (sbc_cie.alloc_mthd == A2D_SBC_IE_ALLOC_MD_S)
3242 { APPL_TRACE_DEBUG("\talloc_mthd:%d (SNR)", sbc_cie.alloc_mthd);}
3243 else if (sbc_cie.alloc_mthd == A2D_SBC_IE_ALLOC_MD_L)
3244 { APPL_TRACE_DEBUG("\talloc_mthd:%d (Loundess)", sbc_cie.alloc_mthd);}
3245 else
3246 { APPL_TRACE_DEBUG("\tBAD alloc_mthd:%d", sbc_cie.alloc_mthd);}
3247
3248 APPL_TRACE_DEBUG("\tBit pool Min:%d Max:%d", sbc_cie.min_bitpool, sbc_cie.max_bitpool);
3249
3250 }
3251
btif_debug_a2dp_dump(int fd)3252 void btif_debug_a2dp_dump(int fd)
3253 {
3254 uint64_t now_us = time_now_us();
3255 btif_media_stats_t *stats = &btif_media_cb.stats;
3256 scheduling_stats_t *enqueue_stats = &stats->tx_queue_enqueue_stats;
3257 scheduling_stats_t *dequeue_stats = &stats->tx_queue_dequeue_stats;
3258 size_t ave_size;
3259 uint64_t ave_time_us;
3260
3261 dprintf(fd, "\nA2DP State:\n");
3262 dprintf(fd, " TxQueue:\n");
3263
3264 dprintf(fd, " Counts (enqueue/dequeue/readbuf) : %zu / %zu / %zu\n",
3265 enqueue_stats->total_updates,
3266 dequeue_stats->total_updates,
3267 stats->tx_queue_total_readbuf_calls);
3268
3269 dprintf(fd, " Last update time ago in ms (enqueue/dequeue/readbuf) : %llu / %llu / %llu\n",
3270 (enqueue_stats->last_update_us > 0) ?
3271 (unsigned long long)(now_us - enqueue_stats->last_update_us) / 1000 : 0,
3272 (dequeue_stats->last_update_us > 0) ?
3273 (unsigned long long)(now_us - dequeue_stats->last_update_us) / 1000 : 0,
3274 (stats->tx_queue_last_readbuf_us > 0)?
3275 (unsigned long long)(now_us - stats->tx_queue_last_readbuf_us) / 1000 : 0);
3276
3277 ave_size = 0;
3278 if (stats->media_read_expected_count != 0)
3279 ave_size = stats->media_read_total_expected_frames / stats->media_read_expected_count;
3280 dprintf(fd, " Frames expected (total/max/ave) : %zu / %zu / %zu\n",
3281 stats->media_read_total_expected_frames,
3282 stats->media_read_max_expected_frames,
3283 ave_size);
3284
3285 ave_size = 0;
3286 if (stats->media_read_limited_count != 0)
3287 ave_size = stats->media_read_total_limited_frames / stats->media_read_limited_count;
3288 dprintf(fd, " Frames limited (total/max/ave) : %zu / %zu / %zu\n",
3289 stats->media_read_total_limited_frames,
3290 stats->media_read_max_limited_frames,
3291 ave_size);
3292
3293 dprintf(fd, " Counts (expected/limited) : %zu / %zu\n",
3294 stats->media_read_expected_count,
3295 stats->media_read_limited_count);
3296
3297 ave_size = 0;
3298 if (enqueue_stats->total_updates != 0)
3299 ave_size = stats->tx_queue_total_frames / enqueue_stats->total_updates;
3300 dprintf(fd, " Frames per packet (total/max/ave) : %zu / %zu / %zu\n",
3301 stats->tx_queue_total_frames,
3302 stats->tx_queue_max_frames_per_packet,
3303 ave_size);
3304
3305 dprintf(fd, " Counts (flushed/dropped/dropouts) : %zu / %zu / %zu\n",
3306 stats->tx_queue_total_flushed_messages,
3307 stats->tx_queue_total_dropped_messages,
3308 stats->tx_queue_dropouts);
3309
3310 dprintf(fd, " Last update time ago in ms (flushed/dropped) : %llu / %llu\n",
3311 (stats->tx_queue_last_flushed_us > 0) ?
3312 (unsigned long long)(now_us - stats->tx_queue_last_flushed_us) / 1000 : 0,
3313 (stats->tx_queue_last_dropouts_us > 0)?
3314 (unsigned long long)(now_us - stats->tx_queue_last_dropouts_us)/ 1000 : 0);
3315
3316 dprintf(fd, " Counts (underflow/underrun) : %zu / %zu\n",
3317 stats->media_read_total_underflow_count,
3318 stats->media_read_total_underrun_count);
3319
3320 dprintf(fd, " Bytes (underflow/underrun) : %zu / %zu\n",
3321 stats->media_read_total_underflow_bytes,
3322 stats->media_read_total_underrun_bytes);
3323
3324 dprintf(fd, " Last update time ago in ms (underflow/underrun) : %llu / %llu\n",
3325 (stats->media_read_last_underflow_us > 0) ?
3326 (unsigned long long)(now_us - stats->media_read_last_underflow_us) / 1000 : 0,
3327 (stats->media_read_last_underrun_us > 0)?
3328 (unsigned long long)(now_us - stats->media_read_last_underrun_us) / 1000 : 0);
3329
3330 //
3331 // TxQueue enqueue stats
3332 //
3333 dprintf(fd, " Enqueue deviation counts (overdue/premature) : %zu / %zu\n",
3334 enqueue_stats->overdue_scheduling_count,
3335 enqueue_stats->premature_scheduling_count);
3336
3337 ave_time_us = 0;
3338 if (enqueue_stats->overdue_scheduling_count != 0) {
3339 ave_time_us = enqueue_stats->total_overdue_scheduling_delta_us /
3340 enqueue_stats->overdue_scheduling_count;
3341 }
3342 dprintf(fd, " Enqueue overdue scheduling time in ms (total/max/ave) : %llu / %llu / %llu\n",
3343 (unsigned long long)enqueue_stats->total_overdue_scheduling_delta_us / 1000,
3344 (unsigned long long)enqueue_stats->max_overdue_scheduling_delta_us / 1000,
3345 (unsigned long long)ave_time_us / 1000);
3346
3347 ave_time_us = 0;
3348 if (enqueue_stats->premature_scheduling_count != 0) {
3349 ave_time_us = enqueue_stats->total_premature_scheduling_delta_us /
3350 enqueue_stats->premature_scheduling_count;
3351 }
3352 dprintf(fd, " Enqueue premature scheduling time in ms (total/max/ave) : %llu / %llu / %llu\n",
3353 (unsigned long long)enqueue_stats->total_premature_scheduling_delta_us / 1000,
3354 (unsigned long long)enqueue_stats->max_premature_scheduling_delta_us / 1000,
3355 (unsigned long long)ave_time_us / 1000);
3356
3357
3358 //
3359 // TxQueue dequeue stats
3360 //
3361 dprintf(fd, " Dequeue deviation counts (overdue/premature) : %zu / %zu\n",
3362 dequeue_stats->overdue_scheduling_count,
3363 dequeue_stats->premature_scheduling_count);
3364
3365 ave_time_us = 0;
3366 if (dequeue_stats->overdue_scheduling_count != 0) {
3367 ave_time_us = dequeue_stats->total_overdue_scheduling_delta_us /
3368 dequeue_stats->overdue_scheduling_count;
3369 }
3370 dprintf(fd, " Dequeue overdue scheduling time in ms (total/max/ave) : %llu / %llu / %llu\n",
3371 (unsigned long long)dequeue_stats->total_overdue_scheduling_delta_us / 1000,
3372 (unsigned long long)dequeue_stats->max_overdue_scheduling_delta_us / 1000,
3373 (unsigned long long)ave_time_us / 1000);
3374
3375 ave_time_us = 0;
3376 if (dequeue_stats->premature_scheduling_count != 0) {
3377 ave_time_us = dequeue_stats->total_premature_scheduling_delta_us /
3378 dequeue_stats->premature_scheduling_count;
3379 }
3380 dprintf(fd, " Dequeue premature scheduling time in ms (total/max/ave) : %llu / %llu / %llu\n",
3381 (unsigned long long)dequeue_stats->total_premature_scheduling_delta_us / 1000,
3382 (unsigned long long)dequeue_stats->max_premature_scheduling_delta_us / 1000,
3383 (unsigned long long)ave_time_us / 1000);
3384
3385 }
3386
btif_update_a2dp_metrics(void)3387 void btif_update_a2dp_metrics(void)
3388 {
3389 uint64_t now_us = time_now_us();
3390 btif_media_stats_t *stats = &btif_media_cb.stats;
3391 scheduling_stats_t *dequeue_stats = &stats->tx_queue_dequeue_stats;
3392 int32_t media_timer_min_ms = 0;
3393 int32_t media_timer_max_ms = 0;
3394 int32_t media_timer_avg_ms = 0;
3395 int32_t buffer_overruns_max_count = 0;
3396 int32_t buffer_overruns_total = 0;
3397 float buffer_underruns_average = 0.0;
3398 int32_t buffer_underruns_count = 0;
3399
3400 int64_t session_duration_sec =
3401 (now_us - stats->session_start_us) / (1000 * 1000);
3402
3403 /* NOTE: Disconnect reason is unused */
3404 const char *disconnect_reason = NULL;
3405 uint32_t device_class = BTM_COD_MAJOR_AUDIO;
3406
3407 if (dequeue_stats->total_updates > 1) {
3408 media_timer_min_ms = BTIF_SINK_MEDIA_TIME_TICK_MS -
3409 (dequeue_stats->max_premature_scheduling_delta_us / 1000);
3410 media_timer_max_ms = BTIF_SINK_MEDIA_TIME_TICK_MS +
3411 (dequeue_stats->max_overdue_scheduling_delta_us / 1000);
3412
3413 uint64_t total_scheduling_count =
3414 dequeue_stats->overdue_scheduling_count +
3415 dequeue_stats->premature_scheduling_count +
3416 dequeue_stats->exact_scheduling_count;
3417 if (total_scheduling_count > 0) {
3418 media_timer_avg_ms = dequeue_stats->total_scheduling_time_us /
3419 (1000 * total_scheduling_count);
3420 }
3421
3422 buffer_overruns_max_count = stats->media_read_max_expected_frames;
3423 buffer_overruns_total = stats->tx_queue_total_dropped_messages;
3424 buffer_underruns_count = stats->media_read_total_underflow_count +
3425 stats->media_read_total_underrun_count;
3426 if (buffer_underruns_count > 0) {
3427 buffer_underruns_average =
3428 (stats->media_read_total_underflow_bytes + stats->media_read_total_underrun_bytes) / buffer_underruns_count;
3429 }
3430 }
3431
3432 metrics_a2dp_session(session_duration_sec, disconnect_reason, device_class,
3433 media_timer_min_ms, media_timer_max_ms,
3434 media_timer_avg_ms, buffer_overruns_max_count,
3435 buffer_overruns_total, buffer_underruns_average,
3436 buffer_underruns_count);
3437 }
3438