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 <string.h>
33 #include <stdio.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <pthread.h>
39 #include <stdint.h>
40 #include <sys/time.h>
41 #include <errno.h>
42 
43 #include "bt_target.h"
44 #include "osi/include/fixed_queue.h"
45 #include "gki.h"
46 #include "bta_api.h"
47 #include "btu.h"
48 #include "bta_sys.h"
49 #include "bta_sys_int.h"
50 
51 #include "bta_av_api.h"
52 #include "a2d_api.h"
53 #include "a2d_sbc.h"
54 #include "a2d_int.h"
55 #include "bta_av_sbc.h"
56 #include "bta_av_ci.h"
57 #include "l2c_api.h"
58 
59 #include "btif_av_co.h"
60 #include "btif_media.h"
61 
62 #include "osi/include/alarm.h"
63 #include "osi/include/log.h"
64 #include "osi/include/thread.h"
65 
66 #if (BTA_AV_INCLUDED == TRUE)
67 #include "sbc_encoder.h"
68 #endif
69 
70 #include <hardware/bluetooth.h>
71 #include "audio_a2dp_hw.h"
72 #include "btif_av.h"
73 #include "btif_sm.h"
74 #include "btif_util.h"
75 #if (BTA_AV_SINK_INCLUDED == TRUE)
76 #include "oi_codec_sbc.h"
77 #include "oi_status.h"
78 #endif
79 #include "stdio.h"
80 #include <dlfcn.h>
81 
82 #if (BTA_AV_SINK_INCLUDED == TRUE)
83 OI_CODEC_SBC_DECODER_CONTEXT context;
84 OI_UINT32 contextData[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)];
85 OI_INT16 pcmData[15*SBC_MAX_SAMPLES_PER_FRAME*SBC_MAX_CHANNELS];
86 #endif
87 
88 /*****************************************************************************
89  **  Constants
90  *****************************************************************************/
91 
92 #ifndef AUDIO_CHANNEL_OUT_MONO
93 #define AUDIO_CHANNEL_OUT_MONO 0x01
94 #endif
95 
96 #ifndef AUDIO_CHANNEL_OUT_STEREO
97 #define AUDIO_CHANNEL_OUT_STEREO 0x03
98 #endif
99 
100 /* BTIF media cmd event definition : BTIF_MEDIA_TASK_CMD */
101 enum
102 {
103     BTIF_MEDIA_START_AA_TX = 1,
104     BTIF_MEDIA_STOP_AA_TX,
105     BTIF_MEDIA_AA_RX_RDY,
106     BTIF_MEDIA_UIPC_RX_RDY,
107     BTIF_MEDIA_SBC_ENC_INIT,
108     BTIF_MEDIA_SBC_ENC_UPDATE,
109     BTIF_MEDIA_SBC_DEC_INIT,
110     BTIF_MEDIA_VIDEO_DEC_INIT,
111     BTIF_MEDIA_FLUSH_AA_TX,
112     BTIF_MEDIA_FLUSH_AA_RX,
113     BTIF_MEDIA_AUDIO_FEEDING_INIT,
114     BTIF_MEDIA_AUDIO_RECEIVING_INIT,
115     BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE,
116     BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK
117 };
118 
119 enum {
120     MEDIA_TASK_STATE_OFF = 0,
121     MEDIA_TASK_STATE_ON = 1,
122     MEDIA_TASK_STATE_SHUTTING_DOWN = 2
123 };
124 
125 /* Macro to multiply the media task tick */
126 #ifndef BTIF_MEDIA_NUM_TICK
127 #define BTIF_MEDIA_NUM_TICK      1
128 #endif
129 
130 /* Media task tick in milliseconds, must be set to multiple of
131    (1000/TICKS_PER_SEC) (10) */
132 
133 #define BTIF_MEDIA_TIME_TICK                     (20 * BTIF_MEDIA_NUM_TICK)
134 #define A2DP_DATA_READ_POLL_MS    (BTIF_MEDIA_TIME_TICK / 2)
135 #define BTIF_SINK_MEDIA_TIME_TICK                (20 * BTIF_MEDIA_NUM_TICK)
136 
137 
138 /* buffer pool */
139 #define BTIF_MEDIA_AA_POOL_ID GKI_POOL_ID_3
140 #define BTIF_MEDIA_AA_BUF_SIZE GKI_BUF3_SIZE
141 
142 /* offset */
143 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
144 #define BTIF_MEDIA_AA_SBC_OFFSET (AVDT_MEDIA_OFFSET + BTA_AV_SBC_HDR_SIZE + 1)
145 #else
146 #define BTIF_MEDIA_AA_SBC_OFFSET (AVDT_MEDIA_OFFSET + BTA_AV_SBC_HDR_SIZE)
147 #endif
148 
149 /* Define the bitrate step when trying to match bitpool value */
150 #ifndef BTIF_MEDIA_BITRATE_STEP
151 #define BTIF_MEDIA_BITRATE_STEP 5
152 #endif
153 
154 /* Middle quality quality setting @ 44.1 khz */
155 #define DEFAULT_SBC_BITRATE 328
156 
157 #ifndef BTIF_A2DP_NON_EDR_MAX_RATE
158 #define BTIF_A2DP_NON_EDR_MAX_RATE 229
159 #endif
160 
161 #define USEC_PER_SEC 1000000L
162 #define TPUT_STATS_INTERVAL_US (3000*1000)
163 
164 /*
165  * CONGESTION COMPENSATION CTRL ::
166  *
167  * Thus setting controls how many buffers we will hold in media task
168  * during temp link congestion. Together with the stack buffer queues
169  * it controls much temporary a2dp link congestion we can
170  * compensate for. It however also depends on the default run level of sinks
171  * jitterbuffers. Depending on type of sink this would vary.
172  * Ideally the (SRC) max tx buffer capacity should equal the sinks
173  * jitterbuffer runlevel including any intermediate buffers on the way
174  * towards the sinks codec.
175  */
176 
177 /* fixme -- define this in pcm time instead of buffer count */
178 
179 /* The typical runlevel of the tx queue size is ~1 buffer
180    but due to link flow control or thread preemption in lower
181    layers we might need to temporarily buffer up data */
182 
183 /* 18 frames is equivalent to 6.89*18*2.9 ~= 360 ms @ 44.1 khz, 20 ms mediatick */
184 #define MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ 18
185 
186 #ifndef MAX_PCM_FRAME_NUM_PER_TICK
187 #define MAX_PCM_FRAME_NUM_PER_TICK     14
188 #endif
189 
190 /* In case of A2DP SINK, we will delay start by 5 AVDTP Packets*/
191 #define MAX_A2DP_DELAYED_START_FRAME_COUNT 5
192 #define PACKET_PLAYED_PER_TICK_48 8
193 #define PACKET_PLAYED_PER_TICK_44 7
194 #define PACKET_PLAYED_PER_TICK_32 5
195 #define PACKET_PLAYED_PER_TICK_16 3
196 
197 typedef struct
198 {
199     UINT16 num_frames_to_be_processed;
200     UINT16 len;
201     UINT16 offset;
202     UINT16 layer_specific;
203 } tBT_SBC_HDR;
204 
205 typedef struct
206 {
207     UINT32 aa_frame_counter;
208     INT32  aa_feed_counter;
209     INT32  aa_feed_residue;
210     UINT32 counter;
211     UINT32 bytes_per_tick;  /* pcm bytes read each media task tick */
212 } tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE;
213 
214 typedef union
215 {
216     tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE pcm;
217 } tBTIF_AV_MEDIA_FEEDINGS_STATE;
218 
219 typedef struct
220 {
221 #if (BTA_AV_INCLUDED == TRUE)
222     BUFFER_Q TxAaQ;
223     BUFFER_Q RxSbcQ;
224     BOOLEAN is_tx_timer;
225     BOOLEAN is_rx_timer;
226     UINT16 TxAaMtuSize;
227     UINT32 timestamp;
228     UINT8 TxTranscoding;
229     tBTIF_AV_FEEDING_MODE feeding_mode;
230     tBTIF_AV_MEDIA_FEEDINGS media_feeding;
231     tBTIF_AV_MEDIA_FEEDINGS_STATE media_feeding_state;
232     SBC_ENC_PARAMS encoder;
233     UINT8 busy_level;
234     void* av_sm_hdl;
235     UINT8 a2dp_cmd_pending; /* we can have max one command pending */
236     BOOLEAN tx_flush; /* discards any outgoing data when true */
237     BOOLEAN rx_flush; /* discards any incoming data when true */
238     UINT8 peer_sep;
239     BOOLEAN data_channel_open;
240     UINT8   frames_to_process;
241 
242     UINT32  sample_rate;
243     UINT8   channel_count;
244     alarm_t *media_alarm;
245     alarm_t *decode_alarm;
246 #endif
247 
248 } tBTIF_MEDIA_CB;
249 
250 typedef struct {
251     long long rx;
252     long long rx_tot;
253     long long tx;
254     long long tx_tot;
255     long long ts_prev_us;
256 } t_stat;
257 
258 static UINT64 last_frame_us = 0;
259 
260 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
261 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
262 static void btif_a2dp_encoder_update(void);
263 #if (BTA_AV_SINK_INCLUDED == TRUE)
264 extern OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
265                                           const OI_BYTE **frameData,
266                                           unsigned long *frameBytes,
267                                           OI_INT16 *pcmData,
268                                           unsigned long *pcmBytes);
269 extern OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
270                                            unsigned long *decoderData,
271                                            unsigned long decoderDataBytes,
272                                            OI_UINT8 maxChannels,
273                                            OI_UINT8 pcmStride,
274                                            OI_BOOL enhanced);
275 #endif
276 static void btif_media_flush_q(BUFFER_Q *p_q);
277 static void btif_media_task_aa_handle_stop_decoding(void );
278 static void btif_media_task_aa_rx_flush(void);
279 
280 static const char *dump_media_event(UINT16 event);
281 static void btif_media_thread_init(void *context);
282 static void btif_media_thread_cleanup(void *context);
283 static void btif_media_thread_handle_cmd(fixed_queue_t *queue, void *context);
284 
285 /* Handle incoming media packets A2DP SINK streaming*/
286 #if (BTA_AV_SINK_INCLUDED == TRUE)
287 static void btif_media_task_handle_inc_media(tBT_SBC_HDR*p_msg);
288 #endif
289 
290 #if (BTA_AV_INCLUDED == TRUE)
291 static void btif_media_send_aa_frame(void);
292 static void btif_media_task_feeding_state_reset(void);
293 static void btif_media_task_aa_start_tx(void);
294 static void btif_media_task_aa_stop_tx(void);
295 static void btif_media_task_enc_init(BT_HDR *p_msg);
296 static void btif_media_task_enc_update(BT_HDR *p_msg);
297 static void btif_media_task_audio_feeding_init(BT_HDR *p_msg);
298 static void btif_media_task_aa_tx_flush(BT_HDR *p_msg);
299 static void btif_media_aa_prep_2_send(UINT8 nb_frame);
300 #if (BTA_AV_SINK_INCLUDED == TRUE)
301 static void btif_media_task_aa_handle_decoder_reset(BT_HDR *p_msg);
302 static void btif_media_task_aa_handle_clear_track(void);
303 #endif
304 static void btif_media_task_aa_handle_start_decoding(void);
305 #endif
306 BOOLEAN btif_media_task_clear_track(void);
307 
308 static void btif_media_task_aa_handle_timer(UNUSED_ATTR void *context);
309 static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context);
310 extern BOOLEAN btif_hf_is_call_idle();
311 
312 static tBTIF_MEDIA_CB btif_media_cb;
313 static int media_task_running = MEDIA_TASK_STATE_OFF;
314 
315 static fixed_queue_t *btif_media_cmd_msg_queue;
316 static thread_t *worker_thread;
317 
318 /*****************************************************************************
319  **  Misc helper functions
320  *****************************************************************************/
321 
time_now_us()322 static UINT64 time_now_us()
323 {
324     struct timespec ts_now;
325     clock_gettime(CLOCK_BOOTTIME, &ts_now);
326     return ((UINT64)ts_now.tv_sec * USEC_PER_SEC) + ((UINT64)ts_now.tv_nsec / 1000);
327 }
328 
log_tstamps_us(char * comment)329 static void log_tstamps_us(char *comment)
330 {
331     static UINT64 prev_us = 0;
332     const UINT64 now_us = time_now_us();
333     APPL_TRACE_DEBUG("[%s] ts %08llu, diff : %08llu, queue sz %d", comment, now_us, now_us - prev_us,
334                 GKI_queue_length(&btif_media_cb.TxAaQ));
335     prev_us = now_us;
336 }
337 
dump_media_event(UINT16 event)338 UNUSED_ATTR static const char *dump_media_event(UINT16 event)
339 {
340     switch(event)
341     {
342         CASE_RETURN_STR(BTIF_MEDIA_START_AA_TX)
343         CASE_RETURN_STR(BTIF_MEDIA_STOP_AA_TX)
344         CASE_RETURN_STR(BTIF_MEDIA_AA_RX_RDY)
345         CASE_RETURN_STR(BTIF_MEDIA_UIPC_RX_RDY)
346         CASE_RETURN_STR(BTIF_MEDIA_SBC_ENC_INIT)
347         CASE_RETURN_STR(BTIF_MEDIA_SBC_ENC_UPDATE)
348         CASE_RETURN_STR(BTIF_MEDIA_SBC_DEC_INIT)
349         CASE_RETURN_STR(BTIF_MEDIA_VIDEO_DEC_INIT)
350         CASE_RETURN_STR(BTIF_MEDIA_FLUSH_AA_TX)
351         CASE_RETURN_STR(BTIF_MEDIA_FLUSH_AA_RX)
352         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_FEEDING_INIT)
353         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_RECEIVING_INIT)
354         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE)
355         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK)
356 
357         default:
358             return "UNKNOWN MEDIA EVENT";
359     }
360 }
361 
362 /*****************************************************************************
363  **  A2DP CTRL PATH
364  *****************************************************************************/
365 
dump_a2dp_ctrl_event(UINT8 event)366 static const char* dump_a2dp_ctrl_event(UINT8 event)
367 {
368     switch(event)
369     {
370         CASE_RETURN_STR(A2DP_CTRL_CMD_NONE)
371         CASE_RETURN_STR(A2DP_CTRL_CMD_CHECK_READY)
372         CASE_RETURN_STR(A2DP_CTRL_CMD_START)
373         CASE_RETURN_STR(A2DP_CTRL_CMD_STOP)
374         CASE_RETURN_STR(A2DP_CTRL_CMD_SUSPEND)
375         default:
376             return "UNKNOWN MSG ID";
377     }
378 }
379 
btif_audiopath_detached(void)380 static void btif_audiopath_detached(void)
381 {
382     APPL_TRACE_EVENT("## AUDIO PATH DETACHED ##");
383 
384     /*  send stop request only if we are actively streaming and haven't received
385         a stop request. Potentially audioflinger detached abnormally */
386     if (btif_media_cb.is_tx_timer)
387     {
388         /* post stop event and wait for audio path to stop */
389         btif_dispatch_sm_event(BTIF_AV_STOP_STREAM_REQ_EVT, NULL, 0);
390     }
391 }
392 
a2dp_cmd_acknowledge(int status)393 static void a2dp_cmd_acknowledge(int status)
394 {
395     UINT8 ack = status;
396 
397     APPL_TRACE_EVENT("## a2dp ack : %s, status %d ##",
398           dump_a2dp_ctrl_event(btif_media_cb.a2dp_cmd_pending), status);
399 
400     /* sanity check */
401     if (btif_media_cb.a2dp_cmd_pending == A2DP_CTRL_CMD_NONE)
402     {
403         APPL_TRACE_ERROR("warning : no command pending, ignore ack");
404         return;
405     }
406 
407     /* clear pending */
408     btif_media_cb.a2dp_cmd_pending = A2DP_CTRL_CMD_NONE;
409 
410     /* acknowledge start request */
411     UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, &ack, 1);
412 }
413 
414 
btif_recv_ctrl_data(void)415 static void btif_recv_ctrl_data(void)
416 {
417     UINT8 cmd = 0;
418     int n;
419     n = UIPC_Read(UIPC_CH_ID_AV_CTRL, NULL, &cmd, 1);
420 
421     /* detach on ctrl channel means audioflinger process was terminated */
422     if (n == 0)
423     {
424         APPL_TRACE_EVENT("CTRL CH DETACHED");
425         UIPC_Close(UIPC_CH_ID_AV_CTRL);
426         /* we can operate only on datachannel, if af client wants to
427            do send additional commands the ctrl channel would be reestablished */
428         //btif_audiopath_detached();
429         return;
430     }
431 
432     APPL_TRACE_DEBUG("a2dp-ctrl-cmd : %s", dump_a2dp_ctrl_event(cmd));
433 
434     btif_media_cb.a2dp_cmd_pending = cmd;
435 
436     switch(cmd)
437     {
438         case A2DP_CTRL_CMD_CHECK_READY:
439 
440             if (media_task_running == MEDIA_TASK_STATE_SHUTTING_DOWN)
441             {
442                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
443                 return;
444             }
445 
446             /* check whether av is ready to setup a2dp datapath */
447             if ((btif_av_stream_ready() == TRUE) || (btif_av_stream_started_ready() == TRUE))
448             {
449                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
450             }
451             else
452             {
453                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
454             }
455             break;
456 
457         case A2DP_CTRL_CMD_START:
458             /* Don't sent START request to stack while we are in call.
459                Some headsets like the Sony MW600, don't allow AVDTP START
460                in call and respond BAD_STATE. */
461             if (!btif_hf_is_call_idle())
462             {
463                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_INCALL_FAILURE);
464                 break;
465             }
466 
467             if (btif_av_stream_ready() == TRUE)
468             {
469                 /* setup audio data channel listener */
470                 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
471 
472                 /* post start event and wait for audio path to open */
473                 btif_dispatch_sm_event(BTIF_AV_START_STREAM_REQ_EVT, NULL, 0);
474 
475 #if (BTA_AV_SINK_INCLUDED == TRUE)
476                 if (btif_media_cb.peer_sep == AVDT_TSEP_SRC)
477                     a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
478 #endif
479             }
480             else if (btif_av_stream_started_ready())
481             {
482                 /* already started, setup audio data channel listener
483                    and ack back immediately */
484                 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
485 
486                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
487             }
488             else
489             {
490                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
491                 break;
492             }
493             break;
494 
495         case A2DP_CTRL_CMD_STOP:
496             if (btif_media_cb.peer_sep == AVDT_TSEP_SNK && btif_media_cb.is_tx_timer == FALSE)
497             {
498                 /* we are already stopped, just ack back */
499                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
500                 break;
501             }
502 
503             btif_dispatch_sm_event(BTIF_AV_STOP_STREAM_REQ_EVT, NULL, 0);
504             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
505             break;
506 
507         case A2DP_CTRL_CMD_SUSPEND:
508             /* local suspend */
509             if (btif_av_stream_started_ready())
510             {
511                 btif_dispatch_sm_event(BTIF_AV_SUSPEND_STREAM_REQ_EVT, NULL, 0);
512             }
513             else
514             {
515                 /* if we are not in started state, just ack back ok and let
516                    audioflinger close the channel. This can happen if we are
517                    remotely suspended, clear REMOTE SUSPEND Flag */
518                 btif_av_clear_remote_suspend_flag();
519                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
520             }
521             break;
522 
523         case A2DP_CTRL_GET_AUDIO_CONFIG:
524         {
525             uint32_t sample_rate = btif_media_cb.sample_rate;
526             uint8_t channel_count = btif_media_cb.channel_count;
527 
528             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
529             UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, (UINT8 *)&sample_rate, 4);
530             UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, &channel_count, 1);
531             break;
532         }
533 
534         default:
535             APPL_TRACE_ERROR("UNSUPPORTED CMD (%d)", cmd);
536             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
537             break;
538     }
539     APPL_TRACE_DEBUG("a2dp-ctrl-cmd : %s DONE", dump_a2dp_ctrl_event(cmd));
540 }
541 
btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)542 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event)
543 {
544     UNUSED(ch_id);
545 
546     APPL_TRACE_DEBUG("A2DP-CTRL-CHANNEL EVENT %s", dump_uipc_event(event));
547 
548     switch(event)
549     {
550         case UIPC_OPEN_EVT:
551             /* fetch av statemachine handle */
552             btif_media_cb.av_sm_hdl = btif_av_get_sm_handle();
553             break;
554 
555         case UIPC_CLOSE_EVT:
556             /* restart ctrl server unless we are shutting down */
557             if (media_task_running == MEDIA_TASK_STATE_ON)
558                 UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
559             break;
560 
561         case UIPC_RX_DATA_READY_EVT:
562             btif_recv_ctrl_data();
563             break;
564 
565         default :
566             APPL_TRACE_ERROR("### A2DP-CTRL-CHANNEL EVENT %d NOT HANDLED ###", event);
567             break;
568     }
569 }
570 
btif_a2dp_data_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)571 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event)
572 {
573     UNUSED(ch_id);
574 
575     APPL_TRACE_DEBUG("BTIF MEDIA (A2DP-DATA) EVENT %s", dump_uipc_event(event));
576 
577     switch(event)
578     {
579         case UIPC_OPEN_EVT:
580 
581             /*  read directly from media task from here on (keep callback for
582                 connection events */
583             UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL);
584             UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO,
585                        (void *)A2DP_DATA_READ_POLL_MS);
586 
587             if (btif_media_cb.peer_sep == AVDT_TSEP_SNK) {
588                 /* Start the media task to encode SBC */
589                 btif_media_task_start_aa_req();
590 
591                 /* make sure we update any changed sbc encoder params */
592                 btif_a2dp_encoder_update();
593             }
594             btif_media_cb.data_channel_open = TRUE;
595 
596             /* ack back when media task is fully started */
597             break;
598 
599         case UIPC_CLOSE_EVT:
600             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
601             btif_audiopath_detached();
602             btif_media_cb.data_channel_open = FALSE;
603             break;
604 
605         default :
606             APPL_TRACE_ERROR("### A2DP-DATA EVENT %d NOT HANDLED ###", event);
607             break;
608     }
609 }
610 
611 
612 /*****************************************************************************
613  **  BTIF ADAPTATION
614  *****************************************************************************/
615 
btif_media_task_get_sbc_rate(void)616 static UINT16 btif_media_task_get_sbc_rate(void)
617 {
618     UINT16 rate = DEFAULT_SBC_BITRATE;
619 
620     /* restrict bitrate if a2dp link is non-edr */
621     if (!btif_av_is_peer_edr())
622     {
623         rate = BTIF_A2DP_NON_EDR_MAX_RATE;
624         APPL_TRACE_DEBUG("non-edr a2dp sink detected, restrict rate to %d", rate);
625     }
626 
627     return rate;
628 }
629 
btif_a2dp_encoder_init(void)630 static void btif_a2dp_encoder_init(void)
631 {
632     UINT16 minmtu;
633     tBTIF_MEDIA_INIT_AUDIO msg;
634     tA2D_SBC_CIE sbc_config;
635 
636     /* lookup table for converting channel mode */
637     UINT16 codec_mode_tbl[5] = { SBC_JOINT_STEREO, SBC_STEREO, SBC_DUAL, 0, SBC_MONO };
638 
639     /* lookup table for converting number of blocks */
640     UINT16 codec_block_tbl[5] = { 16, 12, 8, 0, 4 };
641 
642     /* lookup table to convert freq */
643     UINT16 freq_block_tbl[5] = { SBC_sf48000, SBC_sf44100, SBC_sf32000, 0, SBC_sf16000 };
644 
645     APPL_TRACE_DEBUG("btif_a2dp_encoder_init");
646 
647     /* Retrieve the current SBC configuration (default if currently not used) */
648     bta_av_co_audio_get_sbc_config(&sbc_config, &minmtu);
649     msg.NumOfSubBands = (sbc_config.num_subbands == A2D_SBC_IE_SUBBAND_4) ? 4 : 8;
650     msg.NumOfBlocks = codec_block_tbl[sbc_config.block_len >> 5];
651     msg.AllocationMethod = (sbc_config.alloc_mthd == A2D_SBC_IE_ALLOC_MD_L) ? SBC_LOUDNESS : SBC_SNR;
652     msg.ChannelMode = codec_mode_tbl[sbc_config.ch_mode >> 1];
653     msg.SamplingFreq = freq_block_tbl[sbc_config.samp_freq >> 5];
654     msg.MtuSize = minmtu;
655 
656     APPL_TRACE_EVENT("msg.ChannelMode %x", msg.ChannelMode);
657 
658     /* Init the media task to encode SBC properly */
659     btif_media_task_enc_init_req(&msg);
660 }
661 
btif_a2dp_encoder_update(void)662 static void btif_a2dp_encoder_update(void)
663 {
664     UINT16 minmtu;
665     tA2D_SBC_CIE sbc_config;
666     tBTIF_MEDIA_UPDATE_AUDIO msg;
667     UINT8 pref_min;
668     UINT8 pref_max;
669 
670     APPL_TRACE_DEBUG("btif_a2dp_encoder_update");
671 
672     /* Retrieve the current SBC configuration (default if currently not used) */
673     bta_av_co_audio_get_sbc_config(&sbc_config, &minmtu);
674 
675     APPL_TRACE_DEBUG("btif_a2dp_encoder_update: Common min_bitpool:%d(0x%x) max_bitpool:%d(0x%x)",
676             sbc_config.min_bitpool, sbc_config.min_bitpool,
677             sbc_config.max_bitpool, sbc_config.max_bitpool);
678 
679     if (sbc_config.min_bitpool > sbc_config.max_bitpool)
680     {
681         APPL_TRACE_ERROR("btif_a2dp_encoder_update: ERROR btif_a2dp_encoder_update min_bitpool > max_bitpool");
682     }
683 
684     /* check if remote sink has a preferred bitpool range */
685     if (bta_av_co_get_remote_bitpool_pref(&pref_min, &pref_max) == TRUE)
686     {
687         /* adjust our preferred bitpool with the remote preference if within
688            our capable range */
689 
690         if (pref_min < sbc_config.min_bitpool)
691             pref_min = sbc_config.min_bitpool;
692 
693         if (pref_max > sbc_config.max_bitpool)
694             pref_max = sbc_config.max_bitpool;
695 
696         msg.MinBitPool = pref_min;
697         msg.MaxBitPool = pref_max;
698 
699         if ((pref_min != sbc_config.min_bitpool) || (pref_max != sbc_config.max_bitpool))
700         {
701             APPL_TRACE_EVENT("## adjusted our bitpool range to peer pref [%d:%d] ##",
702                 pref_min, pref_max);
703         }
704     }
705     else
706     {
707         msg.MinBitPool = sbc_config.min_bitpool;
708         msg.MaxBitPool = sbc_config.max_bitpool;
709     }
710 
711     msg.MinMtuSize = minmtu;
712 
713     /* Update the media task to encode SBC properly */
714     btif_media_task_enc_update_req(&msg);
715 }
716 
btif_a2dp_start_media_task(void)717 bool btif_a2dp_start_media_task(void)
718 {
719     if (media_task_running != MEDIA_TASK_STATE_OFF)
720     {
721         APPL_TRACE_ERROR("warning : media task already running");
722         return false;
723     }
724 
725     APPL_TRACE_EVENT("## A2DP START MEDIA THREAD ##");
726 
727     btif_media_cmd_msg_queue = fixed_queue_new(SIZE_MAX);
728 
729     /* start a2dp media task */
730     worker_thread = thread_new("media_worker");
731     if (worker_thread == NULL)
732         goto error_exit;
733 
734     fixed_queue_register_dequeue(btif_media_cmd_msg_queue,
735         thread_get_reactor(worker_thread),
736         btif_media_thread_handle_cmd,
737         NULL);
738 
739     thread_post(worker_thread, btif_media_thread_init, NULL);
740 
741     APPL_TRACE_EVENT("## A2DP MEDIA THREAD STARTED ##");
742 
743     return true;
744 
745  error_exit:;
746     APPL_TRACE_ERROR("%s unable to start up media thread", __func__);
747     return false;
748 }
749 
btif_a2dp_stop_media_task(void)750 void btif_a2dp_stop_media_task(void)
751 {
752     APPL_TRACE_EVENT("## A2DP STOP MEDIA THREAD ##");
753 
754     // Stop timer
755     alarm_free(btif_media_cb.media_alarm);
756     btif_media_cb.media_alarm = NULL;
757     btif_media_cb.is_tx_timer = FALSE;
758 
759     // Exit thread
760     fixed_queue_free(btif_media_cmd_msg_queue, NULL);
761     thread_post(worker_thread, btif_media_thread_cleanup, NULL);
762     thread_free(worker_thread);
763 
764     worker_thread = NULL;
765     btif_media_cmd_msg_queue = NULL;
766 }
767 
768 /*****************************************************************************
769 **
770 ** Function        btif_a2dp_on_init
771 **
772 ** Description
773 **
774 ** Returns
775 **
776 *******************************************************************************/
777 
btif_a2dp_on_init(void)778 void btif_a2dp_on_init(void)
779 {
780     //tput_mon(1, 0, 1);
781 }
782 
783 
784 /*****************************************************************************
785 **
786 ** Function        btif_a2dp_setup_codec
787 **
788 ** Description
789 **
790 ** Returns
791 **
792 *******************************************************************************/
793 
btif_a2dp_setup_codec(void)794 void btif_a2dp_setup_codec(void)
795 {
796     tBTIF_AV_MEDIA_FEEDINGS media_feeding;
797     tBTIF_STATUS status;
798 
799     APPL_TRACE_EVENT("## A2DP SETUP CODEC ##");
800 
801     GKI_disable();
802 
803     /* for now hardcode 44.1 khz 16 bit stereo PCM format */
804     media_feeding.cfg.pcm.sampling_freq = 44100;
805     media_feeding.cfg.pcm.bit_per_sample = 16;
806     media_feeding.cfg.pcm.num_channel = 2;
807     media_feeding.format = BTIF_AV_CODEC_PCM;
808 
809     if (bta_av_co_audio_set_codec(&media_feeding, &status))
810     {
811         tBTIF_MEDIA_INIT_AUDIO_FEEDING mfeed;
812 
813         /* Init the encoding task */
814         btif_a2dp_encoder_init();
815 
816         /* Build the media task configuration */
817         mfeed.feeding = media_feeding;
818         mfeed.feeding_mode = BTIF_AV_FEEDING_ASYNCHRONOUS;
819         /* Send message to Media task to configure transcoding */
820         btif_media_task_audio_feeding_init_req(&mfeed);
821     }
822 
823     GKI_enable();
824 }
825 
826 
827 /*****************************************************************************
828 **
829 ** Function        btif_a2dp_on_idle
830 **
831 ** Description
832 **
833 ** Returns
834 **
835 *******************************************************************************/
836 
btif_a2dp_on_idle(void)837 void btif_a2dp_on_idle(void)
838 {
839     APPL_TRACE_EVENT("## ON A2DP IDLE ##");
840     if (btif_media_cb.peer_sep == AVDT_TSEP_SNK)
841     {
842         /* Make sure media task is stopped */
843         btif_media_task_stop_aa_req();
844     }
845 
846     bta_av_co_init();
847 #if (BTA_AV_SINK_INCLUDED == TRUE)
848     if (btif_media_cb.peer_sep == AVDT_TSEP_SRC)
849     {
850         btif_media_cb.rx_flush = TRUE;
851         btif_media_task_aa_rx_flush_req();
852         btif_media_task_aa_handle_stop_decoding();
853         btif_media_task_clear_track();
854         APPL_TRACE_DEBUG("Stopped BT track");
855     }
856 #endif
857 }
858 
859 /*****************************************************************************
860 **
861 ** Function        btif_a2dp_on_open
862 **
863 ** Description
864 **
865 ** Returns
866 **
867 *******************************************************************************/
868 
btif_a2dp_on_open(void)869 void btif_a2dp_on_open(void)
870 {
871     APPL_TRACE_EVENT("## ON A2DP OPEN ##");
872 
873     /* always use callback to notify socket events */
874     UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
875 }
876 
877 /*******************************************************************************
878  **
879  ** Function         btif_media_task_clear_track
880  **
881  ** Description
882  **
883  ** Returns          TRUE is success
884  **
885  *******************************************************************************/
btif_media_task_clear_track(void)886 BOOLEAN btif_media_task_clear_track(void)
887 {
888     BT_HDR *p_buf;
889 
890     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
891     {
892         return FALSE;
893     }
894 
895     p_buf->event = BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK;
896 
897     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
898     return TRUE;
899 }
900 
901 /*****************************************************************************
902 **
903 ** Function        btif_reset_decoder
904 **
905 ** Description
906 **
907 ** Returns
908 **
909 *******************************************************************************/
910 
btif_reset_decoder(UINT8 * p_av)911 void btif_reset_decoder(UINT8 *p_av)
912 {
913     APPL_TRACE_EVENT("btif_reset_decoder");
914     APPL_TRACE_DEBUG("btif_reset_decoder p_codec_info[%x:%x:%x:%x:%x:%x]",
915             p_av[1], p_av[2], p_av[3],
916             p_av[4], p_av[5], p_av[6]);
917 
918     tBTIF_MEDIA_SINK_CFG_UPDATE *p_buf;
919     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_SINK_CFG_UPDATE))))
920     {
921         APPL_TRACE_EVENT("btif_reset_decoder No Buffer ");
922         return;
923     }
924 
925     memcpy(p_buf->codec_info,p_av, AVDT_CODEC_SIZE);
926     p_buf->hdr.event = BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE;
927 
928     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
929 }
930 
931 /*****************************************************************************
932 **
933 ** Function        btif_a2dp_on_started
934 **
935 ** Description
936 **
937 ** Returns
938 **
939 *******************************************************************************/
940 
btif_a2dp_on_started(tBTA_AV_START * p_av,BOOLEAN pending_start)941 BOOLEAN btif_a2dp_on_started(tBTA_AV_START *p_av, BOOLEAN pending_start)
942 {
943     BOOLEAN ack = FALSE;
944 
945     APPL_TRACE_EVENT("## ON A2DP STARTED ##");
946 
947     if (p_av == NULL)
948     {
949         /* ack back a local start request */
950         a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
951         return TRUE;
952     }
953 
954     if (p_av->status == BTA_AV_SUCCESS)
955     {
956         if (p_av->suspending == FALSE)
957         {
958             if (p_av->initiator)
959             {
960                 if (pending_start) {
961                     a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
962                     ack = TRUE;
963                 }
964             }
965             else
966             {
967                 /* we were remotely started,  make sure codec
968                    is setup before datapath is started */
969                 btif_a2dp_setup_codec();
970             }
971 
972             /* media task is autostarted upon a2dp audiopath connection */
973         }
974     }
975     else if (pending_start)
976     {
977         a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
978         ack = TRUE;
979     }
980     return ack;
981 }
982 
983 
984 /*****************************************************************************
985 **
986 ** Function        btif_a2dp_ack_fail
987 **
988 ** Description
989 **
990 ** Returns
991 **
992 *******************************************************************************/
993 
btif_a2dp_ack_fail(void)994 void btif_a2dp_ack_fail(void)
995 {
996     APPL_TRACE_EVENT("## A2DP_CTRL_ACK_FAILURE ##");
997     a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
998 }
999 
1000 /*****************************************************************************
1001 **
1002 ** Function        btif_a2dp_on_stopped
1003 **
1004 ** Description
1005 **
1006 ** Returns
1007 **
1008 *******************************************************************************/
1009 
btif_a2dp_on_stopped(tBTA_AV_SUSPEND * p_av)1010 void btif_a2dp_on_stopped(tBTA_AV_SUSPEND *p_av)
1011 {
1012     APPL_TRACE_EVENT("## ON A2DP STOPPED ##");
1013     if (btif_media_cb.peer_sep == AVDT_TSEP_SRC) /*  Handling for A2DP SINK cases*/
1014     {
1015         btif_media_cb.rx_flush = TRUE;
1016         btif_media_task_aa_rx_flush_req();
1017         btif_media_task_aa_handle_stop_decoding();
1018         UIPC_Close(UIPC_CH_ID_AV_AUDIO);
1019         btif_media_cb.data_channel_open = FALSE;
1020         return;
1021     }
1022     /* allow using this api for other than suspend */
1023     if (p_av != NULL)
1024     {
1025         if (p_av->status != BTA_AV_SUCCESS)
1026         {
1027             APPL_TRACE_EVENT("AV STOP FAILED (%d)", p_av->status);
1028 
1029             if (p_av->initiator)
1030                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
1031             return;
1032         }
1033     }
1034 
1035     /* ensure tx frames are immediately suspended */
1036     btif_media_cb.tx_flush = 1;
1037 
1038     /* request to stop media task  */
1039     btif_media_task_aa_tx_flush_req();
1040     btif_media_task_stop_aa_req();
1041 
1042     /* once stream is fully stopped we will ack back */
1043 }
1044 
1045 
1046 /*****************************************************************************
1047 **
1048 ** Function        btif_a2dp_on_suspended
1049 **
1050 ** Description
1051 **
1052 ** Returns
1053 **
1054 *******************************************************************************/
1055 
btif_a2dp_on_suspended(tBTA_AV_SUSPEND * p_av)1056 void btif_a2dp_on_suspended(tBTA_AV_SUSPEND *p_av)
1057 {
1058     APPL_TRACE_EVENT("## ON A2DP SUSPENDED ##");
1059     if (btif_media_cb.peer_sep == AVDT_TSEP_SRC)
1060     {
1061         btif_media_cb.rx_flush = TRUE;
1062         btif_media_task_aa_rx_flush_req();
1063         btif_media_task_aa_handle_stop_decoding();
1064         return;
1065     }
1066 
1067     /* check for status failures */
1068     if (p_av->status != BTA_AV_SUCCESS)
1069     {
1070         if (p_av->initiator == TRUE)
1071             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
1072     }
1073 
1074     /* once stream is fully stopped we will ack back */
1075 
1076     /* ensure tx frames are immediately flushed */
1077     btif_media_cb.tx_flush = 1;
1078 
1079     /* stop timer tick */
1080     btif_media_task_stop_aa_req();
1081 }
1082 
1083 /* when true media task discards any rx frames */
btif_a2dp_set_rx_flush(BOOLEAN enable)1084 void btif_a2dp_set_rx_flush(BOOLEAN enable)
1085 {
1086     APPL_TRACE_EVENT("## DROP RX %d ##", enable);
1087     btif_media_cb.rx_flush = enable;
1088 }
1089 
1090 /* when true media task discards any tx frames */
btif_a2dp_set_tx_flush(BOOLEAN enable)1091 void btif_a2dp_set_tx_flush(BOOLEAN enable)
1092 {
1093     APPL_TRACE_EVENT("## DROP TX %d ##", enable);
1094     btif_media_cb.tx_flush = enable;
1095 }
1096 
1097 #if (BTA_AV_SINK_INCLUDED == TRUE)
btif_media_task_avk_handle_timer(UNUSED_ATTR void * context)1098 static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context)
1099 {
1100     UINT8 count;
1101     tBT_SBC_HDR *p_msg;
1102     int num_sbc_frames;
1103     int num_frames_to_process;
1104 
1105     count = btif_media_cb.RxSbcQ._count;
1106     if (0 == count)
1107     {
1108         APPL_TRACE_DEBUG("  QUE  EMPTY ");
1109     }
1110     else
1111     {
1112         if (btif_media_cb.rx_flush == TRUE)
1113         {
1114             btif_media_flush_q(&(btif_media_cb.RxSbcQ));
1115             return;
1116         }
1117 
1118         num_frames_to_process = btif_media_cb.frames_to_process;
1119         APPL_TRACE_DEBUG(" Process Frames + ");
1120 
1121         do
1122         {
1123             p_msg = (tBT_SBC_HDR *)GKI_getfirst(&(btif_media_cb.RxSbcQ));
1124             if (p_msg == NULL)
1125                 return;
1126             num_sbc_frames  = p_msg->num_frames_to_be_processed; /* num of frames in Que Packets */
1127             APPL_TRACE_DEBUG(" Frames left in topmost packet %d", num_sbc_frames);
1128             APPL_TRACE_DEBUG(" Remaining frames to process in tick %d", num_frames_to_process);
1129             APPL_TRACE_DEBUG(" Num of Packets in Que %d", btif_media_cb.RxSbcQ._count);
1130 
1131             if ( num_sbc_frames > num_frames_to_process) /*  Que Packet has more frames*/
1132             {
1133                  p_msg->num_frames_to_be_processed= num_frames_to_process;
1134                  btif_media_task_handle_inc_media(p_msg);
1135                  p_msg->num_frames_to_be_processed = num_sbc_frames - num_frames_to_process;
1136                  num_frames_to_process = 0;
1137                  break;
1138             }
1139             else                                        /*  Que packet has less frames */
1140             {
1141                 btif_media_task_handle_inc_media(p_msg);
1142                 p_msg = (tBT_SBC_HDR *)GKI_dequeue(&(btif_media_cb.RxSbcQ));
1143                 if( p_msg == NULL )
1144                 {
1145                      APPL_TRACE_ERROR("Insufficient data in que ");
1146                      break;
1147                 }
1148                 num_frames_to_process = num_frames_to_process - p_msg->num_frames_to_be_processed;
1149                 GKI_freebuf(p_msg);
1150             }
1151         }while(num_frames_to_process > 0);
1152 
1153         APPL_TRACE_DEBUG(" Process Frames - ");
1154     }
1155 }
1156 #else
btif_media_task_avk_handle_timer(UNUSED_ATTR void * context)1157 static void btif_media_task_avk_handle_timer(UNUSED_ATTR void *context) {}
1158 #endif
1159 
btif_media_task_aa_handle_timer(UNUSED_ATTR void * context)1160 static void btif_media_task_aa_handle_timer(UNUSED_ATTR void *context)
1161 {
1162     log_tstamps_us("media task tx timer");
1163 
1164 #if (BTA_AV_INCLUDED == TRUE)
1165     if(btif_media_cb.is_tx_timer == TRUE)
1166     {
1167         btif_media_send_aa_frame();
1168     }
1169     else
1170     {
1171         APPL_TRACE_ERROR("ERROR Media task Scheduled after Suspend");
1172     }
1173 #endif
1174 }
1175 
1176 #if (BTA_AV_INCLUDED == TRUE)
btif_media_task_aa_handle_uipc_rx_rdy(void)1177 static void btif_media_task_aa_handle_uipc_rx_rdy(void)
1178 {
1179     /* process all the UIPC data */
1180     btif_media_aa_prep_2_send(0xFF);
1181 
1182     /* send it */
1183     LOG_VERBOSE("btif_media_task_aa_handle_uipc_rx_rdy calls bta_av_ci_src_data_ready");
1184     bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
1185 }
1186 #endif
1187 
btif_media_thread_init(UNUSED_ATTR void * context)1188 static void btif_media_thread_init(UNUSED_ATTR void *context) {
1189   memset(&btif_media_cb, 0, sizeof(btif_media_cb));
1190   UIPC_Init(NULL);
1191 
1192 #if (BTA_AV_INCLUDED == TRUE)
1193   UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
1194 #endif
1195 
1196   raise_priority_a2dp(TASK_HIGH_MEDIA);
1197   media_task_running = MEDIA_TASK_STATE_ON;
1198 }
1199 
btif_media_thread_cleanup(UNUSED_ATTR void * context)1200 static void btif_media_thread_cleanup(UNUSED_ATTR void *context) {
1201   /* make sure no channels are restarted while shutting down */
1202   media_task_running = MEDIA_TASK_STATE_SHUTTING_DOWN;
1203 
1204   /* this calls blocks until uipc is fully closed */
1205   UIPC_Close(UIPC_CH_ID_ALL);
1206 
1207   /* Clear media task flag */
1208   media_task_running = MEDIA_TASK_STATE_OFF;
1209 }
1210 
1211 /*******************************************************************************
1212  **
1213  ** Function         btif_media_task_send_cmd_evt
1214  **
1215  ** Description
1216  **
1217  ** Returns          TRUE is success
1218  **
1219  *******************************************************************************/
btif_media_task_send_cmd_evt(UINT16 Evt)1220 BOOLEAN btif_media_task_send_cmd_evt(UINT16 Evt)
1221 {
1222     BT_HDR *p_buf;
1223     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1224     {
1225         return FALSE;
1226     }
1227 
1228     p_buf->event = Evt;
1229 
1230     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1231     return TRUE;
1232 }
1233 
1234 /*******************************************************************************
1235  **
1236  ** Function         btif_media_flush_q
1237  **
1238  ** Description
1239  **
1240  ** Returns          void
1241  **
1242  *******************************************************************************/
btif_media_flush_q(BUFFER_Q * p_q)1243 static void btif_media_flush_q(BUFFER_Q *p_q)
1244 {
1245     while (!GKI_queue_is_empty(p_q))
1246     {
1247         GKI_freebuf(GKI_dequeue(p_q));
1248     }
1249 }
1250 
btif_media_thread_handle_cmd(fixed_queue_t * queue,UNUSED_ATTR void * context)1251 static void btif_media_thread_handle_cmd(fixed_queue_t *queue, UNUSED_ATTR void *context)
1252 {
1253     BT_HDR *p_msg = (BT_HDR *)fixed_queue_dequeue(queue);
1254     LOG_VERBOSE("btif_media_thread_handle_cmd : %d %s", p_msg->event,
1255              dump_media_event(p_msg->event));
1256 
1257     switch (p_msg->event)
1258     {
1259 #if (BTA_AV_INCLUDED == TRUE)
1260     case BTIF_MEDIA_START_AA_TX:
1261         btif_media_task_aa_start_tx();
1262         break;
1263     case BTIF_MEDIA_STOP_AA_TX:
1264         btif_media_task_aa_stop_tx();
1265         break;
1266     case BTIF_MEDIA_SBC_ENC_INIT:
1267         btif_media_task_enc_init(p_msg);
1268         break;
1269     case BTIF_MEDIA_SBC_ENC_UPDATE:
1270         btif_media_task_enc_update(p_msg);
1271         break;
1272     case BTIF_MEDIA_AUDIO_FEEDING_INIT:
1273         btif_media_task_audio_feeding_init(p_msg);
1274         break;
1275     case BTIF_MEDIA_FLUSH_AA_TX:
1276         btif_media_task_aa_tx_flush(p_msg);
1277         break;
1278     case BTIF_MEDIA_UIPC_RX_RDY:
1279         btif_media_task_aa_handle_uipc_rx_rdy();
1280         break;
1281     case BTIF_MEDIA_AUDIO_SINK_CFG_UPDATE:
1282 #if (BTA_AV_SINK_INCLUDED == TRUE)
1283         btif_media_task_aa_handle_decoder_reset(p_msg);
1284 #endif
1285         break;
1286     case BTIF_MEDIA_AUDIO_SINK_CLEAR_TRACK:
1287 #if (BTA_AV_SINK_INCLUDED == TRUE)
1288         btif_media_task_aa_handle_clear_track();
1289 #endif
1290         break;
1291      case BTIF_MEDIA_FLUSH_AA_RX:
1292         btif_media_task_aa_rx_flush();
1293         break;
1294 #endif
1295     default:
1296         APPL_TRACE_ERROR("ERROR in %s unknown event %d", __func__, p_msg->event);
1297     }
1298     GKI_freebuf(p_msg);
1299     LOG_VERBOSE("%s: %s DONE", __func__, dump_media_event(p_msg->event));
1300 }
1301 
1302 #if (BTA_AV_SINK_INCLUDED == TRUE)
1303 /*******************************************************************************
1304  **
1305  ** Function         btif_media_task_handle_inc_media
1306  **
1307  ** Description
1308  **
1309  ** Returns          void
1310  **
1311  *******************************************************************************/
btif_media_task_handle_inc_media(tBT_SBC_HDR * p_msg)1312 static void btif_media_task_handle_inc_media(tBT_SBC_HDR*p_msg)
1313 {
1314     UINT8 *sbc_start_frame = ((UINT8*)(p_msg + 1) + p_msg->offset + 1);
1315     int count;
1316     UINT32 pcmBytes, availPcmBytes;
1317     OI_INT16 *pcmDataPointer = pcmData; /*Will be overwritten on next packet receipt*/
1318     OI_STATUS status;
1319     int num_sbc_frames = p_msg->num_frames_to_be_processed;
1320     UINT32 sbc_frame_len = p_msg->len - 1;
1321     availPcmBytes = 2*sizeof(pcmData);
1322 
1323     if ((btif_media_cb.peer_sep == AVDT_TSEP_SNK) || (btif_media_cb.rx_flush))
1324     {
1325         APPL_TRACE_DEBUG(" State Changed happened in this tick ");
1326         return;
1327     }
1328 
1329     // ignore data if no one is listening
1330     if (!btif_media_cb.data_channel_open)
1331         return;
1332 
1333     APPL_TRACE_DEBUG("Number of sbc frames %d, frame_len %d", num_sbc_frames, sbc_frame_len);
1334 
1335     for(count = 0; count < num_sbc_frames && sbc_frame_len != 0; count ++)
1336     {
1337         pcmBytes = availPcmBytes;
1338         status = OI_CODEC_SBC_DecodeFrame(&context, (const OI_BYTE**)&sbc_start_frame,
1339                                                         (OI_UINT32 *)&sbc_frame_len,
1340                                                         (OI_INT16 *)pcmDataPointer,
1341                                                         (OI_UINT32 *)&pcmBytes);
1342         if (!OI_SUCCESS(status)) {
1343             APPL_TRACE_ERROR("Decoding failure: %d\n", status);
1344             break;
1345         }
1346         availPcmBytes -= pcmBytes;
1347         pcmDataPointer += pcmBytes/2;
1348         p_msg->offset += (p_msg->len - 1) - sbc_frame_len;
1349         p_msg->len = sbc_frame_len + 1;
1350     }
1351 
1352     UIPC_Send(UIPC_CH_ID_AV_AUDIO, 0, (UINT8 *)pcmData, (2*sizeof(pcmData) - availPcmBytes));
1353 }
1354 #endif
1355 
1356 #if (BTA_AV_INCLUDED == TRUE)
1357 /*******************************************************************************
1358  **
1359  ** Function         btif_media_task_enc_init_req
1360  **
1361  ** Description
1362  **
1363  ** Returns          TRUE is success
1364  **
1365  *******************************************************************************/
btif_media_task_enc_init_req(tBTIF_MEDIA_INIT_AUDIO * p_msg)1366 BOOLEAN btif_media_task_enc_init_req(tBTIF_MEDIA_INIT_AUDIO *p_msg)
1367 {
1368     tBTIF_MEDIA_INIT_AUDIO *p_buf;
1369     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_INIT_AUDIO))))
1370     {
1371         return FALSE;
1372     }
1373 
1374     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO));
1375     p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_INIT;
1376 
1377     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1378     return TRUE;
1379 }
1380 
1381 /*******************************************************************************
1382  **
1383  ** Function         btif_media_task_enc_update_req
1384  **
1385  ** Description
1386  **
1387  ** Returns          TRUE is success
1388  **
1389  *******************************************************************************/
btif_media_task_enc_update_req(tBTIF_MEDIA_UPDATE_AUDIO * p_msg)1390 BOOLEAN btif_media_task_enc_update_req(tBTIF_MEDIA_UPDATE_AUDIO *p_msg)
1391 {
1392     tBTIF_MEDIA_UPDATE_AUDIO *p_buf;
1393     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_UPDATE_AUDIO))))
1394     {
1395         return FALSE;
1396     }
1397 
1398     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_UPDATE_AUDIO));
1399     p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_UPDATE;
1400 
1401     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1402     return TRUE;
1403 }
1404 
1405 /*******************************************************************************
1406  **
1407  ** Function         btif_media_task_audio_feeding_init_req
1408  **
1409  ** Description
1410  **
1411  ** Returns          TRUE is success
1412  **
1413  *******************************************************************************/
btif_media_task_audio_feeding_init_req(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_msg)1414 BOOLEAN btif_media_task_audio_feeding_init_req(tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_msg)
1415 {
1416     tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_buf;
1417     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING))))
1418     {
1419         return FALSE;
1420     }
1421 
1422     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING));
1423     p_buf->hdr.event = BTIF_MEDIA_AUDIO_FEEDING_INIT;
1424 
1425     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1426     return TRUE;
1427 }
1428 
1429 /*******************************************************************************
1430  **
1431  ** Function         btif_media_task_start_aa_req
1432  **
1433  ** Description
1434  **
1435  ** Returns          TRUE is success
1436  **
1437  *******************************************************************************/
btif_media_task_start_aa_req(void)1438 BOOLEAN btif_media_task_start_aa_req(void)
1439 {
1440     BT_HDR *p_buf;
1441     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1442     {
1443         APPL_TRACE_EVENT("GKI failed");
1444         return FALSE;
1445     }
1446 
1447     p_buf->event = BTIF_MEDIA_START_AA_TX;
1448 
1449     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1450     return TRUE;
1451 }
1452 
1453 /*******************************************************************************
1454  **
1455  ** Function         btif_media_task_stop_aa_req
1456  **
1457  ** Description
1458  **
1459  ** Returns          TRUE is success
1460  **
1461  *******************************************************************************/
btif_media_task_stop_aa_req(void)1462 BOOLEAN btif_media_task_stop_aa_req(void)
1463 {
1464     BT_HDR *p_buf;
1465     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1466     {
1467         return FALSE;
1468     }
1469 
1470     p_buf->event = BTIF_MEDIA_STOP_AA_TX;
1471 
1472     /*
1473      * Explicitly check whether the btif_media_cmd_msg_queue is not NULL to
1474      * avoid a race condition during shutdown of the Bluetooth stack.
1475      * This race condition is triggered when A2DP audio is streaming on
1476      * shutdown:
1477      * "btif_a2dp_on_stopped() -> btif_media_task_stop_aa_req()" is called
1478      * to stop the particular audio stream, and this happens right after
1479      * the "cleanup() -> btif_a2dp_stop_media_task()" processing during
1480      * the shutdown of the Bluetooth stack.
1481      */
1482     if (btif_media_cmd_msg_queue != NULL)
1483         fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1484 
1485     return TRUE;
1486 }
1487 /*******************************************************************************
1488  **
1489  ** Function         btif_media_task_aa_rx_flush_req
1490  **
1491  ** Description
1492  **
1493  ** Returns          TRUE is success
1494  **
1495  *******************************************************************************/
btif_media_task_aa_rx_flush_req(void)1496 BOOLEAN btif_media_task_aa_rx_flush_req(void)
1497 {
1498     BT_HDR *p_buf;
1499 
1500     if (GKI_queue_is_empty(&(btif_media_cb.RxSbcQ))== TRUE) /*  Que is already empty */
1501         return TRUE;
1502 
1503     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1504     {
1505         return FALSE;
1506     }
1507 
1508     p_buf->event = BTIF_MEDIA_FLUSH_AA_RX;
1509 
1510     fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1511     return TRUE;
1512 }
1513 
1514 /*******************************************************************************
1515  **
1516  ** Function         btif_media_task_aa_tx_flush_req
1517  **
1518  ** Description
1519  **
1520  ** Returns          TRUE is success
1521  **
1522  *******************************************************************************/
btif_media_task_aa_tx_flush_req(void)1523 BOOLEAN btif_media_task_aa_tx_flush_req(void)
1524 {
1525     BT_HDR *p_buf = GKI_getbuf(sizeof(BT_HDR));
1526 
1527     if (p_buf == NULL)
1528         return FALSE;
1529 
1530     p_buf->event = BTIF_MEDIA_FLUSH_AA_TX;
1531 
1532     /*
1533      * Explicitly check whether the btif_media_cmd_msg_queue is not NULL to
1534      * avoid a race condition during shutdown of the Bluetooth stack.
1535      * This race condition is triggered when A2DP audio is streaming on
1536      * shutdown:
1537      * "btif_a2dp_on_stopped() -> btif_media_task_aa_tx_flush_req()" is called
1538      * to stop the particular audio stream, and this happens right after
1539      * the "cleanup() -> btif_a2dp_stop_media_task()" processing during
1540      * the shutdown of the Bluetooth stack.
1541      */
1542     if (btif_media_cmd_msg_queue != NULL)
1543         fixed_queue_enqueue(btif_media_cmd_msg_queue, p_buf);
1544 
1545     return TRUE;
1546 }
1547 /*******************************************************************************
1548  **
1549  ** Function         btif_media_task_aa_rx_flush
1550  **
1551  ** Description
1552  **
1553  ** Returns          void
1554  **
1555  *******************************************************************************/
btif_media_task_aa_rx_flush(void)1556 static void btif_media_task_aa_rx_flush(void)
1557 {
1558     /* Flush all enqueued GKI SBC  buffers (encoded) */
1559     APPL_TRACE_DEBUG("btif_media_task_aa_rx_flush");
1560 
1561     btif_media_flush_q(&(btif_media_cb.RxSbcQ));
1562 }
1563 
1564 
1565 /*******************************************************************************
1566  **
1567  ** Function         btif_media_task_aa_tx_flush
1568  **
1569  ** Description
1570  **
1571  ** Returns          void
1572  **
1573  *******************************************************************************/
btif_media_task_aa_tx_flush(BT_HDR * p_msg)1574 static void btif_media_task_aa_tx_flush(BT_HDR *p_msg)
1575 {
1576     UNUSED(p_msg);
1577 
1578     /* Flush all enqueued GKI music buffers (encoded) */
1579     APPL_TRACE_DEBUG("btif_media_task_aa_tx_flush");
1580 
1581     btif_media_cb.media_feeding_state.pcm.counter = 0;
1582     btif_media_cb.media_feeding_state.pcm.aa_feed_residue = 0;
1583 
1584     btif_media_flush_q(&(btif_media_cb.TxAaQ));
1585 
1586     UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REQ_RX_FLUSH, NULL);
1587 }
1588 
1589 /*******************************************************************************
1590  **
1591  ** Function       btif_media_task_enc_init
1592  **
1593  ** Description    Initialize encoding task
1594  **
1595  ** Returns        void
1596  **
1597  *******************************************************************************/
btif_media_task_enc_init(BT_HDR * p_msg)1598 static void btif_media_task_enc_init(BT_HDR *p_msg)
1599 {
1600     tBTIF_MEDIA_INIT_AUDIO *pInitAudio = (tBTIF_MEDIA_INIT_AUDIO *) p_msg;
1601 
1602     APPL_TRACE_DEBUG("btif_media_task_enc_init");
1603 
1604     btif_media_cb.timestamp = 0;
1605 
1606     /* SBC encoder config (enforced even if not used) */
1607     btif_media_cb.encoder.s16ChannelMode = pInitAudio->ChannelMode;
1608     btif_media_cb.encoder.s16NumOfSubBands = pInitAudio->NumOfSubBands;
1609     btif_media_cb.encoder.s16NumOfBlocks = pInitAudio->NumOfBlocks;
1610     btif_media_cb.encoder.s16AllocationMethod = pInitAudio->AllocationMethod;
1611     btif_media_cb.encoder.s16SamplingFreq = pInitAudio->SamplingFreq;
1612 
1613     btif_media_cb.encoder.u16BitRate = btif_media_task_get_sbc_rate();
1614 
1615     /* Default transcoding is PCM to SBC, modified by feeding configuration */
1616     btif_media_cb.TxTranscoding = BTIF_MEDIA_TRSCD_PCM_2_SBC;
1617     btif_media_cb.TxAaMtuSize = ((BTIF_MEDIA_AA_BUF_SIZE-BTIF_MEDIA_AA_SBC_OFFSET-sizeof(BT_HDR))
1618             < pInitAudio->MtuSize) ? (BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET
1619             - sizeof(BT_HDR)) : pInitAudio->MtuSize;
1620 
1621     APPL_TRACE_EVENT("btif_media_task_enc_init busy %d, mtu %d, peer mtu %d",
1622                      btif_media_cb.busy_level, btif_media_cb.TxAaMtuSize, pInitAudio->MtuSize);
1623     APPL_TRACE_EVENT("      ch mode %d, subnd %d, nb blk %d, alloc %d, rate %d, freq %d",
1624             btif_media_cb.encoder.s16ChannelMode, btif_media_cb.encoder.s16NumOfSubBands,
1625             btif_media_cb.encoder.s16NumOfBlocks,
1626             btif_media_cb.encoder.s16AllocationMethod, btif_media_cb.encoder.u16BitRate,
1627             btif_media_cb.encoder.s16SamplingFreq);
1628 
1629     /* Reset entirely the SBC encoder */
1630     SBC_Encoder_Init(&(btif_media_cb.encoder));
1631     APPL_TRACE_DEBUG("btif_media_task_enc_init bit pool %d", btif_media_cb.encoder.s16BitPool);
1632 }
1633 
1634 /*******************************************************************************
1635  **
1636  ** Function       btif_media_task_enc_update
1637  **
1638  ** Description    Update encoding task
1639  **
1640  ** Returns        void
1641  **
1642  *******************************************************************************/
1643 
btif_media_task_enc_update(BT_HDR * p_msg)1644 static void btif_media_task_enc_update(BT_HDR *p_msg)
1645 {
1646     tBTIF_MEDIA_UPDATE_AUDIO * pUpdateAudio = (tBTIF_MEDIA_UPDATE_AUDIO *) p_msg;
1647     SBC_ENC_PARAMS *pstrEncParams = &btif_media_cb.encoder;
1648     UINT16 s16SamplingFreq;
1649     SINT16 s16BitPool = 0;
1650     SINT16 s16BitRate;
1651     SINT16 s16FrameLen;
1652     UINT8 protect = 0;
1653 
1654     APPL_TRACE_DEBUG("btif_media_task_enc_update : minmtu %d, maxbp %d minbp %d",
1655             pUpdateAudio->MinMtuSize, pUpdateAudio->MaxBitPool, pUpdateAudio->MinBitPool);
1656 
1657     /* Only update the bitrate and MTU size while timer is running to make sure it has been initialized */
1658     //if (btif_media_cb.is_tx_timer)
1659     {
1660         btif_media_cb.TxAaMtuSize = ((BTIF_MEDIA_AA_BUF_SIZE -
1661                                       BTIF_MEDIA_AA_SBC_OFFSET - sizeof(BT_HDR))
1662                 < pUpdateAudio->MinMtuSize) ? (BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET
1663                 - sizeof(BT_HDR)) : pUpdateAudio->MinMtuSize;
1664 
1665         /* Set the initial target bit rate */
1666         pstrEncParams->u16BitRate = btif_media_task_get_sbc_rate();
1667 
1668         if (pstrEncParams->s16SamplingFreq == SBC_sf16000)
1669             s16SamplingFreq = 16000;
1670         else if (pstrEncParams->s16SamplingFreq == SBC_sf32000)
1671             s16SamplingFreq = 32000;
1672         else if (pstrEncParams->s16SamplingFreq == SBC_sf44100)
1673             s16SamplingFreq = 44100;
1674         else
1675             s16SamplingFreq = 48000;
1676 
1677         do
1678         {
1679             if (pstrEncParams->s16NumOfBlocks == 0 || pstrEncParams->s16NumOfSubBands == 0
1680                 || pstrEncParams->s16NumOfChannels == 0)
1681             {
1682                 APPL_TRACE_ERROR("btif_media_task_enc_update() - Avoiding division by zero...");
1683                 APPL_TRACE_ERROR("btif_media_task_enc_update() - block=%d, subBands=%d, channels=%d",
1684                     pstrEncParams->s16NumOfBlocks, pstrEncParams->s16NumOfSubBands,
1685                     pstrEncParams->s16NumOfChannels);
1686                 break;
1687             }
1688 
1689             if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) ||
1690                 (pstrEncParams->s16ChannelMode == SBC_STEREO) )
1691             {
1692                 s16BitPool = (SINT16)( (pstrEncParams->u16BitRate *
1693                     pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq)
1694                     -( (32 + (4 * pstrEncParams->s16NumOfSubBands *
1695                     pstrEncParams->s16NumOfChannels)
1696                     + ( (pstrEncParams->s16ChannelMode - 2) *
1697                     pstrEncParams->s16NumOfSubBands )   )
1698                     / pstrEncParams->s16NumOfBlocks) );
1699 
1700                 s16FrameLen = 4 + (4*pstrEncParams->s16NumOfSubBands*
1701                     pstrEncParams->s16NumOfChannels)/8
1702                     + ( ((pstrEncParams->s16ChannelMode - 2) *
1703                     pstrEncParams->s16NumOfSubBands)
1704                     + (pstrEncParams->s16NumOfBlocks * s16BitPool) ) / 8;
1705 
1706                 s16BitRate = (8 * s16FrameLen * s16SamplingFreq)
1707                     / (pstrEncParams->s16NumOfSubBands *
1708                     pstrEncParams->s16NumOfBlocks * 1000);
1709 
1710                 if (s16BitRate > pstrEncParams->u16BitRate)
1711                     s16BitPool--;
1712 
1713                 if(pstrEncParams->s16NumOfSubBands == 8)
1714                     s16BitPool = (s16BitPool > 255) ? 255 : s16BitPool;
1715                 else
1716                     s16BitPool = (s16BitPool > 128) ? 128 : s16BitPool;
1717             }
1718             else
1719             {
1720                 s16BitPool = (SINT16)( ((pstrEncParams->s16NumOfSubBands *
1721                     pstrEncParams->u16BitRate * 1000)
1722                     / (s16SamplingFreq * pstrEncParams->s16NumOfChannels))
1723                     -( ( (32 / pstrEncParams->s16NumOfChannels) +
1724                     (4 * pstrEncParams->s16NumOfSubBands) )
1725                     /   pstrEncParams->s16NumOfBlocks ) );
1726 
1727                 pstrEncParams->s16BitPool = (s16BitPool >
1728                     (16 * pstrEncParams->s16NumOfSubBands))
1729                     ? (16*pstrEncParams->s16NumOfSubBands) : s16BitPool;
1730             }
1731 
1732             if (s16BitPool < 0)
1733             {
1734                 s16BitPool = 0;
1735             }
1736 
1737             APPL_TRACE_EVENT("bitpool candidate : %d (%d kbps)",
1738                          s16BitPool, pstrEncParams->u16BitRate);
1739 
1740             if (s16BitPool > pUpdateAudio->MaxBitPool)
1741             {
1742                 APPL_TRACE_DEBUG("btif_media_task_enc_update computed bitpool too large (%d)",
1743                                     s16BitPool);
1744                 /* Decrease bitrate */
1745                 btif_media_cb.encoder.u16BitRate -= BTIF_MEDIA_BITRATE_STEP;
1746                 /* Record that we have decreased the bitrate */
1747                 protect |= 1;
1748             }
1749             else if (s16BitPool < pUpdateAudio->MinBitPool)
1750             {
1751                 APPL_TRACE_WARNING("btif_media_task_enc_update computed bitpool too small (%d)", s16BitPool);
1752 
1753                 /* Increase bitrate */
1754                 UINT16 previous_u16BitRate = btif_media_cb.encoder.u16BitRate;
1755                 btif_media_cb.encoder.u16BitRate += BTIF_MEDIA_BITRATE_STEP;
1756                 /* Record that we have increased the bitrate */
1757                 protect |= 2;
1758                 /* Check over-flow */
1759                 if (btif_media_cb.encoder.u16BitRate < previous_u16BitRate)
1760                     protect |= 3;
1761             }
1762             else
1763             {
1764                 break;
1765             }
1766             /* In case we have already increased and decreased the bitrate, just stop */
1767             if (protect == 3)
1768             {
1769                 APPL_TRACE_ERROR("btif_media_task_enc_update could not find bitpool in range");
1770                 break;
1771             }
1772         } while (1);
1773 
1774         /* Finally update the bitpool in the encoder structure */
1775         pstrEncParams->s16BitPool = s16BitPool;
1776 
1777         APPL_TRACE_DEBUG("btif_media_task_enc_update final bit rate %d, final bit pool %d",
1778                 btif_media_cb.encoder.u16BitRate, btif_media_cb.encoder.s16BitPool);
1779 
1780         /* make sure we reinitialize encoder with new settings */
1781         SBC_Encoder_Init(&(btif_media_cb.encoder));
1782     }
1783 }
1784 
1785 /*******************************************************************************
1786  **
1787  ** Function         btif_media_task_pcm2sbc_init
1788  **
1789  ** Description      Init encoding task for PCM to SBC according to feeding
1790  **
1791  ** Returns          void
1792  **
1793  *******************************************************************************/
btif_media_task_pcm2sbc_init(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_feeding)1794 static void btif_media_task_pcm2sbc_init(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_feeding)
1795 {
1796     BOOLEAN reconfig_needed = FALSE;
1797 
1798     APPL_TRACE_DEBUG("PCM feeding:");
1799     APPL_TRACE_DEBUG("sampling_freq:%d", p_feeding->feeding.cfg.pcm.sampling_freq);
1800     APPL_TRACE_DEBUG("num_channel:%d", p_feeding->feeding.cfg.pcm.num_channel);
1801     APPL_TRACE_DEBUG("bit_per_sample:%d", p_feeding->feeding.cfg.pcm.bit_per_sample);
1802 
1803     /* Check the PCM feeding sampling_freq */
1804     switch (p_feeding->feeding.cfg.pcm.sampling_freq)
1805     {
1806         case  8000:
1807         case 12000:
1808         case 16000:
1809         case 24000:
1810         case 32000:
1811         case 48000:
1812             /* For these sampling_freq the AV connection must be 48000 */
1813             if (btif_media_cb.encoder.s16SamplingFreq != SBC_sf48000)
1814             {
1815                 /* Reconfiguration needed at 48000 */
1816                 APPL_TRACE_DEBUG("SBC Reconfiguration needed at 48000");
1817                 btif_media_cb.encoder.s16SamplingFreq = SBC_sf48000;
1818                 reconfig_needed = TRUE;
1819             }
1820             break;
1821 
1822         case 11025:
1823         case 22050:
1824         case 44100:
1825             /* For these sampling_freq the AV connection must be 44100 */
1826             if (btif_media_cb.encoder.s16SamplingFreq != SBC_sf44100)
1827             {
1828                 /* Reconfiguration needed at 44100 */
1829                 APPL_TRACE_DEBUG("SBC Reconfiguration needed at 44100");
1830                 btif_media_cb.encoder.s16SamplingFreq = SBC_sf44100;
1831                 reconfig_needed = TRUE;
1832             }
1833             break;
1834         default:
1835             APPL_TRACE_DEBUG("Feeding PCM sampling_freq unsupported");
1836             break;
1837     }
1838 
1839     /* Some AV Headsets do not support Mono => always ask for Stereo */
1840     if (btif_media_cb.encoder.s16ChannelMode == SBC_MONO)
1841     {
1842         APPL_TRACE_DEBUG("SBC Reconfiguration needed in Stereo");
1843         btif_media_cb.encoder.s16ChannelMode = SBC_JOINT_STEREO;
1844         reconfig_needed = TRUE;
1845     }
1846 
1847     if (reconfig_needed != FALSE)
1848     {
1849         APPL_TRACE_DEBUG("btif_media_task_pcm2sbc_init :: mtu %d", btif_media_cb.TxAaMtuSize);
1850         APPL_TRACE_DEBUG("ch mode %d, nbsubd %d, nb %d, alloc %d, rate %d, freq %d",
1851                 btif_media_cb.encoder.s16ChannelMode,
1852                 btif_media_cb.encoder.s16NumOfSubBands, btif_media_cb.encoder.s16NumOfBlocks,
1853                 btif_media_cb.encoder.s16AllocationMethod, btif_media_cb.encoder.u16BitRate,
1854                 btif_media_cb.encoder.s16SamplingFreq);
1855 
1856         SBC_Encoder_Init(&(btif_media_cb.encoder));
1857     }
1858     else
1859     {
1860         APPL_TRACE_DEBUG("btif_media_task_pcm2sbc_init no SBC reconfig needed");
1861     }
1862 }
1863 
1864 
1865 /*******************************************************************************
1866  **
1867  ** Function         btif_media_task_audio_feeding_init
1868  **
1869  ** Description      Initialize the audio path according to the feeding format
1870  **
1871  ** Returns          void
1872  **
1873  *******************************************************************************/
btif_media_task_audio_feeding_init(BT_HDR * p_msg)1874 static void btif_media_task_audio_feeding_init(BT_HDR *p_msg)
1875 {
1876     tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_feeding = (tBTIF_MEDIA_INIT_AUDIO_FEEDING *) p_msg;
1877 
1878     APPL_TRACE_DEBUG("btif_media_task_audio_feeding_init format:%d", p_feeding->feeding.format);
1879 
1880     /* Save Media Feeding information */
1881     btif_media_cb.feeding_mode = p_feeding->feeding_mode;
1882     btif_media_cb.media_feeding = p_feeding->feeding;
1883 
1884     /* Handle different feeding formats */
1885     switch (p_feeding->feeding.format)
1886     {
1887         case BTIF_AV_CODEC_PCM:
1888             btif_media_cb.TxTranscoding = BTIF_MEDIA_TRSCD_PCM_2_SBC;
1889             btif_media_task_pcm2sbc_init(p_feeding);
1890             break;
1891 
1892         default :
1893             APPL_TRACE_ERROR("unknown feeding format %d", p_feeding->feeding.format);
1894             break;
1895     }
1896 }
1897 
btif_a2dp_get_track_frequency(UINT8 frequency)1898 int btif_a2dp_get_track_frequency(UINT8 frequency) {
1899     int freq = 48000;
1900     switch (frequency) {
1901         case A2D_SBC_IE_SAMP_FREQ_16:
1902             freq = 16000;
1903             break;
1904         case A2D_SBC_IE_SAMP_FREQ_32:
1905             freq = 32000;
1906             break;
1907         case A2D_SBC_IE_SAMP_FREQ_44:
1908             freq = 44100;
1909             break;
1910         case A2D_SBC_IE_SAMP_FREQ_48:
1911             freq = 48000;
1912             break;
1913     }
1914     return freq;
1915 }
1916 
btif_a2dp_get_track_channel_count(UINT8 channeltype)1917 int btif_a2dp_get_track_channel_count(UINT8 channeltype) {
1918     int count = 1;
1919     switch (channeltype) {
1920         case A2D_SBC_IE_CH_MD_MONO:
1921             count = 1;
1922             break;
1923         case A2D_SBC_IE_CH_MD_DUAL:
1924         case A2D_SBC_IE_CH_MD_STEREO:
1925         case A2D_SBC_IE_CH_MD_JOINT:
1926             count = 2;
1927             break;
1928     }
1929     return count;
1930 }
1931 
btif_a2dp_set_peer_sep(UINT8 sep)1932 void btif_a2dp_set_peer_sep(UINT8 sep) {
1933     btif_media_cb.peer_sep = sep;
1934 }
1935 
btif_decode_alarm_cb(UNUSED_ATTR void * context)1936 static void btif_decode_alarm_cb(UNUSED_ATTR void *context) {
1937   thread_post(worker_thread, btif_media_task_avk_handle_timer, NULL);
1938 }
1939 
btif_media_task_aa_handle_stop_decoding(void)1940 static void btif_media_task_aa_handle_stop_decoding(void) {
1941   alarm_free(btif_media_cb.decode_alarm);
1942   btif_media_cb.decode_alarm = NULL;
1943 }
1944 
btif_media_task_aa_handle_start_decoding(void)1945 static void btif_media_task_aa_handle_start_decoding(void) {
1946   if (btif_media_cb.decode_alarm)
1947     return;
1948 
1949   btif_media_cb.decode_alarm = alarm_new();
1950   if (!btif_media_cb.decode_alarm) {
1951     LOG_ERROR("%s unable to allocate decode alarm.", __func__);
1952     return;
1953   }
1954 
1955   alarm_set_periodic(btif_media_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK, btif_decode_alarm_cb, NULL);
1956 }
1957 
1958 #if (BTA_AV_SINK_INCLUDED == TRUE)
1959 
btif_media_task_aa_handle_clear_track(void)1960 static void btif_media_task_aa_handle_clear_track (void)
1961 {
1962     APPL_TRACE_DEBUG("btif_media_task_aa_handle_clear_track");
1963 }
1964 
1965 /*******************************************************************************
1966  **
1967  ** Function         btif_media_task_aa_handle_decoder_reset
1968  **
1969  ** Description
1970  **
1971  ** Returns          void
1972  **
1973  *******************************************************************************/
btif_media_task_aa_handle_decoder_reset(BT_HDR * p_msg)1974 static void btif_media_task_aa_handle_decoder_reset(BT_HDR *p_msg)
1975 {
1976     tBTIF_MEDIA_SINK_CFG_UPDATE *p_buf = (tBTIF_MEDIA_SINK_CFG_UPDATE*) p_msg;
1977     tA2D_STATUS a2d_status;
1978     tA2D_SBC_CIE sbc_cie;
1979     OI_STATUS       status;
1980     UINT32          freq_multiple = 48*20; /* frequency multiple for 20ms of data , initialize with 48K*/
1981     UINT32          num_blocks = 16;
1982     UINT32          num_subbands = 8;
1983 
1984     APPL_TRACE_DEBUG("btif_media_task_aa_handle_decoder_reset p_codec_info[%x:%x:%x:%x:%x:%x]",
1985             p_buf->codec_info[1], p_buf->codec_info[2], p_buf->codec_info[3],
1986             p_buf->codec_info[4], p_buf->codec_info[5], p_buf->codec_info[6]);
1987 
1988     a2d_status = A2D_ParsSbcInfo(&sbc_cie, p_buf->codec_info, FALSE);
1989     if (a2d_status != A2D_SUCCESS)
1990     {
1991         APPL_TRACE_ERROR("ERROR dump_codec_info A2D_ParsSbcInfo fail:%d", a2d_status);
1992         return;
1993     }
1994 
1995     btif_media_cb.sample_rate = btif_a2dp_get_track_frequency(sbc_cie.samp_freq);
1996     btif_media_cb.channel_count = btif_a2dp_get_track_channel_count(sbc_cie.ch_mode);
1997 
1998     btif_media_cb.rx_flush = FALSE;
1999     APPL_TRACE_DEBUG("Reset to sink role");
2000     status = OI_CODEC_SBC_DecoderReset(&context, contextData, sizeof(contextData), 2, 2, FALSE);
2001     if (!OI_SUCCESS(status)) {
2002         APPL_TRACE_ERROR("OI_CODEC_SBC_DecoderReset failed with error code %d\n", status);
2003     }
2004 
2005     UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
2006 
2007     switch(sbc_cie.samp_freq)
2008     {
2009         case A2D_SBC_IE_SAMP_FREQ_16:
2010             APPL_TRACE_DEBUG("\tsamp_freq:%d (16000)", sbc_cie.samp_freq);
2011             freq_multiple = 16*20;
2012             break;
2013         case A2D_SBC_IE_SAMP_FREQ_32:
2014             APPL_TRACE_DEBUG("\tsamp_freq:%d (32000)", sbc_cie.samp_freq);
2015             freq_multiple = 32*20;
2016             break;
2017         case A2D_SBC_IE_SAMP_FREQ_44:
2018             APPL_TRACE_DEBUG("\tsamp_freq:%d (44100)", sbc_cie.samp_freq);
2019             freq_multiple = 441*2;
2020             break;
2021         case A2D_SBC_IE_SAMP_FREQ_48:
2022             APPL_TRACE_DEBUG("\tsamp_freq:%d (48000)", sbc_cie.samp_freq);
2023             freq_multiple = 48*20;
2024             break;
2025         default:
2026             APPL_TRACE_DEBUG(" Unknown Frequency ");
2027             break;
2028     }
2029 
2030     switch(sbc_cie.ch_mode)
2031     {
2032         case A2D_SBC_IE_CH_MD_MONO:
2033             APPL_TRACE_DEBUG("\tch_mode:%d (Mono)", sbc_cie.ch_mode);
2034             break;
2035         case A2D_SBC_IE_CH_MD_DUAL:
2036             APPL_TRACE_DEBUG("\tch_mode:%d (DUAL)", sbc_cie.ch_mode);
2037             break;
2038         case A2D_SBC_IE_CH_MD_STEREO:
2039             APPL_TRACE_DEBUG("\tch_mode:%d (STEREO)", sbc_cie.ch_mode);
2040             break;
2041         case A2D_SBC_IE_CH_MD_JOINT:
2042             APPL_TRACE_DEBUG("\tch_mode:%d (JOINT)", sbc_cie.ch_mode);
2043             break;
2044         default:
2045             APPL_TRACE_DEBUG(" Unknown Mode ");
2046             break;
2047     }
2048 
2049     switch(sbc_cie.block_len)
2050     {
2051         case A2D_SBC_IE_BLOCKS_4:
2052             APPL_TRACE_DEBUG("\tblock_len:%d (4)", sbc_cie.block_len);
2053             num_blocks = 4;
2054             break;
2055         case A2D_SBC_IE_BLOCKS_8:
2056             APPL_TRACE_DEBUG("\tblock_len:%d (8)", sbc_cie.block_len);
2057             num_blocks = 8;
2058             break;
2059         case A2D_SBC_IE_BLOCKS_12:
2060             APPL_TRACE_DEBUG("\tblock_len:%d (12)", sbc_cie.block_len);
2061             num_blocks = 12;
2062             break;
2063         case A2D_SBC_IE_BLOCKS_16:
2064             APPL_TRACE_DEBUG("\tblock_len:%d (16)", sbc_cie.block_len);
2065             num_blocks = 16;
2066             break;
2067         default:
2068             APPL_TRACE_DEBUG(" Unknown BlockLen ");
2069             break;
2070     }
2071 
2072     switch(sbc_cie.num_subbands)
2073     {
2074         case A2D_SBC_IE_SUBBAND_4:
2075             APPL_TRACE_DEBUG("\tnum_subbands:%d (4)", sbc_cie.num_subbands);
2076             num_subbands = 4;
2077             break;
2078         case A2D_SBC_IE_SUBBAND_8:
2079             APPL_TRACE_DEBUG("\tnum_subbands:%d (8)", sbc_cie.num_subbands);
2080             num_subbands = 8;
2081             break;
2082         default:
2083             APPL_TRACE_DEBUG(" Unknown SubBands ");
2084             break;
2085     }
2086 
2087     switch(sbc_cie.alloc_mthd)
2088     {
2089         case A2D_SBC_IE_ALLOC_MD_S:
2090             APPL_TRACE_DEBUG("\talloc_mthd:%d (SNR)", sbc_cie.alloc_mthd);
2091             break;
2092         case A2D_SBC_IE_ALLOC_MD_L:
2093             APPL_TRACE_DEBUG("\talloc_mthd:%d (Loudness)", sbc_cie.alloc_mthd);
2094             break;
2095         default:
2096             APPL_TRACE_DEBUG(" Unknown Allocation Method");
2097             break;
2098     }
2099 
2100     APPL_TRACE_DEBUG("\tBit pool Min:%d Max:%d", sbc_cie.min_bitpool, sbc_cie.max_bitpool);
2101 
2102     btif_media_cb.frames_to_process = ((freq_multiple)/(num_blocks*num_subbands)) + 1;
2103     APPL_TRACE_DEBUG(" Frames to be processed in 20 ms %d",btif_media_cb.frames_to_process);
2104 }
2105 #endif
2106 
2107 /*******************************************************************************
2108  **
2109  ** Function         btif_media_task_feeding_state_reset
2110  **
2111  ** Description      Reset the media feeding state
2112  **
2113  ** Returns          void
2114  **
2115  *******************************************************************************/
btif_media_task_feeding_state_reset(void)2116 static void btif_media_task_feeding_state_reset(void)
2117 {
2118     /* By default, just clear the entire state */
2119     memset(&btif_media_cb.media_feeding_state, 0, sizeof(btif_media_cb.media_feeding_state));
2120 
2121     if (btif_media_cb.TxTranscoding == BTIF_MEDIA_TRSCD_PCM_2_SBC)
2122     {
2123         btif_media_cb.media_feeding_state.pcm.bytes_per_tick =
2124                 (btif_media_cb.media_feeding.cfg.pcm.sampling_freq *
2125                  btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8 *
2126                  btif_media_cb.media_feeding.cfg.pcm.num_channel *
2127                  BTIF_MEDIA_TIME_TICK)/1000;
2128 
2129         APPL_TRACE_WARNING("pcm bytes per tick %d",
2130                             (int)btif_media_cb.media_feeding_state.pcm.bytes_per_tick);
2131     }
2132 }
2133 
btif_media_task_alarm_cb(UNUSED_ATTR void * context)2134 static void btif_media_task_alarm_cb(UNUSED_ATTR void *context) {
2135   thread_post(worker_thread, btif_media_task_aa_handle_timer, NULL);
2136 }
2137 
2138 /*******************************************************************************
2139  **
2140  ** Function         btif_media_task_aa_start_tx
2141  **
2142  ** Description      Start media task encoding
2143  **
2144  ** Returns          void
2145  **
2146  *******************************************************************************/
btif_media_task_aa_start_tx(void)2147 static void btif_media_task_aa_start_tx(void)
2148 {
2149     APPL_TRACE_DEBUG("btif_media_task_aa_start_tx is timer %d, feeding mode %d",
2150              btif_media_cb.is_tx_timer, btif_media_cb.feeding_mode);
2151 
2152     /* Use a timer to poll the UIPC, get rid of the UIPC call back */
2153     // UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REG_CBACK, NULL);
2154 
2155     btif_media_cb.is_tx_timer = TRUE;
2156     last_frame_us = 0;
2157 
2158     /* Reset the media feeding state */
2159     btif_media_task_feeding_state_reset();
2160 
2161     APPL_TRACE_EVENT("starting timer %dms", BTIF_MEDIA_TIME_TICK);
2162 
2163     assert(btif_media_cb.media_alarm == NULL);
2164 
2165     btif_media_cb.media_alarm = alarm_new();
2166     if (!btif_media_cb.media_alarm) {
2167       LOG_ERROR("%s unable to allocate media alarm.", __func__);
2168       return;
2169     }
2170 
2171     alarm_set_periodic(btif_media_cb.media_alarm, BTIF_MEDIA_TIME_TICK, btif_media_task_alarm_cb, NULL);
2172 }
2173 
2174 /*******************************************************************************
2175  **
2176  ** Function         btif_media_task_aa_stop_tx
2177  **
2178  ** Description      Stop media task encoding
2179  **
2180  ** Returns          void
2181  **
2182  *******************************************************************************/
btif_media_task_aa_stop_tx(void)2183 static void btif_media_task_aa_stop_tx(void)
2184 {
2185     APPL_TRACE_DEBUG("%s is_tx_timer: %d", __func__, btif_media_cb.is_tx_timer);
2186 
2187     const bool send_ack = (btif_media_cb.is_tx_timer != FALSE);
2188 
2189     /* Stop the timer first */
2190     alarm_free(btif_media_cb.media_alarm);
2191     btif_media_cb.media_alarm = NULL;
2192     btif_media_cb.is_tx_timer = FALSE;
2193 
2194     UIPC_Close(UIPC_CH_ID_AV_AUDIO);
2195 
2196     /* Try to send acknowldegment once the media stream is
2197        stopped. This will make sure that the A2DP HAL layer is
2198        un-blocked on wait for acknowledgment for the sent command.
2199        This resolves a corner cases AVDTP SUSPEND collision
2200        when the DUT and the remote device issue SUSPEND simultaneously
2201        and due to the processing of the SUSPEND request from the remote,
2202        the media path is torn down. If the A2DP HAL happens to wait
2203        for ACK for the initiated SUSPEND, it would never receive it casuing
2204        a block/wait. Due to this acknowledgement, the A2DP HAL is guranteed
2205        to get the ACK for any pending command in such cases. */
2206 
2207     if (send_ack)
2208         a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
2209 
2210     /* audio engine stopped, reset tx suspended flag */
2211     btif_media_cb.tx_flush = 0;
2212     last_frame_us = 0;
2213 
2214     /* Reset the media feeding state */
2215     btif_media_task_feeding_state_reset();
2216 }
2217 
2218 /*******************************************************************************
2219  **
2220  ** Function         btif_get_num_aa_frame
2221  **
2222  ** Description
2223  **
2224  ** Returns          The number of media frames in this time slice
2225  **
2226  *******************************************************************************/
btif_get_num_aa_frame(void)2227 static UINT8 btif_get_num_aa_frame(void)
2228 {
2229     UINT8 result=0;
2230 
2231     switch (btif_media_cb.TxTranscoding)
2232     {
2233         case BTIF_MEDIA_TRSCD_PCM_2_SBC:
2234         {
2235             UINT32 pcm_bytes_per_frame = btif_media_cb.encoder.s16NumOfSubBands *
2236                              btif_media_cb.encoder.s16NumOfBlocks *
2237                              btif_media_cb.media_feeding.cfg.pcm.num_channel *
2238                              btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8;
2239 
2240             UINT32 us_this_tick = BTIF_MEDIA_TIME_TICK * 1000;
2241             UINT64 now_us = time_now_us();
2242             if (last_frame_us != 0)
2243                 us_this_tick = (now_us - last_frame_us);
2244             last_frame_us = now_us;
2245 
2246             btif_media_cb.media_feeding_state.pcm.counter +=
2247                                 btif_media_cb.media_feeding_state.pcm.bytes_per_tick *
2248                                 us_this_tick / (BTIF_MEDIA_TIME_TICK * 1000);
2249 
2250             /* calculate nbr of frames pending for this media tick */
2251             result = btif_media_cb.media_feeding_state.pcm.counter/pcm_bytes_per_frame;
2252             if (result > MAX_PCM_FRAME_NUM_PER_TICK)
2253             {
2254                 APPL_TRACE_WARNING("%s() - Limiting frames to be sent from %d to %d"
2255                     , __FUNCTION__, result, MAX_PCM_FRAME_NUM_PER_TICK);
2256                 result = MAX_PCM_FRAME_NUM_PER_TICK;
2257             }
2258             btif_media_cb.media_feeding_state.pcm.counter -= result*pcm_bytes_per_frame;
2259 
2260             LOG_VERBOSE("WRITE %d FRAMES", result);
2261         }
2262         break;
2263 
2264         default:
2265             APPL_TRACE_ERROR("ERROR btif_get_num_aa_frame Unsupported transcoding format 0x%x",
2266                     btif_media_cb.TxTranscoding);
2267             result = 0;
2268             break;
2269     }
2270 
2271     return (UINT8)result;
2272 }
2273 
2274 /*******************************************************************************
2275  **
2276  ** Function         btif_media_sink_enque_buf
2277  **
2278  ** Description      This function is called by the av_co to fill A2DP Sink Queue
2279  **
2280  **
2281  ** Returns          size of the queue
2282  *******************************************************************************/
btif_media_sink_enque_buf(BT_HDR * p_pkt)2283 UINT8 btif_media_sink_enque_buf(BT_HDR *p_pkt)
2284 {
2285     tBT_SBC_HDR *p_msg;
2286 
2287     if(btif_media_cb.rx_flush == TRUE) /* Flush enabled, do not enque*/
2288         return GKI_queue_length(&btif_media_cb.RxSbcQ);
2289     if(GKI_queue_length(&btif_media_cb.RxSbcQ) == MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ)
2290     {
2291         GKI_freebuf(GKI_dequeue(&(btif_media_cb.RxSbcQ)));
2292     }
2293 
2294     BTIF_TRACE_VERBOSE("btif_media_sink_enque_buf + ");
2295     /* allocate and Queue this buffer */
2296     if ((p_msg = (tBT_SBC_HDR *) GKI_getbuf(sizeof(tBT_SBC_HDR) +
2297                         p_pkt->offset+ p_pkt->len)) != NULL)
2298     {
2299         memcpy(p_msg, p_pkt, (sizeof(BT_HDR) + p_pkt->offset + p_pkt->len));
2300         p_msg->num_frames_to_be_processed = (*((UINT8*)(p_msg + 1) + p_msg->offset)) & 0x0f;
2301         BTIF_TRACE_VERBOSE("btif_media_sink_enque_buf + ", p_msg->num_frames_to_be_processed);
2302         GKI_enqueue(&(btif_media_cb.RxSbcQ), p_msg);
2303         if(GKI_queue_length(&btif_media_cb.RxSbcQ) == MAX_A2DP_DELAYED_START_FRAME_COUNT)
2304         {
2305             BTIF_TRACE_DEBUG(" Initiate Decoding ");
2306             btif_media_task_aa_handle_start_decoding();
2307         }
2308     }
2309     else
2310     {
2311         /* let caller deal with a failed allocation */
2312         BTIF_TRACE_VERBOSE("btif_media_sink_enque_buf No Buffer left - ");
2313     }
2314     return GKI_queue_length(&btif_media_cb.RxSbcQ);
2315 }
2316 
2317 /*******************************************************************************
2318  **
2319  ** Function         btif_media_aa_readbuf
2320  **
2321  ** Description      This function is called by the av_co to get the next buffer to send
2322  **
2323  **
2324  ** Returns          void
2325  *******************************************************************************/
btif_media_aa_readbuf(void)2326 BT_HDR *btif_media_aa_readbuf(void)
2327 {
2328     return GKI_dequeue(&(btif_media_cb.TxAaQ));
2329 }
2330 
2331 /*******************************************************************************
2332  **
2333  ** Function         btif_media_aa_read_feeding
2334  **
2335  ** Description
2336  **
2337  ** Returns          void
2338  **
2339  *******************************************************************************/
2340 
btif_media_aa_read_feeding(tUIPC_CH_ID channel_id)2341 BOOLEAN btif_media_aa_read_feeding(tUIPC_CH_ID channel_id)
2342 {
2343     UINT16 event;
2344     UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands * \
2345                              btif_media_cb.encoder.s16NumOfBlocks;
2346     UINT32 read_size;
2347     UINT16 sbc_sampling = 48000;
2348     UINT32 src_samples;
2349     UINT16 bytes_needed = blocm_x_subband * btif_media_cb.encoder.s16NumOfChannels * \
2350                           btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8;
2351     static UINT16 up_sampled_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS
2352             * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * 2];
2353     static UINT16 read_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS
2354             * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS];
2355     UINT32 src_size_used;
2356     UINT32 dst_size_used;
2357     BOOLEAN fract_needed;
2358     INT32   fract_max;
2359     INT32   fract_threshold;
2360     UINT32  nb_byte_read;
2361 
2362     /* Get the SBC sampling rate */
2363     switch (btif_media_cb.encoder.s16SamplingFreq)
2364     {
2365     case SBC_sf48000:
2366         sbc_sampling = 48000;
2367         break;
2368     case SBC_sf44100:
2369         sbc_sampling = 44100;
2370         break;
2371     case SBC_sf32000:
2372         sbc_sampling = 32000;
2373         break;
2374     case SBC_sf16000:
2375         sbc_sampling = 16000;
2376         break;
2377     }
2378 
2379     if (sbc_sampling == btif_media_cb.media_feeding.cfg.pcm.sampling_freq) {
2380         read_size = bytes_needed - btif_media_cb.media_feeding_state.pcm.aa_feed_residue;
2381         nb_byte_read = UIPC_Read(channel_id, &event,
2382                   ((UINT8 *)btif_media_cb.encoder.as16PcmBuffer) +
2383                   btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2384                   read_size);
2385         if (nb_byte_read == read_size) {
2386             btif_media_cb.media_feeding_state.pcm.aa_feed_residue = 0;
2387             return TRUE;
2388         } else {
2389             APPL_TRACE_WARNING("### UNDERFLOW :: ONLY READ %d BYTES OUT OF %d ###",
2390                 nb_byte_read, read_size);
2391             btif_media_cb.media_feeding_state.pcm.aa_feed_residue += nb_byte_read;
2392             return FALSE;
2393         }
2394     }
2395 
2396     /* Some Feeding PCM frequencies require to split the number of sample */
2397     /* to read. */
2398     /* E.g 128/6=21.3333 => read 22 and 21 and 21 => max = 2; threshold = 0*/
2399     fract_needed = FALSE;   /* Default */
2400     switch (btif_media_cb.media_feeding.cfg.pcm.sampling_freq)
2401     {
2402     case 32000:
2403     case 8000:
2404         fract_needed = TRUE;
2405         fract_max = 2;          /* 0, 1 and 2 */
2406         fract_threshold = 0;    /* Add one for the first */
2407         break;
2408     case 16000:
2409         fract_needed = TRUE;
2410         fract_max = 2;          /* 0, 1 and 2 */
2411         fract_threshold = 1;    /* Add one for the first two frames*/
2412         break;
2413     }
2414 
2415     /* Compute number of sample to read from source */
2416     src_samples = blocm_x_subband;
2417     src_samples *= btif_media_cb.media_feeding.cfg.pcm.sampling_freq;
2418     src_samples /= sbc_sampling;
2419 
2420     /* The previous division may have a remainder not null */
2421     if (fract_needed)
2422     {
2423         if (btif_media_cb.media_feeding_state.pcm.aa_feed_counter <= fract_threshold)
2424         {
2425             src_samples++; /* for every read before threshold add one sample */
2426         }
2427 
2428         /* do nothing if counter >= threshold */
2429         btif_media_cb.media_feeding_state.pcm.aa_feed_counter++; /* one more read */
2430         if (btif_media_cb.media_feeding_state.pcm.aa_feed_counter > fract_max)
2431         {
2432             btif_media_cb.media_feeding_state.pcm.aa_feed_counter = 0;
2433         }
2434     }
2435 
2436     /* Compute number of bytes to read from source */
2437     read_size = src_samples;
2438     read_size *= btif_media_cb.media_feeding.cfg.pcm.num_channel;
2439     read_size *= (btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8);
2440 
2441     /* Read Data from UIPC channel */
2442     nb_byte_read = UIPC_Read(channel_id, &event, (UINT8 *)read_buffer, read_size);
2443 
2444     //tput_mon(TRUE, nb_byte_read, FALSE);
2445 
2446     if (nb_byte_read < read_size)
2447     {
2448         APPL_TRACE_WARNING("### UNDERRUN :: ONLY READ %d BYTES OUT OF %d ###",
2449                 nb_byte_read, read_size);
2450 
2451         if (nb_byte_read == 0)
2452             return FALSE;
2453 
2454         if(btif_media_cb.feeding_mode == BTIF_AV_FEEDING_ASYNCHRONOUS)
2455         {
2456             /* Fill the unfilled part of the read buffer with silence (0) */
2457             memset(((UINT8 *)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
2458             nb_byte_read = read_size;
2459         }
2460     }
2461 
2462     /* Initialize PCM up-sampling engine */
2463     bta_av_sbc_init_up_sample(btif_media_cb.media_feeding.cfg.pcm.sampling_freq,
2464             sbc_sampling, btif_media_cb.media_feeding.cfg.pcm.bit_per_sample,
2465             btif_media_cb.media_feeding.cfg.pcm.num_channel);
2466 
2467     /* re-sample read buffer */
2468     /* The output PCM buffer will be stereo, 16 bit per sample */
2469     dst_size_used = bta_av_sbc_up_sample((UINT8 *)read_buffer,
2470             (UINT8 *)up_sampled_buffer + btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2471             nb_byte_read,
2472             sizeof(up_sampled_buffer) - btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2473             &src_size_used);
2474 
2475     /* update the residue */
2476     btif_media_cb.media_feeding_state.pcm.aa_feed_residue += dst_size_used;
2477 
2478     /* only copy the pcm sample when we have up-sampled enough PCM */
2479     if(btif_media_cb.media_feeding_state.pcm.aa_feed_residue >= bytes_needed)
2480     {
2481         /* Copy the output pcm samples in SBC encoding buffer */
2482         memcpy((UINT8 *)btif_media_cb.encoder.as16PcmBuffer,
2483                 (UINT8 *)up_sampled_buffer,
2484                 bytes_needed);
2485         /* update the residue */
2486         btif_media_cb.media_feeding_state.pcm.aa_feed_residue -= bytes_needed;
2487 
2488         if (btif_media_cb.media_feeding_state.pcm.aa_feed_residue != 0)
2489         {
2490             memcpy((UINT8 *)up_sampled_buffer,
2491                    (UINT8 *)up_sampled_buffer + bytes_needed,
2492                    btif_media_cb.media_feeding_state.pcm.aa_feed_residue);
2493         }
2494         return TRUE;
2495     }
2496 
2497     return FALSE;
2498 }
2499 
2500 /*******************************************************************************
2501  **
2502  ** Function         btif_media_aa_prep_sbc_2_send
2503  **
2504  ** Description
2505  **
2506  ** Returns          void
2507  **
2508  *******************************************************************************/
btif_media_aa_prep_sbc_2_send(UINT8 nb_frame)2509 static void btif_media_aa_prep_sbc_2_send(UINT8 nb_frame)
2510 {
2511     BT_HDR * p_buf;
2512     UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands *
2513                              btif_media_cb.encoder.s16NumOfBlocks;
2514 
2515     while (nb_frame)
2516     {
2517         if (NULL == (p_buf = GKI_getpoolbuf(BTIF_MEDIA_AA_POOL_ID)))
2518         {
2519             APPL_TRACE_ERROR ("ERROR btif_media_aa_prep_sbc_2_send no buffer TxCnt %d ",
2520                                 GKI_queue_length(&btif_media_cb.TxAaQ));
2521             return;
2522         }
2523 
2524         /* Init buffer */
2525         p_buf->offset = BTIF_MEDIA_AA_SBC_OFFSET;
2526         p_buf->len = 0;
2527         p_buf->layer_specific = 0;
2528 
2529         do
2530         {
2531             /* Write @ of allocated buffer in encoder.pu8Packet */
2532             btif_media_cb.encoder.pu8Packet = (UINT8 *) (p_buf + 1) + p_buf->offset + p_buf->len;
2533             /* Fill allocated buffer with 0 */
2534             memset(btif_media_cb.encoder.as16PcmBuffer, 0, blocm_x_subband
2535                     * btif_media_cb.encoder.s16NumOfChannels);
2536 
2537             /* Read PCM data and upsample them if needed */
2538             if (btif_media_aa_read_feeding(UIPC_CH_ID_AV_AUDIO))
2539             {
2540                 /* SBC encode and descramble frame */
2541                 SBC_Encoder(&(btif_media_cb.encoder));
2542                 A2D_SbcChkFrInit(btif_media_cb.encoder.pu8Packet);
2543                 A2D_SbcDescramble(btif_media_cb.encoder.pu8Packet, btif_media_cb.encoder.u16PacketLength);
2544                 /* Update SBC frame length */
2545                 p_buf->len += btif_media_cb.encoder.u16PacketLength;
2546                 nb_frame--;
2547                 p_buf->layer_specific++;
2548             }
2549             else
2550             {
2551                 APPL_TRACE_WARNING("btif_media_aa_prep_sbc_2_send underflow %d, %d",
2552                     nb_frame, btif_media_cb.media_feeding_state.pcm.aa_feed_residue);
2553                 btif_media_cb.media_feeding_state.pcm.counter += nb_frame *
2554                      btif_media_cb.encoder.s16NumOfSubBands *
2555                      btif_media_cb.encoder.s16NumOfBlocks *
2556                      btif_media_cb.media_feeding.cfg.pcm.num_channel *
2557                      btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8;
2558                 /* no more pcm to read */
2559                 nb_frame = 0;
2560 
2561                 /* break read loop if timer was stopped (media task stopped) */
2562                 if ( btif_media_cb.is_tx_timer == FALSE )
2563                 {
2564                     GKI_freebuf(p_buf);
2565                     return;
2566                 }
2567             }
2568 
2569         } while (((p_buf->len + btif_media_cb.encoder.u16PacketLength) < btif_media_cb.TxAaMtuSize)
2570                 && (p_buf->layer_specific < 0x0F) && nb_frame);
2571 
2572         if(p_buf->len)
2573         {
2574             /* timestamp of the media packet header represent the TS of the first SBC frame
2575                i.e the timestamp before including this frame */
2576             *((UINT32 *) (p_buf + 1)) = btif_media_cb.timestamp;
2577 
2578             btif_media_cb.timestamp += p_buf->layer_specific * blocm_x_subband;
2579 
2580             if (btif_media_cb.tx_flush)
2581             {
2582                 APPL_TRACE_DEBUG("### tx suspended, discarded frame ###");
2583 
2584                 if (GKI_queue_length(&btif_media_cb.TxAaQ) > 0)
2585                     btif_media_flush_q(&(btif_media_cb.TxAaQ));
2586 
2587                 GKI_freebuf(p_buf);
2588                 return;
2589             }
2590 
2591             /* Enqueue the encoded SBC frame in AA Tx Queue */
2592             GKI_enqueue(&(btif_media_cb.TxAaQ), p_buf);
2593         }
2594         else
2595         {
2596             GKI_freebuf(p_buf);
2597         }
2598     }
2599 }
2600 
2601 
2602 /*******************************************************************************
2603  **
2604  ** Function         btif_media_aa_prep_2_send
2605  **
2606  ** Description
2607  **
2608  ** Returns          void
2609  **
2610  *******************************************************************************/
2611 
btif_media_aa_prep_2_send(UINT8 nb_frame)2612 static void btif_media_aa_prep_2_send(UINT8 nb_frame)
2613 {
2614     // Check for TX queue overflow
2615 
2616     if (nb_frame > MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ)
2617         nb_frame = MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ;
2618 
2619     if (GKI_queue_length(&btif_media_cb.TxAaQ) > (MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ - nb_frame))
2620     {
2621         APPL_TRACE_WARNING("%s() - TX queue buffer count %d/%d", __func__,
2622             GKI_queue_length(&btif_media_cb.TxAaQ), MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ - nb_frame);
2623     }
2624 
2625     while (GKI_queue_length(&btif_media_cb.TxAaQ) > (MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ - nb_frame))
2626         GKI_freebuf(GKI_dequeue(&(btif_media_cb.TxAaQ)));
2627 
2628     // Transcode frame
2629 
2630     switch (btif_media_cb.TxTranscoding)
2631     {
2632     case BTIF_MEDIA_TRSCD_PCM_2_SBC:
2633         btif_media_aa_prep_sbc_2_send(nb_frame);
2634         break;
2635 
2636     default:
2637         APPL_TRACE_ERROR("%s unsupported transcoding format 0x%x", __func__, btif_media_cb.TxTranscoding);
2638         break;
2639     }
2640 }
2641 
2642 /*******************************************************************************
2643  **
2644  ** Function         btif_media_send_aa_frame
2645  **
2646  ** Description
2647  **
2648  ** Returns          void
2649  **
2650  *******************************************************************************/
btif_media_send_aa_frame(void)2651 static void btif_media_send_aa_frame(void)
2652 {
2653     UINT8 nb_frame_2_send;
2654 
2655     /* get the number of frame to send */
2656     nb_frame_2_send = btif_get_num_aa_frame();
2657 
2658     if (nb_frame_2_send != 0)
2659     {
2660         /* format and Q buffer to send */
2661         btif_media_aa_prep_2_send(nb_frame_2_send);
2662     }
2663 
2664     /* send it */
2665     LOG_VERBOSE("btif_media_send_aa_frame : send %d frames", nb_frame_2_send);
2666     bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
2667 }
2668 
2669 #endif /* BTA_AV_INCLUDED == TRUE */
2670 
2671 /*******************************************************************************
2672  **
2673  ** Function         dump_codec_info
2674  **
2675  ** Description      Decode and display codec_info (for debug)
2676  **
2677  ** Returns          void
2678  **
2679  *******************************************************************************/
dump_codec_info(unsigned char * p_codec)2680 void dump_codec_info(unsigned char *p_codec)
2681 {
2682     tA2D_STATUS a2d_status;
2683     tA2D_SBC_CIE sbc_cie;
2684 
2685     a2d_status = A2D_ParsSbcInfo(&sbc_cie, p_codec, FALSE);
2686     if (a2d_status != A2D_SUCCESS)
2687     {
2688         APPL_TRACE_ERROR("ERROR dump_codec_info A2D_ParsSbcInfo fail:%d", a2d_status);
2689         return;
2690     }
2691 
2692     APPL_TRACE_DEBUG("dump_codec_info");
2693 
2694     if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_16)
2695     {    APPL_TRACE_DEBUG("\tsamp_freq:%d (16000)", sbc_cie.samp_freq);}
2696     else  if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_32)
2697     {    APPL_TRACE_DEBUG("\tsamp_freq:%d (32000)", sbc_cie.samp_freq);}
2698     else  if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_44)
2699     {    APPL_TRACE_DEBUG("\tsamp_freq:%d (44.100)", sbc_cie.samp_freq);}
2700     else  if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_48)
2701     {    APPL_TRACE_DEBUG("\tsamp_freq:%d (48000)", sbc_cie.samp_freq);}
2702     else
2703     {    APPL_TRACE_DEBUG("\tBAD samp_freq:%d", sbc_cie.samp_freq);}
2704 
2705     if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_MONO)
2706     {    APPL_TRACE_DEBUG("\tch_mode:%d (Mono)", sbc_cie.ch_mode);}
2707     else  if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_DUAL)
2708     {    APPL_TRACE_DEBUG("\tch_mode:%d (Dual)", sbc_cie.ch_mode);}
2709     else  if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_STEREO)
2710     {    APPL_TRACE_DEBUG("\tch_mode:%d (Stereo)", sbc_cie.ch_mode);}
2711     else  if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_JOINT)
2712     {    APPL_TRACE_DEBUG("\tch_mode:%d (Joint)", sbc_cie.ch_mode);}
2713     else
2714     {    APPL_TRACE_DEBUG("\tBAD ch_mode:%d", sbc_cie.ch_mode);}
2715 
2716     if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_4)
2717     {    APPL_TRACE_DEBUG("\tblock_len:%d (4)", sbc_cie.block_len);}
2718     else  if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_8)
2719     {    APPL_TRACE_DEBUG("\tblock_len:%d (8)", sbc_cie.block_len);}
2720     else  if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_12)
2721     {    APPL_TRACE_DEBUG("\tblock_len:%d (12)", sbc_cie.block_len);}
2722     else  if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_16)
2723     {    APPL_TRACE_DEBUG("\tblock_len:%d (16)", sbc_cie.block_len);}
2724     else
2725     {    APPL_TRACE_DEBUG("\tBAD block_len:%d", sbc_cie.block_len);}
2726 
2727     if (sbc_cie.num_subbands == A2D_SBC_IE_SUBBAND_4)
2728     {    APPL_TRACE_DEBUG("\tnum_subbands:%d (4)", sbc_cie.num_subbands);}
2729     else  if (sbc_cie.num_subbands == A2D_SBC_IE_SUBBAND_8)
2730     {    APPL_TRACE_DEBUG("\tnum_subbands:%d (8)", sbc_cie.num_subbands);}
2731     else
2732     {    APPL_TRACE_DEBUG("\tBAD num_subbands:%d", sbc_cie.num_subbands);}
2733 
2734     if (sbc_cie.alloc_mthd == A2D_SBC_IE_ALLOC_MD_S)
2735     {    APPL_TRACE_DEBUG("\talloc_mthd:%d (SNR)", sbc_cie.alloc_mthd);}
2736     else  if (sbc_cie.alloc_mthd == A2D_SBC_IE_ALLOC_MD_L)
2737     {    APPL_TRACE_DEBUG("\talloc_mthd:%d (Loundess)", sbc_cie.alloc_mthd);}
2738     else
2739     {    APPL_TRACE_DEBUG("\tBAD alloc_mthd:%d", sbc_cie.alloc_mthd);}
2740 
2741     APPL_TRACE_DEBUG("\tBit pool Min:%d Max:%d", sbc_cie.min_bitpool, sbc_cie.max_bitpool);
2742 
2743 }
2744 
2745