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