• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <string.h>
30 #include <stdio.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <pthread.h>
36 #include <stdint.h>
37 #include <sys/time.h>
38 
39 #include "bt_target.h"
40 #include "gki.h"
41 #include "bta_api.h"
42 #include "btu.h"
43 #include "bta_sys.h"
44 #include "bta_sys_int.h"
45 
46 #include "bta_av_api.h"
47 #include "a2d_api.h"
48 #include "a2d_sbc.h"
49 #include "a2d_int.h"
50 #include "bta_av_sbc.h"
51 #include "bta_av_ci.h"
52 #include "l2c_api.h"
53 
54 
55 #include "btif_av_co.h"
56 #include "btif_media.h"
57 
58 
59 #if (BTA_AV_INCLUDED == TRUE)
60 #include "sbc_encoder.h"
61 #endif
62 
63 #define LOG_TAG "BTIF-MEDIA"
64 
65 #include <hardware/bluetooth.h>
66 #include "audio_a2dp_hw.h"
67 #include "btif_av.h"
68 #include "btif_sm.h"
69 #include "btif_util.h"
70 #include "bt_utils.h"
71 
72 /*****************************************************************************
73  **  Constants
74  *****************************************************************************/
75 
76 //#define DEBUG_MEDIA_AV_FLOW TRUE
77 
78 /* BTIF media task gki event definition */
79 #define BTIF_MEDIA_TASK_CMD TASK_MBOX_0_EVT_MASK
80 #define BTIF_MEDIA_TASK_DATA TASK_MBOX_1_EVT_MASK
81 
82 #define BTIF_MEDIA_TASK_KILL EVENT_MASK(GKI_SHUTDOWN_EVT)
83 
84 #define BTIF_MEDIA_AA_TASK_TIMER_ID TIMER_0
85 #define BTIF_MEDIA_AV_TASK_TIMER_ID TIMER_1
86 #define BTIF_MEDIA_AA_TASK_TIMER TIMER_0_EVT_MASK
87 #define BTIF_MEDIA_AV_TASK_TIMER TIMER_1_EVT_MASK
88 
89 #define BTIF_MEDIA_TASK_CMD_MBOX        TASK_MBOX_0     /* cmd mailbox  */
90 #define BTIF_MEDIA_TASK_DATA_MBOX       TASK_MBOX_1     /* data mailbox  */
91 
92 /* BTIF media cmd event definition : BTIF_MEDIA_TASK_CMD */
93 enum
94 {
95     BTIF_MEDIA_START_AA_TX = 1,
96     BTIF_MEDIA_STOP_AA_TX,
97     BTIF_MEDIA_AA_RX_RDY,
98     BTIF_MEDIA_UIPC_RX_RDY,
99     BTIF_MEDIA_SBC_ENC_INIT,
100     BTIF_MEDIA_SBC_ENC_UPDATE,
101     BTIF_MEDIA_SBC_DEC_INIT,
102     BTIF_MEDIA_VIDEO_DEC_INIT,
103     BTIF_MEDIA_FLUSH_AA_TX,
104     BTIF_MEDIA_FLUSH_AA_RX,
105     BTIF_MEDIA_AUDIO_FEEDING_INIT,
106     BTIF_MEDIA_AUDIO_RECEIVING_INIT
107 };
108 
109 enum {
110     MEDIA_TASK_STATE_OFF = 0,
111     MEDIA_TASK_STATE_ON = 1,
112     MEDIA_TASK_STATE_SHUTTING_DOWN = 2
113 };
114 
115 /* Macro to multiply the media task tick */
116 #ifndef BTIF_MEDIA_NUM_TICK
117 #define BTIF_MEDIA_NUM_TICK      1
118 #endif
119 
120 /* Media task tick in milliseconds */
121 #define BTIF_MEDIA_TIME_TICK                     (20 * BTIF_MEDIA_NUM_TICK)
122 
123 /* Number of frames per media task tick.
124    Configure value rounded up to closest integer and
125    adjust any deltas in btif_get_num_aa_frame */
126 
127 /* 7.5 frames/tick @ 20 ms tick (every 2nd frame send one less) */
128 #define BTIF_MEDIA_FR_PER_TICKS_48               (8 * BTIF_MEDIA_NUM_TICK)
129 
130 /* 6.89 frames/tick  @ 20 ms tick (7 out of 64 frames send one less */
131 #define BTIF_MEDIA_FR_PER_TICKS_44_1             (7 * BTIF_MEDIA_NUM_TICK)
132 
133 /* 5.0 frames/tick  @ 20 ms tick */
134 #define BTIF_MEDIA_FR_PER_TICKS_32               (5 * BTIF_MEDIA_NUM_TICK)
135 
136 /* 2.5 frames/tick  @ 20 ms tick (every 2nd frame send one less) */
137 #define BTIF_MEDIA_FR_PER_TICKS_16               (3 * BTIF_MEDIA_NUM_TICK)
138 
139 
140 /* buffer pool */
141 #define BTIF_MEDIA_AA_POOL_ID GKI_POOL_ID_3
142 #define BTIF_MEDIA_AA_BUF_SIZE GKI_BUF3_SIZE
143 
144 /* offset */
145 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
146 #define BTIF_MEDIA_AA_SBC_OFFSET (AVDT_MEDIA_OFFSET + BTA_AV_SBC_HDR_SIZE + 1)
147 #else
148 #define BTIF_MEDIA_AA_SBC_OFFSET (AVDT_MEDIA_OFFSET + BTA_AV_SBC_HDR_SIZE)
149 #endif
150 
151 /* Define the bitrate step when trying to match bitpool value */
152 #ifndef BTIF_MEDIA_BITRATE_STEP
153 #define BTIF_MEDIA_BITRATE_STEP 5
154 #endif
155 
156 /* Middle quality quality setting @ 44.1 khz */
157 #define DEFAULT_SBC_BITRATE 229
158 
159 #ifndef A2DP_MEDIA_TASK_STACK_SIZE
160 #define A2DP_MEDIA_TASK_STACK_SIZE       0x2000         /* In bytes */
161 #endif
162 
163 #define A2DP_MEDIA_TASK_TASK_STR        ((INT8 *) "A2DP-MEDIA")
164 static UINT32 a2dp_media_task_stack[(A2DP_MEDIA_TASK_STACK_SIZE + 3) / 4];
165 
166 #define BT_MEDIA_TASK A2DP_MEDIA_TASK
167 
168 #define USEC_PER_SEC 1000000L
169 #define TPUT_STATS_INTERVAL_US (1000*1000)
170 
171 /*
172  * CONGESTION COMPENSATION CTRL ::
173  *
174  * Thus setting controls how many buffers we will hold in media task
175  * during temp link congestion. Together with the stack buffer queues
176  * it controls much temporary a2dp link congestion we can
177  * compensate for. It however also depends on the default run level of sinks
178  * jitterbuffers. Depending on type of sink this would vary.
179  * Ideally the (SRC) max tx buffer capacity should equal the sinks
180  * jitterbuffer runlevel including any intermediate buffers on the way
181  * towards the sinks codec.
182  */
183 
184 /* fixme -- define this in pcm time instead of buffer count */
185 /* fixme -- tune optimal value. For now set a large buffer capacity */
186 #define MAX_OUTPUT_BUFFER_QUEUE_SZ 24
187 
188 //#define BTIF_MEDIA_VERBOSE_ENABLED
189 
190 #ifdef BTIF_MEDIA_VERBOSE_ENABLED
191 #define VERBOSE(fmt, ...) \
192       LogMsg( TRACE_CTRL_GENERAL | TRACE_LAYER_NONE | TRACE_ORG_APPL | \
193               TRACE_TYPE_ERROR, fmt, ## __VA_ARGS__)
194 #else
195 #define VERBOSE(fmt, ...)
196 #endif
197 
198 /*****************************************************************************
199  **  Data types
200  *****************************************************************************/
201 
202 typedef struct
203 {
204     UINT32 aa_frame_counter;
205     INT32  aa_feed_counter;
206     INT32  aa_feed_residue;
207 } tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE;
208 
209 
210 typedef union
211 {
212     tBTIF_AV_MEDIA_FEEDINGS_PCM_STATE pcm;
213 } tBTIF_AV_MEDIA_FEEDINGS_STATE;
214 
215 typedef struct
216 {
217 #if (BTA_AV_INCLUDED == TRUE)
218     BUFFER_Q TxAaQ;
219     BOOLEAN is_tx_timer;
220     UINT16 TxAaMtuSize;
221     UINT32 timestamp;
222     UINT8 TxTranscoding;
223     tBTIF_AV_FEEDING_MODE feeding_mode;
224     tBTIF_AV_MEDIA_FEEDINGS media_feeding;
225     tBTIF_AV_MEDIA_FEEDINGS_STATE media_feeding_state;
226     SBC_ENC_PARAMS encoder;
227     UINT8 busy_level;
228     void* av_sm_hdl;
229     UINT8 a2dp_cmd_pending; /* we can have max one command pending */
230     BOOLEAN tx_flush; /* discards any outgoing data when true */
231     BOOLEAN scaling_disabled;
232 #endif
233 
234 } tBTIF_MEDIA_CB;
235 
236 typedef struct {
237     int rx;
238     int rx_tot;
239     int tx;
240     int tx_tot;
241     int ts_prev_us;
242 } t_stat;
243 
244 /*****************************************************************************
245  **  Local data
246  *****************************************************************************/
247 
248 static tBTIF_MEDIA_CB btif_media_cb;
249 static int media_task_running = MEDIA_TASK_STATE_OFF;
250 
251 
252 /*****************************************************************************
253  **  Local functions
254  *****************************************************************************/
255 
256 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
257 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event);
258 static void btif_a2dp_encoder_update(void);
259 
260 /*****************************************************************************
261  **  Externs
262  *****************************************************************************/
263 
264 static void btif_media_task_handle_cmd(BT_HDR *p_msg);
265 static void btif_media_task_handle_media(BT_HDR *p_msg);
266 
267 #if (BTA_AV_INCLUDED == TRUE)
268 static void btif_media_send_aa_frame(void);
269 static void btif_media_task_feeding_state_reset(void);
270 static void btif_media_task_aa_start_tx(void);
271 static void btif_media_task_aa_stop_tx(void);
272 static void btif_media_task_enc_init(BT_HDR *p_msg);
273 static void btif_media_task_enc_update(BT_HDR *p_msg);
274 static void btif_media_task_audio_feeding_init(BT_HDR *p_msg);
275 static void btif_media_task_aa_tx_flush(BT_HDR *p_msg);
276 static void btif_media_aa_prep_2_send(UINT8 nb_frame);
277 #endif
278 
279 
280 /*****************************************************************************
281  **  Misc helper functions
282  *****************************************************************************/
283 
tput_mon(int is_rx,int len,int reset)284 static void tput_mon(int is_rx, int len, int reset)
285 {
286     /* only monitor one connection at a time for now */
287     static t_stat cur_stat;
288     struct timespec now;
289     unsigned int prev_us;
290     unsigned int now_us;
291 
292     if (reset == TRUE)
293     {
294         memset(&cur_stat, 0, sizeof(t_stat));
295         return;
296     }
297 
298     if (is_rx)
299     {
300         cur_stat.rx+=len;
301         cur_stat.rx_tot+=len;
302     }
303     else
304     {
305         cur_stat.tx+=len;
306         cur_stat.tx_tot+=len;
307     }
308     clock_gettime(CLOCK_MONOTONIC, &now);
309 
310     now_us = now.tv_sec*USEC_PER_SEC + now.tv_nsec/1000;
311 
312     //APPL_TRACE_DEBUG1("%d us", now_us - cur_stat.ts_prev_us);
313 
314     if ((now_us - cur_stat.ts_prev_us) < TPUT_STATS_INTERVAL_US)
315         return;
316 
317     APPL_TRACE_WARNING4("tput rx:%d, tx:%d (kB/s)  (tot : rx %d, tx %d bytes)",
318           (cur_stat.rx)/((now_us - cur_stat.ts_prev_us)/1000),
319           (cur_stat.tx)/((now_us - cur_stat.ts_prev_us)/1000),
320            cur_stat.rx_tot, cur_stat.tx_tot);
321 
322     /* stats dumped. now reset stats for next interval */
323     cur_stat.rx = 0;
324     cur_stat.tx = 0;
325     cur_stat.ts_prev_us = now_us;
326 }
327 
328 
log_tstamps_us(char * comment)329 static void log_tstamps_us(char *comment)
330 {
331     #define USEC_PER_SEC 1000000L
332     static struct timespec prev = {0, 0};
333     struct timespec now, diff;
334     unsigned int diff_us = 0;
335     unsigned int now_us = 0;
336 
337     clock_gettime(CLOCK_MONOTONIC, &now);
338     now_us = now.tv_sec*USEC_PER_SEC + now.tv_nsec/1000;
339     diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (now.tv_nsec - prev.tv_nsec)/1000;
340 
341     APPL_TRACE_DEBUG4("[%s] ts %08d, diff : %08d, queue sz %d", comment, now_us, diff_us,
342                 btif_media_cb.TxAaQ.count);
343 
344     prev = now;
345 }
346 
dump_media_event(UINT16 event)347 const char* dump_media_event(UINT16 event)
348 {
349     switch(event)
350     {
351         CASE_RETURN_STR(BTIF_MEDIA_START_AA_TX)
352         CASE_RETURN_STR(BTIF_MEDIA_STOP_AA_TX)
353         CASE_RETURN_STR(BTIF_MEDIA_AA_RX_RDY)
354         CASE_RETURN_STR(BTIF_MEDIA_UIPC_RX_RDY)
355         CASE_RETURN_STR(BTIF_MEDIA_SBC_ENC_INIT)
356         CASE_RETURN_STR(BTIF_MEDIA_SBC_ENC_UPDATE)
357         CASE_RETURN_STR(BTIF_MEDIA_SBC_DEC_INIT)
358         CASE_RETURN_STR(BTIF_MEDIA_VIDEO_DEC_INIT)
359         CASE_RETURN_STR(BTIF_MEDIA_FLUSH_AA_TX)
360         CASE_RETURN_STR(BTIF_MEDIA_FLUSH_AA_RX)
361         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_FEEDING_INIT)
362         CASE_RETURN_STR(BTIF_MEDIA_AUDIO_RECEIVING_INIT)
363 
364         default:
365             return "UNKNOWN MEDIA EVENT";
366     }
367 }
368 
369 /*****************************************************************************
370  **  A2DP CTRL PATH
371  *****************************************************************************/
372 
dump_a2dp_ctrl_event(UINT8 event)373 static const char* dump_a2dp_ctrl_event(UINT8 event)
374 {
375     switch(event)
376     {
377         CASE_RETURN_STR(A2DP_CTRL_CMD_NONE)
378         CASE_RETURN_STR(A2DP_CTRL_CMD_CHECK_READY)
379         CASE_RETURN_STR(A2DP_CTRL_CMD_START)
380         CASE_RETURN_STR(A2DP_CTRL_CMD_STOP)
381         CASE_RETURN_STR(A2DP_CTRL_CMD_SUSPEND)
382         default:
383             return "UNKNOWN MSG ID";
384     }
385 }
386 
btif_audiopath_detached(void)387 static void btif_audiopath_detached(void)
388 {
389     APPL_TRACE_EVENT0("## AUDIO PATH DETACHED ##");
390 
391     /*  send stop request only if we are actively streaming and haven't received
392         a stop request. Potentially audioflinger detached abnormally */
393     if (btif_media_cb.is_tx_timer)
394     {
395         /* post stop event and wait for audio path to stop */
396         btif_dispatch_sm_event(BTIF_AV_STOP_STREAM_REQ_EVT, NULL, 0);
397     }
398 }
399 
a2dp_cmd_acknowledge(int status)400 static void a2dp_cmd_acknowledge(int status)
401 {
402     UINT8 ack = status;
403 
404     APPL_TRACE_EVENT2("## a2dp ack : %s, status %d ##", dump_a2dp_ctrl_event(btif_media_cb.a2dp_cmd_pending), status);
405 
406     /* sanity check */
407     if (btif_media_cb.a2dp_cmd_pending == A2DP_CTRL_CMD_NONE)
408     {
409         APPL_TRACE_ERROR0("warning : no command pending, ignore ack");
410         return;
411     }
412 
413     /* clear pending */
414     btif_media_cb.a2dp_cmd_pending = A2DP_CTRL_CMD_NONE;
415 
416     /* acknowledge start request */
417     UIPC_Send(UIPC_CH_ID_AV_CTRL, 0, &ack, 1);
418 }
419 
420 
btif_recv_ctrl_data(void)421 static void btif_recv_ctrl_data(void)
422 {
423     UINT8 cmd = 0;
424     int n;
425 
426     n = UIPC_Read(UIPC_CH_ID_AV_CTRL, NULL, &cmd, 1);
427 
428     /* detach on ctrl channel means audioflinger process was terminated */
429     if (n == 0)
430     {
431         APPL_TRACE_EVENT0("CTRL CH DETACHED");
432         UIPC_Close(UIPC_CH_ID_AV_CTRL);
433         /* we can operate only on datachannel, if af client wants to
434            do send additional commands the ctrl channel would be reestablished */
435         //btif_audiopath_detached();
436         return;
437     }
438 
439     APPL_TRACE_DEBUG1("a2dp-ctrl-cmd : %s", dump_a2dp_ctrl_event(cmd));
440 
441     btif_media_cb.a2dp_cmd_pending = cmd;
442 
443     switch(cmd)
444     {
445         case A2DP_CTRL_CMD_CHECK_READY:
446 
447             if (media_task_running == MEDIA_TASK_STATE_SHUTTING_DOWN)
448             {
449                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
450                 return;
451             }
452 
453             /* check whether av is ready to setup a2dp datapath */
454             if ((btif_av_stream_ready() == TRUE) || (btif_av_stream_started_ready() == TRUE))
455             {
456                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
457             }
458             else
459             {
460                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
461             }
462             break;
463 
464         case A2DP_CTRL_CMD_START:
465 
466             if (btif_av_stream_ready() == TRUE)
467             {
468                 /* setup audio data channel listener */
469                 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
470 
471                 /* post start event and wait for audio path to open */
472                 btif_dispatch_sm_event(BTIF_AV_START_STREAM_REQ_EVT, NULL, 0);
473             }
474             else if (btif_av_stream_started_ready())
475             {
476                 /* already started, setup audio data channel listener
477                    and ack back immediately */
478                 UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
479 
480                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
481             }
482             else
483             {
484                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
485                 break;
486             }
487             break;
488 
489         case A2DP_CTRL_CMD_STOP:
490 
491             if (btif_media_cb.is_tx_timer == FALSE)
492             {
493                 /* we are already stopped, just ack back */
494                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
495                 break;
496             }
497 
498             btif_dispatch_sm_event(BTIF_AV_STOP_STREAM_REQ_EVT, NULL, 0);
499             break;
500 
501         case A2DP_CTRL_CMD_SUSPEND:
502             /* local suspend */
503             if (btif_av_stream_started_ready())
504             {
505                 btif_dispatch_sm_event(BTIF_AV_SUSPEND_STREAM_REQ_EVT, NULL, 0);
506             }
507             else
508             {
509                 /* if we are not in started state, just ack back ok and let
510                    audioflinger close the channel. This can happen if we are
511                    remotely suspended */
512                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
513             }
514             break;
515 
516         default:
517             APPL_TRACE_ERROR1("UNSUPPORTED CMD (%d)", cmd);
518             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
519             break;
520     }
521     APPL_TRACE_DEBUG1("a2dp-ctrl-cmd : %s DONE", dump_a2dp_ctrl_event(cmd));
522 }
523 
btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)524 static void btif_a2dp_ctrl_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event)
525 {
526     APPL_TRACE_DEBUG1("A2DP-CTRL-CHANNEL EVENT %s", dump_uipc_event(event));
527 
528     switch(event)
529     {
530         case UIPC_OPEN_EVT:
531             /* fetch av statemachine handle */
532             btif_media_cb.av_sm_hdl = btif_av_get_sm_handle();
533             break;
534 
535         case UIPC_CLOSE_EVT:
536             /* restart ctrl server unless we are shutting down */
537             if (media_task_running == MEDIA_TASK_STATE_ON)
538                 UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
539             break;
540 
541         case UIPC_RX_DATA_READY_EVT:
542             btif_recv_ctrl_data();
543             break;
544 
545         default :
546             APPL_TRACE_ERROR1("### A2DP-CTRL-CHANNEL EVENT %d NOT HANDLED ###", event);
547             break;
548     }
549 }
550 
btif_a2dp_data_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)551 static void btif_a2dp_data_cb(tUIPC_CH_ID ch_id, tUIPC_EVENT event)
552 {
553     APPL_TRACE_DEBUG1("BTIF MEDIA (A2DP-DATA) EVENT %s", dump_uipc_event(event));
554 
555     switch(event)
556     {
557         case UIPC_OPEN_EVT:
558 
559             /*  read directly from media task from here on (keep callback for
560                 connection events */
561             UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL);
562 
563             /* Start the media task to encode SBC */
564             btif_media_task_start_aa_req();
565 
566             /* make sure we update any changed sbc encoder params */
567             btif_a2dp_encoder_update();
568 
569             /* ack back when media task is fully started */
570             break;
571 
572         case UIPC_CLOSE_EVT:
573             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
574             btif_audiopath_detached();
575             break;
576 
577         default :
578             APPL_TRACE_ERROR1("### A2DP-DATA EVENT %d NOT HANDLED ###", event);
579             break;
580     }
581 }
582 
583 
584 /*****************************************************************************
585  **  BTIF ADAPTATION
586  *****************************************************************************/
587 
btif_a2dp_encoder_init(void)588 static void btif_a2dp_encoder_init(void)
589 {
590     UINT16 minmtu;
591     tBTIF_MEDIA_INIT_AUDIO msg;
592     tA2D_SBC_CIE sbc_config;
593 
594     /* lookup table for converting channel mode */
595     UINT16 codec_mode_tbl[5] = { SBC_JOINT_STEREO, SBC_STEREO, SBC_DUAL, 0, SBC_MONO };
596 
597     /* lookup table for converting number of blocks */
598     UINT16 codec_block_tbl[5] = { 16, 12, 8, 0, 4 };
599 
600     /* lookup table to convert freq */
601     UINT16 freq_block_tbl[5] = { SBC_sf48000, SBC_sf44100, SBC_sf32000, 0, SBC_sf16000 };
602 
603     APPL_TRACE_DEBUG0("btif_a2dp_encoder_init");
604 
605     /* Retrieve the current SBC configuration (default if currently not used) */
606     bta_av_co_audio_get_sbc_config(&sbc_config, &minmtu);
607     msg.NumOfSubBands = (sbc_config.num_subbands == A2D_SBC_IE_SUBBAND_4) ? 4 : 8;
608     msg.NumOfBlocks = codec_block_tbl[sbc_config.block_len >> 5];
609     msg.AllocationMethod = (sbc_config.alloc_mthd == A2D_SBC_IE_ALLOC_MD_L) ? SBC_LOUDNESS : SBC_SNR;
610     msg.ChannelMode = codec_mode_tbl[sbc_config.ch_mode >> 1];
611     msg.SamplingFreq = freq_block_tbl[sbc_config.samp_freq >> 5];
612     msg.MtuSize = minmtu;
613 
614     APPL_TRACE_EVENT1("msg.ChannelMode %x", msg.ChannelMode);
615 
616     /* Init the media task to encode SBC properly */
617     btif_media_task_enc_init_req(&msg);
618 }
619 
btif_a2dp_encoder_update(void)620 static void btif_a2dp_encoder_update(void)
621 {
622     UINT16 minmtu;
623     tA2D_SBC_CIE sbc_config;
624     tBTIF_MEDIA_UPDATE_AUDIO msg;
625     UINT8 pref_min;
626     UINT8 pref_max;
627 
628     APPL_TRACE_DEBUG0("btif_a2dp_encoder_update");
629 
630     /* Retrieve the current SBC configuration (default if currently not used) */
631     bta_av_co_audio_get_sbc_config(&sbc_config, &minmtu);
632 
633     APPL_TRACE_DEBUG4("btif_a2dp_encoder_update: Common min_bitpool:%d(0x%x) max_bitpool:%d(0x%x)",
634             sbc_config.min_bitpool, sbc_config.min_bitpool,
635             sbc_config.max_bitpool, sbc_config.max_bitpool);
636 
637     if (sbc_config.min_bitpool > sbc_config.max_bitpool)
638     {
639         APPL_TRACE_ERROR0("btif_a2dp_encoder_update: ERROR btif_a2dp_encoder_update min_bitpool > max_bitpool");
640     }
641 
642     /* check if remote sink has a preferred bitpool range */
643     if (bta_av_co_get_remote_bitpool_pref(&pref_min, &pref_max) == TRUE)
644     {
645         /* adjust our preferred bitpool with the remote preference if within
646            our capable range */
647 
648         if (pref_min < sbc_config.min_bitpool)
649             pref_min = sbc_config.min_bitpool;
650 
651         if (pref_max > sbc_config.max_bitpool)
652             pref_max = sbc_config.max_bitpool;
653 
654         msg.MinBitPool = pref_min;
655         msg.MaxBitPool = pref_max;
656 
657         if ((pref_min != sbc_config.min_bitpool) || (pref_max != sbc_config.max_bitpool))
658         {
659             APPL_TRACE_EVENT2("## adjusted our bitpool range to peer pref [%d:%d] ##",
660                 pref_min, pref_max);
661         }
662     }
663     else
664     {
665         msg.MinBitPool = sbc_config.min_bitpool;
666         msg.MaxBitPool = sbc_config.max_bitpool;
667     }
668 
669     msg.MinMtuSize = minmtu;
670 
671     /* Update the media task to encode SBC properly */
672     btif_media_task_enc_update_req(&msg);
673 }
674 
675 
676 /*****************************************************************************
677 **
678 ** Function        btif_a2dp_start_media_task
679 **
680 ** Description
681 **
682 ** Returns
683 **
684 *******************************************************************************/
685 
btif_a2dp_start_media_task(void)686 int btif_a2dp_start_media_task(void)
687 {
688     int retval;
689 
690     if (media_task_running != MEDIA_TASK_STATE_OFF)
691     {
692         APPL_TRACE_ERROR0("warning : media task already running");
693         return GKI_FAILURE;
694     }
695 
696     APPL_TRACE_EVENT0("## A2DP START MEDIA TASK ##");
697 
698     /* start a2dp media task */
699     retval = GKI_create_task((TASKPTR)btif_media_task, A2DP_MEDIA_TASK,
700                 A2DP_MEDIA_TASK_TASK_STR,
701                 (UINT16 *) ((UINT8 *)a2dp_media_task_stack + A2DP_MEDIA_TASK_STACK_SIZE),
702                 sizeof(a2dp_media_task_stack));
703 
704     if (retval != GKI_SUCCESS)
705         return retval;
706 
707     /* wait for task to come up to sure we are able to send messages to it */
708     while (media_task_running == MEDIA_TASK_STATE_OFF)
709         usleep(10);
710 
711     APPL_TRACE_EVENT0("## A2DP MEDIA TASK STARTED ##");
712 
713     return retval;
714 }
715 
716 /*****************************************************************************
717 **
718 ** Function        btif_a2dp_stop_media_task
719 **
720 ** Description
721 **
722 ** Returns
723 **
724 *******************************************************************************/
725 
btif_a2dp_stop_media_task(void)726 void btif_a2dp_stop_media_task(void)
727 {
728     APPL_TRACE_EVENT0("## A2DP STOP MEDIA TASK ##");
729     GKI_destroy_task(BT_MEDIA_TASK);
730 }
731 
732 /*****************************************************************************
733 **
734 ** Function        btif_a2dp_on_init
735 **
736 ** Description
737 **
738 ** Returns
739 **
740 *******************************************************************************/
741 
btif_a2dp_on_init(void)742 void btif_a2dp_on_init(void)
743 {
744     //tput_mon(1, 0, 1);
745 }
746 
747 
748 /*****************************************************************************
749 **
750 ** Function        btif_a2dp_setup_codec
751 **
752 ** Description
753 **
754 ** Returns
755 **
756 *******************************************************************************/
757 
btif_a2dp_setup_codec(void)758 void btif_a2dp_setup_codec(void)
759 {
760     tBTIF_AV_MEDIA_FEEDINGS media_feeding;
761     tBTIF_STATUS status;
762 
763     APPL_TRACE_EVENT0("## A2DP SETUP CODEC ##");
764 
765     GKI_disable();
766 
767     /* for now hardcode 44.1 khz 16 bit stereo */
768     media_feeding.cfg.pcm.sampling_freq = 44100;
769     media_feeding.cfg.pcm.bit_per_sample = 16;
770     media_feeding.cfg.pcm.num_channel = 2;
771     media_feeding.format = BTIF_AV_CODEC_PCM;
772 
773     if (bta_av_co_audio_set_codec(&media_feeding, &status))
774     {
775         tBTIF_MEDIA_INIT_AUDIO_FEEDING mfeed;
776 
777         /* Init the encoding task */
778         btif_a2dp_encoder_init();
779 
780         /* Build the media task configuration */
781         mfeed.feeding = media_feeding;
782         mfeed.feeding_mode = BTIF_AV_FEEDING_ASYNCHRONOUS;
783         /* Send message to Media task to configure transcoding */
784         btif_media_task_audio_feeding_init_req(&mfeed);
785     }
786 
787     GKI_enable();
788 }
789 
790 
791 /*****************************************************************************
792 **
793 ** Function        btif_a2dp_on_idle
794 **
795 ** Description
796 **
797 ** Returns
798 **
799 *******************************************************************************/
800 
btif_a2dp_on_idle(void)801 void btif_a2dp_on_idle(void)
802 {
803     APPL_TRACE_EVENT0("## ON A2DP IDLE ##");
804 
805     /* Make sure media task is stopped */
806     btif_media_task_stop_aa_req();
807 
808     bta_av_co_init();
809 }
810 
811 /*****************************************************************************
812 **
813 ** Function        btif_a2dp_on_open
814 **
815 ** Description
816 **
817 ** Returns
818 **
819 *******************************************************************************/
820 
btif_a2dp_on_open(void)821 void btif_a2dp_on_open(void)
822 {
823     APPL_TRACE_EVENT0("## ON A2DP OPEN ##");
824 
825     /* always use callback to notify socket events */
826     UIPC_Open(UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb);
827 }
828 
829 /*****************************************************************************
830 **
831 ** Function        btif_a2dp_on_started
832 **
833 ** Description
834 **
835 ** Returns
836 **
837 *******************************************************************************/
838 
btif_a2dp_on_started(tBTA_AV_START * p_av)839 void btif_a2dp_on_started(tBTA_AV_START *p_av)
840 {
841     tBTIF_AV_MEDIA_FEEDINGS media_feeding;
842     tBTIF_STATUS status;
843 
844     APPL_TRACE_EVENT0("## ON A2DP STARTED ##");
845 
846     if (p_av->status == BTA_AV_SUCCESS)
847     {
848         if (p_av->suspending == FALSE)
849         {
850             if (p_av->initiator)
851             {
852                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_SUCCESS);
853             }
854             else
855             {
856                 /* we were remotely started,  make sure codec
857                    is setup before datapath is started */
858                 btif_a2dp_setup_codec();
859             }
860 
861             /* media task is autostarted upon a2dp audiopath connection */
862         }
863     }
864     else
865     {
866         a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
867     }
868 }
869 
870 
871 /*****************************************************************************
872 **
873 ** Function        btif_a2dp_on_stopped
874 **
875 ** Description
876 **
877 ** Returns
878 **
879 *******************************************************************************/
880 
btif_a2dp_on_stopped(tBTA_AV_SUSPEND * p_av)881 void btif_a2dp_on_stopped(tBTA_AV_SUSPEND *p_av)
882 {
883     APPL_TRACE_EVENT0("## ON A2DP STOPPED ##");
884 
885     /* allow using this api for other than suspend */
886     if (p_av != NULL)
887     {
888         if (p_av->status != BTA_AV_SUCCESS)
889         {
890             APPL_TRACE_EVENT1("AV STOP FAILED (%d)", p_av->status);
891 
892             if (p_av->initiator)
893                 a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
894             return;
895         }
896     }
897 
898     /* ensure tx frames are immediately suspended */
899     btif_media_cb.tx_flush = 1;
900 
901     /* request to stop media task  */
902     btif_media_task_aa_tx_flush_req();
903     btif_media_task_stop_aa_req();
904 
905     /* once stream is fully stopped we will ack back */
906 }
907 
908 
909 /*****************************************************************************
910 **
911 ** Function        btif_a2dp_on_suspended
912 **
913 ** Description
914 **
915 ** Returns
916 **
917 *******************************************************************************/
918 
btif_a2dp_on_suspended(tBTA_AV_SUSPEND * p_av)919 void btif_a2dp_on_suspended(tBTA_AV_SUSPEND *p_av)
920 {
921     APPL_TRACE_EVENT0("## ON A2DP SUSPENDED ##");
922 
923     /* check for status failures */
924     if (p_av->status != BTA_AV_SUCCESS)
925     {
926         if (p_av->initiator == TRUE)
927             a2dp_cmd_acknowledge(A2DP_CTRL_ACK_FAILURE);
928     }
929 
930     /* once stream is fully stopped we will ack back */
931 
932     /* ensure tx frames are immediately flushed */
933     btif_media_cb.tx_flush = 1;
934 
935     /* stop timer tick */
936     btif_media_task_stop_aa_req();
937 }
938 
939 /* when true media task discards any tx frames */
btif_a2dp_set_tx_flush(BOOLEAN enable)940 void btif_a2dp_set_tx_flush(BOOLEAN enable)
941 {
942     APPL_TRACE_EVENT1("## DROP TX %d ##", enable);
943     btif_media_cb.tx_flush = enable;
944 }
945 
946 /*****************************************************************************
947 **
948 ** Function        btif_calc_pcmtime
949 **
950 ** Description     Calculates the pcmtime equivalent of a datapacket
951 **
952 ** Returns         microseconds
953 **
954 *******************************************************************************/
955 
btif_calc_pcmtime(UINT32 bytes_processed)956 static int btif_calc_pcmtime(UINT32 bytes_processed)
957 {
958     int pcm_time_us = 0;
959     tBTIF_AV_MEDIA_FEED_CFG *p_cfg;
960 
961     p_cfg = &btif_media_cb.media_feeding.cfg;
962 
963     /* calculate corresponding pcm time based on data processed */
964     switch(btif_media_cb.media_feeding.format)
965     {
966         case BTIF_AV_CODEC_PCM:
967             pcm_time_us = (bytes_processed*1000000)/
968                           (p_cfg->pcm.num_channel*p_cfg->pcm.sampling_freq*p_cfg->pcm.bit_per_sample/8);
969             break;
970 
971         default :
972             APPL_TRACE_ERROR1("mediafeeding format invalid : %d", btif_media_cb.media_feeding.format);
973             break;
974     }
975 
976     return pcm_time_us;
977 }
978 
979 
980 /*******************************************************************************
981  **
982  ** Function         btif_media_task_aa_handle_timer
983  **
984  ** Description
985  **
986  ** Returns          void
987  **
988  *******************************************************************************/
989 
btif_media_task_aa_handle_timer(void)990 static void btif_media_task_aa_handle_timer(void)
991 {
992 #if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
993     static UINT16 Debug = 0;
994     APPL_TRACE_DEBUG1("btif_media_task_aa_handle_timer: %d", Debug++);
995 #endif
996 
997     log_tstamps_us("media task tx timer");
998 
999 #if (BTA_AV_INCLUDED == TRUE)
1000     btif_media_send_aa_frame();
1001 #endif
1002 }
1003 
1004 #if (BTA_AV_INCLUDED == TRUE)
1005 /*******************************************************************************
1006  **
1007  ** Function         btif_media_task_aa_handle_timer
1008  **
1009  ** Description
1010  **
1011  ** Returns          void
1012  **
1013  *******************************************************************************/
btif_media_task_aa_handle_uipc_rx_rdy(void)1014 static void btif_media_task_aa_handle_uipc_rx_rdy(void)
1015 {
1016 #if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
1017     static UINT16 Debug = 0;
1018     APPL_TRACE_DEBUG1("btif_media_task_aa_handle_uipc_rx_rdy: %d", Debug++);
1019 #endif
1020 
1021     /* process all the UIPC data */
1022     btif_media_aa_prep_2_send(0xFF);
1023 
1024     /* send it */
1025     VERBOSE("btif_media_task_aa_handle_uipc_rx_rdy calls bta_av_ci_src_data_ready");
1026     bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
1027 }
1028 #endif
1029 
1030 /*******************************************************************************
1031  **
1032  ** Function         btif_media_task_init
1033  **
1034  ** Description
1035  **
1036  ** Returns          void
1037  **
1038  *******************************************************************************/
1039 
btif_media_task_init(void)1040 void btif_media_task_init(void)
1041 {
1042     memset(&(btif_media_cb), 0, sizeof(btif_media_cb));
1043 
1044     UIPC_Init(NULL);
1045 
1046 #if (BTA_AV_INCLUDED == TRUE)
1047     UIPC_Open(UIPC_CH_ID_AV_CTRL , btif_a2dp_ctrl_cb);
1048 #endif
1049 
1050 
1051 }
1052 /*******************************************************************************
1053  **
1054  ** Function         btif_media_task
1055  **
1056  ** Description      Task for SBC encoder.  This task receives an
1057  **                  event when the waveIn interface has a pcm data buffer
1058  **                  ready.  On receiving the event, handle all ready pcm
1059  **                  data buffers.  If stream is started, run the SBC encoder
1060  **                  on each chunk of pcm samples and build an output packet
1061  **                  consisting of one or more encoded SBC frames.
1062  **
1063  ** Returns          void
1064  **
1065  *******************************************************************************/
btif_media_task(void * p)1066 int btif_media_task(void *p)
1067 {
1068     UINT16 event;
1069     BT_HDR *p_msg;
1070 
1071     VERBOSE("================ MEDIA TASK STARTING ================");
1072 
1073     btif_media_task_init();
1074 
1075     media_task_running = MEDIA_TASK_STATE_ON;
1076 
1077     raise_priority_a2dp(TASK_HIGH_MEDIA);
1078 
1079     while (1)
1080     {
1081         event = GKI_wait(0xffff, 0);
1082 
1083         VERBOSE("================= MEDIA TASK EVENT %d ===============", event);
1084 
1085         if (event & BTIF_MEDIA_TASK_CMD)
1086         {
1087             /* Process all messages in the queue */
1088             while ((p_msg = (BT_HDR *) GKI_read_mbox(BTIF_MEDIA_TASK_CMD_MBOX)) != NULL)
1089             {
1090                 btif_media_task_handle_cmd(p_msg);
1091             }
1092         }
1093 
1094         if (event & BTIF_MEDIA_TASK_DATA)
1095         {
1096             /* Process all messages in the queue */
1097             while ((p_msg = (BT_HDR *) GKI_read_mbox(BTIF_MEDIA_TASK_DATA_MBOX)) != NULL)
1098             {
1099                 btif_media_task_handle_media(p_msg);
1100             }
1101         }
1102 
1103         if (event & BTIF_MEDIA_AA_TASK_TIMER)
1104         {
1105             /* advance audio timer expiration */
1106             btif_media_task_aa_handle_timer();
1107         }
1108 
1109 
1110         VERBOSE("=============== MEDIA TASK EVENT %d DONE ============", event);
1111 
1112         /* When we get this event we exit the task  - should only happen on GKI_shutdown  */
1113         if (event & BTIF_MEDIA_TASK_KILL)
1114         {
1115             /* make sure no channels are restarted while shutting down */
1116             media_task_running = MEDIA_TASK_STATE_SHUTTING_DOWN;
1117 
1118             /* this calls blocks until uipc is fully closed */
1119             UIPC_Close(UIPC_CH_ID_ALL);
1120             break;
1121         }
1122     }
1123 
1124     /* Clear media task flag */
1125     media_task_running = MEDIA_TASK_STATE_OFF;
1126 
1127     APPL_TRACE_DEBUG0("MEDIA TASK EXITING");
1128 
1129     return 0;
1130 }
1131 
1132 
1133 /*******************************************************************************
1134  **
1135  ** Function         btif_media_task_send_cmd_evt
1136  **
1137  ** Description
1138  **
1139  ** Returns          TRUE is success
1140  **
1141  *******************************************************************************/
btif_media_task_send_cmd_evt(UINT16 Evt)1142 BOOLEAN btif_media_task_send_cmd_evt(UINT16 Evt)
1143 {
1144     BT_HDR *p_buf;
1145     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1146     {
1147         return FALSE;
1148     }
1149 
1150     p_buf->event = Evt;
1151 
1152     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1153     return TRUE;
1154 }
1155 
1156 /*******************************************************************************
1157  **
1158  ** Function         btif_media_flush_q
1159  **
1160  ** Description
1161  **
1162  ** Returns          void
1163  **
1164  *******************************************************************************/
btif_media_flush_q(BUFFER_Q * p_q)1165 static void btif_media_flush_q(BUFFER_Q *p_q)
1166 {
1167     while (GKI_IS_QUEUE_EMPTY(p_q) == FALSE)
1168     {
1169         GKI_freebuf(GKI_dequeue(p_q));
1170     }
1171 }
1172 
1173 
1174 /*******************************************************************************
1175  **
1176  ** Function         btif_media_task_handle_cmd
1177  **
1178  ** Description
1179  **
1180  ** Returns          void
1181  **
1182  *******************************************************************************/
btif_media_task_handle_cmd(BT_HDR * p_msg)1183 static void btif_media_task_handle_cmd(BT_HDR *p_msg)
1184 {
1185     VERBOSE("btif_media_task_handle_cmd : %d %s", p_msg->event, dump_media_event(p_msg->event));
1186 
1187     switch (p_msg->event)
1188     {
1189 #if (BTA_AV_INCLUDED == TRUE)
1190     case BTIF_MEDIA_START_AA_TX:
1191         btif_media_task_aa_start_tx();
1192         break;
1193     case BTIF_MEDIA_STOP_AA_TX:
1194         btif_media_task_aa_stop_tx();
1195         break;
1196     case BTIF_MEDIA_SBC_ENC_INIT:
1197         btif_media_task_enc_init(p_msg);
1198         break;
1199     case BTIF_MEDIA_SBC_ENC_UPDATE:
1200         btif_media_task_enc_update(p_msg);
1201         break;
1202     case BTIF_MEDIA_AUDIO_FEEDING_INIT:
1203         btif_media_task_audio_feeding_init(p_msg);
1204         break;
1205     case BTIF_MEDIA_FLUSH_AA_TX:
1206         btif_media_task_aa_tx_flush(p_msg);
1207         break;
1208     case BTIF_MEDIA_UIPC_RX_RDY:
1209         btif_media_task_aa_handle_uipc_rx_rdy();
1210         break;
1211 #endif
1212     default:
1213         APPL_TRACE_ERROR1("ERROR in btif_media_task_handle_cmd unknown event %d", p_msg->event);
1214     }
1215     GKI_freebuf(p_msg);
1216     VERBOSE("btif_media_task_handle_cmd : %s DONE", dump_media_event(p_msg->event));
1217 }
1218 
1219 /*******************************************************************************
1220  **
1221  ** Function         btif_media_task_handle_media
1222  **
1223  ** Description
1224  **
1225  ** Returns          void
1226  **
1227  *******************************************************************************/
btif_media_task_handle_media(BT_HDR * p_msg)1228 static void btif_media_task_handle_media(BT_HDR *p_msg)
1229 {
1230     APPL_TRACE_ERROR0("ERROR btif_media_task_handle_media: not in use");
1231 
1232     GKI_freebuf(p_msg);
1233 }
1234 
1235 
1236 
1237 
1238 #if (BTA_AV_INCLUDED == TRUE)
1239 /*******************************************************************************
1240  **
1241  ** Function         btif_media_task_enc_init_req
1242  **
1243  ** Description
1244  **
1245  ** Returns          TRUE is success
1246  **
1247  *******************************************************************************/
btif_media_task_enc_init_req(tBTIF_MEDIA_INIT_AUDIO * p_msg)1248 BOOLEAN btif_media_task_enc_init_req(tBTIF_MEDIA_INIT_AUDIO *p_msg)
1249 {
1250     tBTIF_MEDIA_INIT_AUDIO *p_buf;
1251     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_INIT_AUDIO))))
1252     {
1253         return FALSE;
1254     }
1255 
1256     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO));
1257     p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_INIT;
1258 
1259     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1260     return TRUE;
1261 }
1262 
1263 /*******************************************************************************
1264  **
1265  ** Function         btif_media_task_enc_update_req
1266  **
1267  ** Description
1268  **
1269  ** Returns          TRUE is success
1270  **
1271  *******************************************************************************/
btif_media_task_enc_update_req(tBTIF_MEDIA_UPDATE_AUDIO * p_msg)1272 BOOLEAN btif_media_task_enc_update_req(tBTIF_MEDIA_UPDATE_AUDIO *p_msg)
1273 {
1274     tBTIF_MEDIA_UPDATE_AUDIO *p_buf;
1275     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_UPDATE_AUDIO))))
1276     {
1277         return FALSE;
1278     }
1279 
1280     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_UPDATE_AUDIO));
1281     p_buf->hdr.event = BTIF_MEDIA_SBC_ENC_UPDATE;
1282 
1283     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1284     return TRUE;
1285 }
1286 
1287 /*******************************************************************************
1288  **
1289  ** Function         btif_media_task_audio_feeding_init_req
1290  **
1291  ** Description
1292  **
1293  ** Returns          TRUE is success
1294  **
1295  *******************************************************************************/
btif_media_task_audio_feeding_init_req(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_msg)1296 BOOLEAN btif_media_task_audio_feeding_init_req(tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_msg)
1297 {
1298     tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_buf;
1299     if (NULL == (p_buf = GKI_getbuf(sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING))))
1300     {
1301         return FALSE;
1302     }
1303 
1304     memcpy(p_buf, p_msg, sizeof(tBTIF_MEDIA_INIT_AUDIO_FEEDING));
1305     p_buf->hdr.event = BTIF_MEDIA_AUDIO_FEEDING_INIT;
1306 
1307     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1308     return TRUE;
1309 }
1310 
1311 /*******************************************************************************
1312  **
1313  ** Function         btif_media_task_start_aa_req
1314  **
1315  ** Description
1316  **
1317  ** Returns          TRUE is success
1318  **
1319  *******************************************************************************/
btif_media_task_start_aa_req(void)1320 BOOLEAN btif_media_task_start_aa_req(void)
1321 {
1322     BT_HDR *p_buf;
1323     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1324     {
1325         APPL_TRACE_EVENT0("GKI failed");
1326         return FALSE;
1327     }
1328 
1329     p_buf->event = BTIF_MEDIA_START_AA_TX;
1330 
1331     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1332     return TRUE;
1333 }
1334 
1335 /*******************************************************************************
1336  **
1337  ** Function         btif_media_task_stop_aa_req
1338  **
1339  ** Description
1340  **
1341  ** Returns          TRUE is success
1342  **
1343  *******************************************************************************/
btif_media_task_stop_aa_req(void)1344 BOOLEAN btif_media_task_stop_aa_req(void)
1345 {
1346     BT_HDR *p_buf;
1347     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1348     {
1349         return FALSE;
1350     }
1351 
1352     p_buf->event = BTIF_MEDIA_STOP_AA_TX;
1353 
1354     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1355     return TRUE;
1356 }
1357 
1358 /*******************************************************************************
1359  **
1360  ** Function         btif_media_task_aa_tx_flush_req
1361  **
1362  ** Description
1363  **
1364  ** Returns          TRUE is success
1365  **
1366  *******************************************************************************/
btif_media_task_aa_tx_flush_req(void)1367 BOOLEAN btif_media_task_aa_tx_flush_req(void)
1368 {
1369     BT_HDR *p_buf;
1370     if (NULL == (p_buf = GKI_getbuf(sizeof(BT_HDR))))
1371     {
1372         return FALSE;
1373     }
1374 
1375     p_buf->event = BTIF_MEDIA_FLUSH_AA_TX;
1376 
1377     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_buf);
1378     return TRUE;
1379 }
1380 
1381 /*******************************************************************************
1382  **
1383  ** Function         btif_media_task_aa_tx_flush
1384  **
1385  ** Description
1386  **
1387  ** Returns          void
1388  **
1389  *******************************************************************************/
btif_media_task_aa_tx_flush(BT_HDR * p_msg)1390 static void btif_media_task_aa_tx_flush(BT_HDR *p_msg)
1391 {
1392     /* Flush all enqueued GKI music buffers (encoded) */
1393     APPL_TRACE_DEBUG0("btif_media_task_aa_tx_flush");
1394 
1395     btif_media_flush_q(&(btif_media_cb.TxAaQ));
1396 
1397     UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REQ_RX_FLUSH, NULL);
1398 }
1399 
1400 /*******************************************************************************
1401  **
1402  ** Function       btif_media_task_enc_init
1403  **
1404  ** Description    Initialize encoding task
1405  **
1406  ** Returns        void
1407  **
1408  *******************************************************************************/
btif_media_task_enc_init(BT_HDR * p_msg)1409 static void btif_media_task_enc_init(BT_HDR *p_msg)
1410 {
1411     tBTIF_MEDIA_INIT_AUDIO *pInitAudio = (tBTIF_MEDIA_INIT_AUDIO *) p_msg;
1412 
1413     APPL_TRACE_DEBUG0("btif_media_task_enc_init");
1414 
1415     btif_media_cb.timestamp = 0;
1416 
1417     /* SBC encoder config (enforced even if not used) */
1418     btif_media_cb.encoder.s16ChannelMode = pInitAudio->ChannelMode;
1419     btif_media_cb.encoder.s16NumOfSubBands = pInitAudio->NumOfSubBands;
1420     btif_media_cb.encoder.s16NumOfBlocks = pInitAudio->NumOfBlocks;
1421     btif_media_cb.encoder.s16AllocationMethod = pInitAudio->AllocationMethod;
1422     btif_media_cb.encoder.s16SamplingFreq = pInitAudio->SamplingFreq;
1423 
1424     btif_media_cb.encoder.u16BitRate = DEFAULT_SBC_BITRATE;
1425     /* Default transcoding is PCM to SBC, modified by feeding configuration */
1426     btif_media_cb.TxTranscoding = BTIF_MEDIA_TRSCD_PCM_2_SBC;
1427     btif_media_cb.TxAaMtuSize = ((BTIF_MEDIA_AA_BUF_SIZE-BTIF_MEDIA_AA_SBC_OFFSET-sizeof(BT_HDR))
1428             < pInitAudio->MtuSize) ? (BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET
1429             - sizeof(BT_HDR)) : pInitAudio->MtuSize;
1430 
1431     APPL_TRACE_EVENT3("btif_media_task_enc_init busy %d, mtu %d, peer mtu %d",
1432                      btif_media_cb.busy_level, btif_media_cb.TxAaMtuSize, pInitAudio->MtuSize);
1433     APPL_TRACE_EVENT6("      ch mode %d, subnd %d, nb blk %d, alloc %d, rate %d, freq %d",
1434             btif_media_cb.encoder.s16ChannelMode, btif_media_cb.encoder.s16NumOfSubBands,
1435             btif_media_cb.encoder.s16NumOfBlocks,
1436             btif_media_cb.encoder.s16AllocationMethod, btif_media_cb.encoder.u16BitRate,
1437             btif_media_cb.encoder.s16SamplingFreq);
1438 
1439     /* Reset entirely the SBC encoder */
1440     SBC_Encoder_Init(&(btif_media_cb.encoder));
1441     APPL_TRACE_DEBUG1("btif_media_task_enc_init bit pool %d", btif_media_cb.encoder.s16BitPool);
1442 }
1443 
1444 /*******************************************************************************
1445  **
1446  ** Function       btif_media_task_enc_update
1447  **
1448  ** Description    Update encoding task
1449  **
1450  ** Returns        void
1451  **
1452  *******************************************************************************/
1453 
btif_media_task_enc_update(BT_HDR * p_msg)1454 static void btif_media_task_enc_update(BT_HDR *p_msg)
1455 {
1456     tBTIF_MEDIA_UPDATE_AUDIO * pUpdateAudio = (tBTIF_MEDIA_UPDATE_AUDIO *) p_msg;
1457     SBC_ENC_PARAMS *pstrEncParams = &btif_media_cb.encoder;
1458     UINT16 s16SamplingFreq;
1459     SINT16 s16BitPool;
1460     SINT16 s16BitRate;
1461     SINT16 s16FrameLen;
1462     UINT8 protect = 0;
1463 
1464     APPL_TRACE_DEBUG3("btif_media_task_enc_update : minmtu %d, maxbp %d minbp %d",
1465             pUpdateAudio->MinMtuSize, pUpdateAudio->MaxBitPool, pUpdateAudio->MinBitPool);
1466 
1467     /* Only update the bitrate and MTU size while timer is running to make sure it has been initialized */
1468     //if (btif_media_cb.is_tx_timer)
1469     {
1470         btif_media_cb.TxAaMtuSize = ((BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET - sizeof(BT_HDR))
1471                 < pUpdateAudio->MinMtuSize) ? (BTIF_MEDIA_AA_BUF_SIZE - BTIF_MEDIA_AA_SBC_OFFSET
1472                 - sizeof(BT_HDR)) : pUpdateAudio->MinMtuSize;
1473 
1474         /* Set the initial target bit rate */
1475         pstrEncParams->u16BitRate = DEFAULT_SBC_BITRATE;
1476 
1477         if (pstrEncParams->s16SamplingFreq == SBC_sf16000)
1478             s16SamplingFreq = 16000;
1479         else if (pstrEncParams->s16SamplingFreq == SBC_sf32000)
1480             s16SamplingFreq = 32000;
1481         else if (pstrEncParams->s16SamplingFreq == SBC_sf44100)
1482             s16SamplingFreq = 44100;
1483         else
1484             s16SamplingFreq = 48000;
1485 
1486         do
1487         {
1488             if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) ||
1489                 (pstrEncParams->s16ChannelMode == SBC_STEREO) )
1490             {
1491                 s16BitPool = (SINT16)( (pstrEncParams->u16BitRate *
1492                     pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq)
1493                     -( (32 + (4 * pstrEncParams->s16NumOfSubBands *
1494                     pstrEncParams->s16NumOfChannels)
1495                     + ( (pstrEncParams->s16ChannelMode - 2) *
1496                     pstrEncParams->s16NumOfSubBands )   )
1497                     / pstrEncParams->s16NumOfBlocks) );
1498 
1499                 s16FrameLen = 4 + (4*pstrEncParams->s16NumOfSubBands*
1500                     pstrEncParams->s16NumOfChannels)/8
1501                     + ( ((pstrEncParams->s16ChannelMode - 2) *
1502                     pstrEncParams->s16NumOfSubBands)
1503                     + (pstrEncParams->s16NumOfBlocks * s16BitPool) ) / 8;
1504 
1505                 s16BitRate = (8 * s16FrameLen * s16SamplingFreq)
1506                     / (pstrEncParams->s16NumOfSubBands *
1507                     pstrEncParams->s16NumOfBlocks * 1000);
1508 
1509                 if (s16BitRate > pstrEncParams->u16BitRate)
1510                     s16BitPool--;
1511 
1512                 if(pstrEncParams->s16NumOfSubBands == 8)
1513                     s16BitPool = (s16BitPool > 255) ? 255 : s16BitPool;
1514                 else
1515                     s16BitPool = (s16BitPool > 128) ? 128 : s16BitPool;
1516             }
1517             else
1518             {
1519                 s16BitPool = (SINT16)( ((pstrEncParams->s16NumOfSubBands *
1520                     pstrEncParams->u16BitRate * 1000)
1521                     / (s16SamplingFreq * pstrEncParams->s16NumOfChannels))
1522                     -( ( (32 / pstrEncParams->s16NumOfChannels) +
1523                     (4 * pstrEncParams->s16NumOfSubBands) )
1524                     /   pstrEncParams->s16NumOfBlocks ) );
1525 
1526                 pstrEncParams->s16BitPool = (s16BitPool >
1527                     (16 * pstrEncParams->s16NumOfSubBands))
1528                     ? (16*pstrEncParams->s16NumOfSubBands) : s16BitPool;
1529             }
1530 
1531             if (s16BitPool < 0)
1532             {
1533                 s16BitPool = 0;
1534             }
1535 
1536             APPL_TRACE_EVENT2("bitpool candidate : %d (%d kbps)", s16BitPool, pstrEncParams->u16BitRate);
1537 
1538             if (s16BitPool > pUpdateAudio->MaxBitPool)
1539             {
1540                 APPL_TRACE_WARNING1("btif_media_task_enc_update computed bitpool too large (%d)", s16BitPool);
1541                 /* Decrease bitrate */
1542                 btif_media_cb.encoder.u16BitRate -= BTIF_MEDIA_BITRATE_STEP;
1543                 /* Record that we have decreased the bitrate */
1544                 protect |= 1;
1545             }
1546             else if (s16BitPool < pUpdateAudio->MinBitPool)
1547             {
1548                 APPL_TRACE_WARNING1("btif_media_task_enc_update computed bitpool too small (%d)", s16BitPool);
1549                 /* Increase bitrate */
1550                 btif_media_cb.encoder.u16BitRate += BTIF_MEDIA_BITRATE_STEP;
1551                 /* Record that we have increased the bitrate */
1552                 protect |= 2;
1553             }
1554             else
1555             {
1556                 break;
1557             }
1558             /* In case we have already increased and decreased the bitrate, just stop */
1559             if (protect == 3)
1560             {
1561                 APPL_TRACE_ERROR0("btif_media_task_enc_update could not find bitpool in range");
1562                 break;
1563             }
1564         } while (1);
1565 
1566         /* Finally update the bitpool in the encoder structure */
1567         pstrEncParams->s16BitPool = s16BitPool;
1568 
1569         APPL_TRACE_DEBUG2("btif_media_task_enc_update final bit rate %d, final bit pool %d",
1570                 btif_media_cb.encoder.u16BitRate, btif_media_cb.encoder.s16BitPool);
1571 
1572         /* make sure we reinitialize encoder with new settings */
1573         SBC_Encoder_Init(&(btif_media_cb.encoder));
1574     }
1575 }
1576 
1577 /*******************************************************************************
1578  **
1579  ** Function         btif_media_task_pcm2sbc_init
1580  **
1581  ** Description      Init encoding task for PCM to SBC according to feeding
1582  **
1583  ** Returns          void
1584  **
1585  *******************************************************************************/
btif_media_task_pcm2sbc_init(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_feeding)1586 static void btif_media_task_pcm2sbc_init(tBTIF_MEDIA_INIT_AUDIO_FEEDING * p_feeding)
1587 {
1588     BOOLEAN reconfig_needed = FALSE;
1589 
1590     APPL_TRACE_DEBUG0("PCM feeding:");
1591     APPL_TRACE_DEBUG1("sampling_freq:%d", p_feeding->feeding.cfg.pcm.sampling_freq);
1592     APPL_TRACE_DEBUG1("num_channel:%d", p_feeding->feeding.cfg.pcm.num_channel);
1593     APPL_TRACE_DEBUG1("bit_per_sample:%d", p_feeding->feeding.cfg.pcm.bit_per_sample);
1594 
1595 
1596     /* Check the PCM feeding sampling_freq */
1597     switch (p_feeding->feeding.cfg.pcm.sampling_freq)
1598     {
1599         case  8000:
1600         case 12000:
1601         case 16000:
1602         case 24000:
1603         case 32000:
1604         case 48000:
1605             /* For these sampling_freq the AV connection must be 48000 */
1606             if (btif_media_cb.encoder.s16SamplingFreq != SBC_sf48000)
1607             {
1608                 /* Reconfiguration needed at 48000 */
1609                 APPL_TRACE_DEBUG0("SBC Reconfiguration needed at 48000");
1610                 btif_media_cb.encoder.s16SamplingFreq = SBC_sf48000;
1611                 reconfig_needed = TRUE;
1612             }
1613             break;
1614 
1615         case 11025:
1616         case 22050:
1617         case 44100:
1618             /* For these sampling_freq the AV connection must be 44100 */
1619             if (btif_media_cb.encoder.s16SamplingFreq != SBC_sf44100)
1620             {
1621                 /* Reconfiguration needed at 44100 */
1622                 APPL_TRACE_DEBUG0("SBC Reconfiguration needed at 44100");
1623                 btif_media_cb.encoder.s16SamplingFreq = SBC_sf44100;
1624                 reconfig_needed = TRUE;
1625             }
1626             break;
1627         default:
1628             APPL_TRACE_DEBUG0("Feeding PCM sampling_freq unsupported");
1629             break;
1630     }
1631 
1632     /* Some AV Headsets do not support Mono => always ask for Stereo */
1633     if (btif_media_cb.encoder.s16ChannelMode == SBC_MONO)
1634     {
1635         APPL_TRACE_DEBUG0("SBC Reconfiguration needed in Stereo");
1636         btif_media_cb.encoder.s16ChannelMode = SBC_JOINT_STEREO;
1637         reconfig_needed = TRUE;
1638     }
1639 
1640     if (reconfig_needed != FALSE)
1641     {
1642         APPL_TRACE_DEBUG0("btif_media_task_pcm2sbc_init calls SBC_Encoder_Init");
1643         APPL_TRACE_DEBUG1("btif_media_task_pcm2sbc_init mtu %d", btif_media_cb.TxAaMtuSize);
1644         APPL_TRACE_DEBUG6("btif_media_task_pcm2sbc_init ch mode %d, nbsubd %d, nb blk %d, alloc method %d, bit rate %d, Smp freq %d",
1645                 btif_media_cb.encoder.s16ChannelMode, btif_media_cb.encoder.s16NumOfSubBands, btif_media_cb.encoder.s16NumOfBlocks,
1646                 btif_media_cb.encoder.s16AllocationMethod, btif_media_cb.encoder.u16BitRate, btif_media_cb.encoder.s16SamplingFreq);
1647         SBC_Encoder_Init(&(btif_media_cb.encoder));
1648     }
1649     else
1650     {
1651         APPL_TRACE_DEBUG0("btif_media_task_pcm2sbc_init no SBC reconfig needed");
1652     }
1653 }
1654 
1655 
1656 /*******************************************************************************
1657  **
1658  ** Function         btif_media_task_audio_feeding_init
1659  **
1660  ** Description      Initialize the audio path according to the feeding format
1661  **
1662  ** Returns          void
1663  **
1664  *******************************************************************************/
btif_media_task_audio_feeding_init(BT_HDR * p_msg)1665 static void btif_media_task_audio_feeding_init(BT_HDR *p_msg)
1666 {
1667     tBTIF_MEDIA_INIT_AUDIO_FEEDING *p_feeding = (tBTIF_MEDIA_INIT_AUDIO_FEEDING *) p_msg;
1668 
1669     APPL_TRACE_DEBUG1("btif_media_task_audio_feeding_init format:%d", p_feeding->feeding.format);
1670 
1671     /* Save Media Feeding information */
1672     btif_media_cb.feeding_mode = p_feeding->feeding_mode;
1673     btif_media_cb.media_feeding = p_feeding->feeding;
1674 
1675     /* Handle different feeding formats */
1676     switch (p_feeding->feeding.format)
1677     {
1678         case BTIF_AV_CODEC_PCM:
1679             btif_media_cb.TxTranscoding = BTIF_MEDIA_TRSCD_PCM_2_SBC;
1680             btif_media_task_pcm2sbc_init(p_feeding);
1681             break;
1682 
1683         default :
1684             APPL_TRACE_ERROR1("unknown feeding format %d", p_feeding->feeding.format);
1685             break;
1686     }
1687 }
1688 
1689 /*******************************************************************************
1690  **
1691  ** Function         btif_media_task_uipc_cback
1692  **
1693  ** Description      UIPC call back function for synchronous mode only
1694  **
1695  ** Returns          void
1696  **
1697  *******************************************************************************/
btif_media_task_uipc_cback(BT_HDR * p_msg)1698 static void btif_media_task_uipc_cback(BT_HDR *p_msg)
1699 {
1700     /* Sanity check */
1701     if (NULL == p_msg)
1702     {
1703         return;
1704     }
1705 
1706     /* Just handle RX_EVT */
1707     if (p_msg->event != UIPC_RX_DATA_EVT)
1708     {
1709         return;
1710     }
1711 
1712     p_msg->event = BTIF_MEDIA_UIPC_RX_RDY;
1713 
1714     GKI_send_msg(BT_MEDIA_TASK, BTIF_MEDIA_TASK_CMD_MBOX, p_msg);
1715 }
1716 
1717 /*******************************************************************************
1718  **
1719  ** Function         btif_media_task_feeding_state_reset
1720  **
1721  ** Description      Reset the media feeding state
1722  **
1723  ** Returns          void
1724  **
1725  *******************************************************************************/
btif_media_task_feeding_state_reset(void)1726 static void btif_media_task_feeding_state_reset(void)
1727 {
1728     /* By default, just clear the entire state */
1729     memset(&btif_media_cb.media_feeding_state, 0, sizeof(btif_media_cb.media_feeding_state));
1730 }
1731 /*******************************************************************************
1732  **
1733  ** Function         btif_media_task_aa_start_tx
1734  **
1735  ** Description      Start media task encoding
1736  **
1737  ** Returns          void
1738  **
1739  *******************************************************************************/
btif_media_task_aa_start_tx(void)1740 static void btif_media_task_aa_start_tx(void)
1741 {
1742     APPL_TRACE_DEBUG2("btif_media_task_aa_start_tx is timer %d, feeding mode %d",
1743             btif_media_cb.is_tx_timer, btif_media_cb.feeding_mode);
1744 
1745 
1746     /* Use a timer to poll the UIPC, get rid of the UIPC call back */
1747     // UIPC_Ioctl(UIPC_CH_ID_AV_AUDIO, UIPC_REG_CBACK, NULL);
1748 
1749     btif_media_cb.is_tx_timer = TRUE;
1750 
1751     /* Reset the media feeding state */
1752     btif_media_task_feeding_state_reset();
1753 
1754     APPL_TRACE_EVENT2("starting timer %d ticks (%d)", GKI_MS_TO_TICKS(BTIF_MEDIA_TIME_TICK), TICKS_PER_SEC);
1755     GKI_start_timer(BTIF_MEDIA_AA_TASK_TIMER_ID, GKI_MS_TO_TICKS(BTIF_MEDIA_TIME_TICK), TRUE);
1756 }
1757 
1758 /*******************************************************************************
1759  **
1760  ** Function         btif_media_task_aa_stop_tx
1761  **
1762  ** Description      Stop media task encoding
1763  **
1764  ** Returns          void
1765  **
1766  *******************************************************************************/
btif_media_task_aa_stop_tx(void)1767 static void btif_media_task_aa_stop_tx(void)
1768 {
1769     APPL_TRACE_DEBUG1("btif_media_task_aa_stop_tx is timer: %d", btif_media_cb.is_tx_timer);
1770 
1771     /* Stop the timer first */
1772     GKI_stop_timer(BTIF_MEDIA_AA_TASK_TIMER_ID);
1773     btif_media_cb.is_tx_timer = FALSE;
1774 
1775     UIPC_Close(UIPC_CH_ID_AV_AUDIO);
1776 
1777     /* audio engine stopped, reset tx suspended flag */
1778     btif_media_cb.tx_flush = 0;
1779 
1780     /* Reset the media feeding state */
1781     btif_media_task_feeding_state_reset();
1782 }
1783 
1784 /*******************************************************************************
1785  **
1786  ** Function         btif_get_num_aa_frame
1787  **
1788  ** Description
1789  **
1790  ** Returns          The number of media frames in this time slice
1791  **
1792  *******************************************************************************/
1793 
1794 
btif_get_num_aa_frame(void)1795 static UINT8 btif_get_num_aa_frame(void)
1796 {
1797     UINT8 result=0;
1798 
1799     switch (btif_media_cb.TxTranscoding)
1800     {
1801         case BTIF_MEDIA_TRSCD_PCM_2_SBC:
1802             switch (btif_media_cb.encoder.s16SamplingFreq)
1803             {
1804             case SBC_sf16000:
1805                 if (!btif_media_cb.scaling_disabled &&
1806                     (btif_media_cb.media_feeding_state.pcm.aa_frame_counter++ % 2) == 0)
1807                 {
1808                     result = BTIF_MEDIA_FR_PER_TICKS_16-1;
1809                 }
1810                 else
1811                 {
1812                     result = BTIF_MEDIA_FR_PER_TICKS_16;
1813                 }
1814                 break;
1815 
1816             case SBC_sf32000:
1817                 result = BTIF_MEDIA_FR_PER_TICKS_32;
1818                 break;
1819 
1820             case SBC_sf48000:
1821                 if (!btif_media_cb.scaling_disabled &&
1822                     (btif_media_cb.media_feeding_state.pcm.aa_frame_counter++ % 2) == 0)
1823                 {
1824                     result = BTIF_MEDIA_FR_PER_TICKS_48-1;
1825                 }
1826                 else
1827                 {
1828                     result = BTIF_MEDIA_FR_PER_TICKS_48;
1829                 }
1830                 break;
1831 
1832             case SBC_sf44100:
1833                 if (!btif_media_cb.scaling_disabled &&
1834                     (btif_media_cb.media_feeding_state.pcm.aa_frame_counter++ % 64) < 7)
1835                 {
1836                     result = BTIF_MEDIA_FR_PER_TICKS_44_1-1;
1837                 }
1838                 else
1839                 {
1840                     result = BTIF_MEDIA_FR_PER_TICKS_44_1;
1841                 }
1842                 break;
1843             }
1844 
1845             VERBOSE("WRITE %d FRAMES", result);
1846             break;
1847 
1848         default:
1849             APPL_TRACE_ERROR1("ERROR btif_get_num_aa_frame Unsupported transcoding format 0x%x",
1850                     btif_media_cb.TxTranscoding);
1851             result = 0;
1852             break;
1853     }
1854 
1855 #if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
1856     APPL_TRACE_DEBUG1("btif_get_num_aa_frame returns %d", result);
1857 #endif
1858 
1859     return result;
1860 }
1861 
1862 /*******************************************************************************
1863  **
1864  ** Function         btif_media_aa_readbuf
1865  **
1866  ** Description      This function is called by the av_co to get the next buffer to send
1867  **
1868  **
1869  ** Returns          void
1870  *******************************************************************************/
btif_media_aa_readbuf(void)1871 BT_HDR *btif_media_aa_readbuf(void)
1872 {
1873     return GKI_dequeue(&(btif_media_cb.TxAaQ));
1874 }
1875 
1876 /*******************************************************************************
1877  **
1878  ** Function         btif_media_aa_read_feeding
1879  **
1880  ** Description
1881  **
1882  ** Returns          void
1883  **
1884  *******************************************************************************/
1885 
btif_media_aa_read_feeding(tUIPC_CH_ID channel_id)1886 BOOLEAN btif_media_aa_read_feeding(tUIPC_CH_ID channel_id)
1887 {
1888     UINT16 event;
1889     /* coverity[SIGN_EXTENSION] False-positive: Parameter are always in range avoiding sign extension*/
1890     UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands * btif_media_cb.encoder.s16NumOfBlocks;
1891     UINT32 read_size;
1892     UINT16 sbc_sampling = 48000;
1893     UINT32 src_samples;
1894     UINT16 bytes_needed = blocm_x_subband * btif_media_cb.encoder.s16NumOfChannels * sizeof(SINT16);
1895     static UINT16 up_sampled_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS
1896             * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * 2];
1897     static UINT16 read_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS
1898             * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS];
1899     UINT32 src_size_used;
1900     UINT32 dst_size_used;
1901     BOOLEAN fract_needed;
1902     INT32   fract_max;
1903     INT32   fract_threshold;
1904     UINT32  nb_byte_read;
1905 
1906     /* Get the SBC sampling rate */
1907     switch (btif_media_cb.encoder.s16SamplingFreq)
1908     {
1909     case SBC_sf48000:
1910         sbc_sampling = 48000;
1911         break;
1912     case SBC_sf44100:
1913         sbc_sampling = 44100;
1914         break;
1915     case SBC_sf32000:
1916         sbc_sampling = 32000;
1917         break;
1918     case SBC_sf16000:
1919         sbc_sampling = 16000;
1920         break;
1921     }
1922 
1923     /* Some Feeding PCM frequencies require to split the number of sample */
1924     /* to read. */
1925     /* E.g 128/6=21.3333 => read 22 and 21 and 21 => max = 2; threshold = 0*/
1926     fract_needed = FALSE;   /* Default */
1927     switch (btif_media_cb.media_feeding.cfg.pcm.sampling_freq)
1928     {
1929     case 32000:
1930     case 8000:
1931         fract_needed = TRUE;
1932         fract_max = 2;          /* 0, 1 and 2 */
1933         fract_threshold = 0;    /* Add one for the first */
1934         break;
1935     case 16000:
1936         fract_needed = TRUE;
1937         fract_max = 2;          /* 0, 1 and 2 */
1938         fract_threshold = 1;    /* Add one for the first two frames*/
1939         break;
1940     }
1941 
1942     /* Compute number of sample to read from source */
1943     src_samples = blocm_x_subband;
1944     src_samples *= btif_media_cb.media_feeding.cfg.pcm.sampling_freq;
1945     src_samples /= sbc_sampling;
1946 
1947     /* The previous division may have a remainder not null */
1948     if (fract_needed)
1949     {
1950         if (btif_media_cb.media_feeding_state.pcm.aa_feed_counter <= fract_threshold)
1951         {
1952             src_samples++; /* for every read before threshold add one sample */
1953         }
1954 
1955         /* do nothing if counter >= threshold */
1956         btif_media_cb.media_feeding_state.pcm.aa_feed_counter++; /* one more read */
1957         if (btif_media_cb.media_feeding_state.pcm.aa_feed_counter > fract_max)
1958         {
1959             btif_media_cb.media_feeding_state.pcm.aa_feed_counter = 0;
1960         }
1961     }
1962 
1963     /* Compute number of bytes to read from source */
1964     read_size = src_samples;
1965     read_size *= btif_media_cb.media_feeding.cfg.pcm.num_channel;
1966     read_size *= (btif_media_cb.media_feeding.cfg.pcm.bit_per_sample / 8);
1967 
1968     /* Read Data from UIPC channel */
1969     nb_byte_read = UIPC_Read(channel_id, &event, (UINT8 *)read_buffer, read_size);
1970 
1971     //tput_mon(TRUE, nb_byte_read, FALSE);
1972 
1973     if (nb_byte_read < read_size)
1974     {
1975         APPL_TRACE_WARNING2("### UNDERRUN :: ONLY READ %d BYTES OUT OF %d ###",
1976                 nb_byte_read, read_size);
1977 
1978         if (nb_byte_read == 0)
1979             return FALSE;
1980 
1981         if(btif_media_cb.feeding_mode == BTIF_AV_FEEDING_ASYNCHRONOUS)
1982         {
1983             /* Fill the unfilled part of the read buffer with silence (0) */
1984             memset(((UINT8 *)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
1985             nb_byte_read = read_size;
1986         }
1987     }
1988 
1989     /* Initialize PCM up-sampling engine */
1990     bta_av_sbc_init_up_sample(btif_media_cb.media_feeding.cfg.pcm.sampling_freq,
1991             sbc_sampling, btif_media_cb.media_feeding.cfg.pcm.bit_per_sample,
1992             btif_media_cb.media_feeding.cfg.pcm.num_channel);
1993 
1994     /* re-sample read buffer */
1995     /* The output PCM buffer will be stereo, 16 bit per sec */
1996     dst_size_used = bta_av_sbc_up_sample((UINT8 *)read_buffer,
1997             (UINT8 *)up_sampled_buffer + btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
1998             nb_byte_read,
1999             sizeof(up_sampled_buffer) - btif_media_cb.media_feeding_state.pcm.aa_feed_residue,
2000             &src_size_used);
2001 
2002 #if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
2003     APPL_TRACE_DEBUG3("btif_media_aa_read_feeding read_size:%d src_size_used:%d dst_size_used:%d",
2004             read_size, src_size_used, dst_size_used);
2005 #endif
2006 
2007     /* update the residue */
2008     btif_media_cb.media_feeding_state.pcm.aa_feed_residue += dst_size_used;
2009 
2010     /* only copy the pcm sample when we have up-sampled enough PCM */
2011     if(btif_media_cb.media_feeding_state.pcm.aa_feed_residue >= bytes_needed)
2012     {
2013         /* Copy the output pcm samples in SBC encoding buffer */
2014         memcpy((UINT8 *)btif_media_cb.encoder.as16PcmBuffer,
2015                 (UINT8 *)up_sampled_buffer,
2016                 bytes_needed);
2017         /* update the residue */
2018         btif_media_cb.media_feeding_state.pcm.aa_feed_residue -= bytes_needed;
2019 
2020         if (btif_media_cb.media_feeding_state.pcm.aa_feed_residue != 0)
2021         {
2022             memcpy((UINT8 *)up_sampled_buffer,
2023                    (UINT8 *)up_sampled_buffer + bytes_needed,
2024                    btif_media_cb.media_feeding_state.pcm.aa_feed_residue);
2025         }
2026         return TRUE;
2027     }
2028 
2029 #if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
2030     APPL_TRACE_DEBUG3("btif_media_aa_read_feeding residue:%d, dst_size_used %d, bytes_needed %d",
2031             btif_media_cb.media_feeding_state.pcm.aa_feed_residue, dst_size_used, bytes_needed);
2032 #endif
2033 
2034     return FALSE;
2035 }
2036 
2037 /*******************************************************************************
2038  **
2039  ** Function         btif_media_aa_prep_sbc_2_send
2040  **
2041  ** Description
2042  **
2043  ** Returns          void
2044  **
2045  *******************************************************************************/
btif_media_aa_prep_sbc_2_send(UINT8 nb_frame)2046 static void btif_media_aa_prep_sbc_2_send(UINT8 nb_frame)
2047 {
2048     BT_HDR * p_buf;
2049     UINT16 blocm_x_subband = btif_media_cb.encoder.s16NumOfSubBands * btif_media_cb.encoder.s16NumOfBlocks;
2050 
2051 #if (defined(DEBUG_MEDIA_AV_FLOW) && (DEBUG_MEDIA_AV_FLOW == TRUE))
2052     APPL_TRACE_DEBUG2("btif_media_aa_prep_sbc_2_send nb_frame %d, TxAaQ %d", nb_frame, btif_media_cb.TxAaQ.count);
2053 #endif
2054     while (nb_frame)
2055     {
2056         if (NULL == (p_buf = GKI_getpoolbuf(BTIF_MEDIA_AA_POOL_ID)))
2057         {
2058             APPL_TRACE_ERROR1 ("ERROR btif_media_aa_prep_sbc_2_send no buffer TxCnt %d ", btif_media_cb.TxAaQ.count);
2059             return;
2060         }
2061 
2062         /* Init buffer */
2063         p_buf->offset = BTIF_MEDIA_AA_SBC_OFFSET;
2064         p_buf->len = 0;
2065         p_buf->layer_specific = 0;
2066 
2067         do
2068         {
2069             /* Write @ of allocated buffer in encoder.pu8Packet */
2070             btif_media_cb.encoder.pu8Packet = (UINT8 *) (p_buf + 1) + p_buf->offset + p_buf->len;
2071             /* Fill allocated buffer with 0 */
2072             /* coverity[SIGN_EXTENSION] False-positive: Parameter are always in range avoiding sign extension*/
2073             memset(btif_media_cb.encoder.as16PcmBuffer, 0, blocm_x_subband
2074                     * btif_media_cb.encoder.s16NumOfChannels);
2075 
2076             /* Read PCM data and upsample them if needed */
2077             if (btif_media_aa_read_feeding(UIPC_CH_ID_AV_AUDIO))
2078             {
2079                 /* SBC encode and descramble frame */
2080                 SBC_Encoder(&(btif_media_cb.encoder));
2081                 A2D_SbcChkFrInit(btif_media_cb.encoder.pu8Packet);
2082                 A2D_SbcDescramble(btif_media_cb.encoder.pu8Packet, btif_media_cb.encoder.u16PacketLength);
2083                 /* Update SBC frame length */
2084                 p_buf->len += btif_media_cb.encoder.u16PacketLength;
2085                 nb_frame--;
2086                 p_buf->layer_specific++;
2087             }
2088             else
2089             {
2090                 /* no more pcm to read */
2091                 nb_frame = 0;
2092 
2093                 /* break read loop if timer was stopped (media task stopped) */
2094                 if ( btif_media_cb.is_tx_timer == FALSE )
2095                     return;
2096             }
2097 
2098         } while (((p_buf->len + btif_media_cb.encoder.u16PacketLength) < btif_media_cb.TxAaMtuSize)
2099                 && (p_buf->layer_specific < 0x0F) && nb_frame);
2100 
2101         /* coverity[SIGN_EXTENSION] False-positive: Parameter are always in range avoiding sign extension*/
2102         btif_media_cb.timestamp += p_buf->layer_specific * blocm_x_subband;
2103 
2104         /* store the time stamp in the buffer to send */
2105         *((UINT32 *) (p_buf + 1)) = btif_media_cb.timestamp;
2106 
2107         VERBOSE("TX QUEUE NOW %d", btif_media_cb.TxAaQ.count);
2108 
2109         if (btif_media_cb.tx_flush)
2110         {
2111             APPL_TRACE_DEBUG0("### tx suspended, discarded frame ###");
2112 
2113             if (btif_media_cb.TxAaQ.count > 0)
2114                 btif_media_flush_q(&(btif_media_cb.TxAaQ));
2115 
2116             GKI_freebuf(p_buf);
2117             return;
2118         }
2119 
2120         /* Enqueue the encoded SBC frame in AA Tx Queue */
2121         GKI_enqueue(&(btif_media_cb.TxAaQ), p_buf);
2122     }
2123 }
2124 
2125 
2126 /*******************************************************************************
2127  **
2128  ** Function         btif_media_aa_prep_2_send
2129  **
2130  ** Description
2131  **
2132  ** Returns          void
2133  **
2134  *******************************************************************************/
2135 
btif_media_aa_prep_2_send(UINT8 nb_frame)2136 static void btif_media_aa_prep_2_send(UINT8 nb_frame)
2137 {
2138     VERBOSE("btif_media_aa_prep_2_send : %d frames (queue %d)", nb_frame,
2139                        btif_media_cb.TxAaQ.count);
2140 
2141     /* Remove all the buffers not sent until there are only 4 in the queue */
2142     while (btif_media_cb.TxAaQ.count >= MAX_OUTPUT_BUFFER_QUEUE_SZ)
2143     {
2144         APPL_TRACE_WARNING1("btif_media_aa_prep_2_send congestion buf count %d",btif_media_cb.TxAaQ.count);
2145         GKI_freebuf(GKI_dequeue(&(btif_media_cb.TxAaQ)));
2146     }
2147 
2148     switch (btif_media_cb.TxTranscoding)
2149     {
2150     case BTIF_MEDIA_TRSCD_PCM_2_SBC:
2151         btif_media_aa_prep_sbc_2_send(nb_frame);
2152         break;
2153 
2154 
2155     default:
2156         APPL_TRACE_ERROR1("ERROR btif_media_aa_prep_2_send unsupported transcoding format 0x%x",btif_media_cb.TxTranscoding);
2157         break;
2158     }
2159 }
2160 
2161 /*******************************************************************************
2162  **
2163  ** Function         btif_media_send_aa_frame
2164  **
2165  ** Description
2166  **
2167  ** Returns          void
2168  **
2169  *******************************************************************************/
btif_media_send_aa_frame(void)2170 static void btif_media_send_aa_frame(void)
2171 {
2172     UINT8 nb_frame_2_send;
2173 
2174     /* get the number of frame to send */
2175     nb_frame_2_send = btif_get_num_aa_frame();
2176 
2177     /* format and Q buffer to send */
2178     btif_media_aa_prep_2_send(nb_frame_2_send);
2179 
2180     /* send it */
2181     VERBOSE("btif_media_send_aa_frame : send %d frames", nb_frame_2_send);
2182     bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
2183 }
2184 
2185 /*******************************************************************************
2186  **
2187  ** Function         btif_media_check_iop_exceptions
2188  **
2189  ** Description    Perform any device specific iop changes
2190  **
2191  ** Returns          void
2192  **
2193  *******************************************************************************/
2194 
btif_media_check_iop_exceptions(UINT8 * peer_bda)2195 void btif_media_check_iop_exceptions(UINT8 *peer_bda)
2196 {
2197     /* disable rate scaling for pcm carkit */
2198     if ((peer_bda[0] == 0x00) &&
2199         (peer_bda[1] == 0x0E) &&
2200         (peer_bda[2] == 0x9F))
2201     {
2202         BTIF_TRACE_WARNING0("detected pcm carkit, disable rate scaling");
2203         btif_media_cb.scaling_disabled = TRUE;
2204     }
2205     else
2206     {
2207         btif_media_cb.scaling_disabled = FALSE;
2208     }
2209 }
2210 
2211 
2212 #endif /* BTA_AV_INCLUDED == TRUE */
2213 
2214 /*******************************************************************************
2215  **
2216  ** Function         dump_codec_info
2217  **
2218  ** Description      Decode and display codec_info (for debug)
2219  **
2220  ** Returns          void
2221  **
2222  *******************************************************************************/
dump_codec_info(unsigned char * p_codec)2223 void dump_codec_info(unsigned char *p_codec)
2224 {
2225     tA2D_STATUS a2d_status;
2226     tA2D_SBC_CIE sbc_cie;
2227 
2228     a2d_status = A2D_ParsSbcInfo(&sbc_cie, p_codec, FALSE);
2229     if (a2d_status != A2D_SUCCESS)
2230     {
2231         APPL_TRACE_ERROR1("ERROR dump_codec_info A2D_ParsSbcInfo fail:%d", a2d_status);
2232         return;
2233     }
2234 
2235     APPL_TRACE_DEBUG0("dump_codec_info");
2236 
2237     if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_16)
2238     {    APPL_TRACE_DEBUG1("\tsamp_freq:%d (16000)", sbc_cie.samp_freq);}
2239     else  if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_32)
2240     {    APPL_TRACE_DEBUG1("\tsamp_freq:%d (32000)", sbc_cie.samp_freq);}
2241     else  if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_44)
2242     {    APPL_TRACE_DEBUG1("\tsamp_freq:%d (44.100)", sbc_cie.samp_freq);}
2243     else  if (sbc_cie.samp_freq == A2D_SBC_IE_SAMP_FREQ_48)
2244     {    APPL_TRACE_DEBUG1("\tsamp_freq:%d (48000)", sbc_cie.samp_freq);}
2245     else
2246     {    APPL_TRACE_DEBUG1("\tBAD samp_freq:%d", sbc_cie.samp_freq);}
2247 
2248     if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_MONO)
2249     {    APPL_TRACE_DEBUG1("\tch_mode:%d (Mono)", sbc_cie.ch_mode);}
2250     else  if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_DUAL)
2251     {    APPL_TRACE_DEBUG1("\tch_mode:%d (Dual)", sbc_cie.ch_mode);}
2252     else  if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_STEREO)
2253     {    APPL_TRACE_DEBUG1("\tch_mode:%d (Stereo)", sbc_cie.ch_mode);}
2254     else  if (sbc_cie.ch_mode == A2D_SBC_IE_CH_MD_JOINT)
2255     {    APPL_TRACE_DEBUG1("\tch_mode:%d (Joint)", sbc_cie.ch_mode);}
2256     else
2257     {    APPL_TRACE_DEBUG1("\tBAD ch_mode:%d", sbc_cie.ch_mode);}
2258 
2259     if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_4)
2260     {    APPL_TRACE_DEBUG1("\tblock_len:%d (4)", sbc_cie.block_len);}
2261     else  if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_8)
2262     {    APPL_TRACE_DEBUG1("\tblock_len:%d (8)", sbc_cie.block_len);}
2263     else  if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_12)
2264     {    APPL_TRACE_DEBUG1("\tblock_len:%d (12)", sbc_cie.block_len);}
2265     else  if (sbc_cie.block_len == A2D_SBC_IE_BLOCKS_16)
2266     {    APPL_TRACE_DEBUG1("\tblock_len:%d (16)", sbc_cie.block_len);}
2267     else
2268     {    APPL_TRACE_DEBUG1("\tBAD block_len:%d", sbc_cie.block_len);}
2269 
2270     if (sbc_cie.num_subbands == A2D_SBC_IE_SUBBAND_4)
2271     {    APPL_TRACE_DEBUG1("\tnum_subbands:%d (4)", sbc_cie.num_subbands);}
2272     else  if (sbc_cie.num_subbands == A2D_SBC_IE_SUBBAND_8)
2273     {    APPL_TRACE_DEBUG1("\tnum_subbands:%d (8)", sbc_cie.num_subbands);}
2274     else
2275     {    APPL_TRACE_DEBUG1("\tBAD num_subbands:%d", sbc_cie.num_subbands);}
2276 
2277     if (sbc_cie.alloc_mthd == A2D_SBC_IE_ALLOC_MD_S)
2278     {    APPL_TRACE_DEBUG1("\talloc_mthd:%d (SNR)", sbc_cie.alloc_mthd);}
2279     else  if (sbc_cie.alloc_mthd == A2D_SBC_IE_ALLOC_MD_L)
2280     {    APPL_TRACE_DEBUG1("\talloc_mthd:%d (Loundess)", sbc_cie.alloc_mthd);}
2281     else
2282     {    APPL_TRACE_DEBUG1("\tBAD alloc_mthd:%d", sbc_cie.alloc_mthd);}
2283 
2284     APPL_TRACE_DEBUG2("\tBit pool Min:%d Max:%d", sbc_cie.min_bitpool, sbc_cie.max_bitpool);
2285 
2286 }
2287 
2288