• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2016 The Android Open Source Project
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 #define LOG_TAG "a2dp_sbc_encoder"
21 
22 #include "a2dp_sbc_encoder.h"
23 
24 #include <limits.h>
25 #include <stdio.h>
26 #include <string.h>
27 
28 #include "a2dp_sbc.h"
29 #include "a2dp_sbc_up_sample.h"
30 #include "bt_common.h"
31 #include "common/time_util.h"
32 #include "embdrv/sbc/encoder/include/sbc_encoder.h"
33 #include "osi/include/log.h"
34 #include "osi/include/osi.h"
35 
36 /* Buffer pool */
37 #define A2DP_SBC_BUFFER_SIZE BT_DEFAULT_BUFFER_SIZE
38 
39 // A2DP SBC encoder interval in milliseconds.
40 #define A2DP_SBC_ENCODER_INTERVAL_MS 20
41 
42 /* High quality quality setting @ 44.1 khz */
43 #define A2DP_SBC_DEFAULT_BITRATE 328
44 
45 #define A2DP_SBC_NON_EDR_MAX_RATE 229
46 
47 #define A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK 3
48 
49 #define A2DP_SBC_MAX_HQ_FRAME_SIZE_44_1 119
50 #define A2DP_SBC_MAX_HQ_FRAME_SIZE_48 115
51 
52 /* Define the bitrate step when trying to match bitpool value */
53 #define A2DP_SBC_BITRATE_STEP 5
54 
55 /* Readability constants */
56 #define A2DP_SBC_FRAME_HEADER_SIZE_BYTES 4  // A2DP Spec v1.3, 12.4, Table 12.12
57 #define A2DP_SBC_SCALE_FACTOR_BITS 4        // A2DP Spec v1.3, 12.4, Table 12.13
58 
59 /* offset */
60 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
61 /* A2DP header will contain a CP header of size 1 */
62 #define A2DP_HDR_SIZE 2
63 #define A2DP_SBC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_SBC_MPL_HDR_LEN + 1)
64 #else
65 #define A2DP_HDR_SIZE 1
66 #define A2DP_SBC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_SBC_MPL_HDR_LEN)
67 #endif
68 
69 typedef struct {
70   uint32_t aa_frame_counter;
71   int32_t aa_feed_counter;
72   int32_t aa_feed_residue;
73   float counter;
74   uint32_t bytes_per_tick; /* pcm bytes read each media task tick */
75   uint64_t last_frame_us;
76 } tA2DP_SBC_FEEDING_STATE;
77 
78 typedef struct {
79   uint64_t session_start_us;
80 
81   size_t media_read_total_expected_packets;
82   size_t media_read_total_expected_reads_count;
83   size_t media_read_total_expected_read_bytes;
84 
85   size_t media_read_total_dropped_packets;
86   size_t media_read_total_actual_reads_count;
87   size_t media_read_total_actual_read_bytes;
88 
89   size_t media_read_total_expected_frames;
90   size_t media_read_total_dropped_frames;
91 } a2dp_sbc_encoder_stats_t;
92 
93 typedef struct {
94   a2dp_source_read_callback_t read_callback;
95   a2dp_source_enqueue_callback_t enqueue_callback;
96   uint16_t TxAaMtuSize;
97   uint8_t tx_sbc_frames;
98   bool is_peer_edr;         /* True if the peer device supports EDR */
99   bool peer_supports_3mbps; /* True if the peer device supports 3Mbps EDR */
100   uint16_t peer_mtu;        /* MTU of the A2DP peer */
101   uint32_t timestamp;       /* Timestamp for the A2DP frames */
102   SBC_ENC_PARAMS sbc_encoder_params;
103   tA2DP_FEEDING_PARAMS feeding_params;
104   tA2DP_SBC_FEEDING_STATE feeding_state;
105   int16_t pcmBuffer[SBC_MAX_PCM_BUFFER_SIZE];
106 
107   a2dp_sbc_encoder_stats_t stats;
108 } tA2DP_SBC_ENCODER_CB;
109 
110 static tA2DP_SBC_ENCODER_CB a2dp_sbc_encoder_cb;
111 
112 static void a2dp_sbc_encoder_update(uint16_t peer_mtu,
113                                     A2dpCodecConfig* a2dp_codec_config,
114                                     bool* p_restart_input,
115                                     bool* p_restart_output,
116                                     bool* p_config_updated);
117 static bool a2dp_sbc_read_feeding(uint32_t* bytes);
118 static void a2dp_sbc_encode_frames(uint8_t nb_frame);
119 static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations,
120                                              uint8_t* num_of_frames,
121                                              uint64_t timestamp_us);
122 static uint8_t calculate_max_frames_per_packet(void);
123 static uint16_t a2dp_sbc_source_rate();
124 static uint32_t a2dp_sbc_frame_length(void);
125 
A2DP_LoadEncoderSbc(void)126 bool A2DP_LoadEncoderSbc(void) {
127   // Nothing to do - the library is statically linked
128   return true;
129 }
130 
A2DP_UnloadEncoderSbc(void)131 void A2DP_UnloadEncoderSbc(void) {
132   // Nothing to do - the library is statically linked
133 }
134 
a2dp_sbc_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS * p_peer_params,A2dpCodecConfig * a2dp_codec_config,a2dp_source_read_callback_t read_callback,a2dp_source_enqueue_callback_t enqueue_callback)135 void a2dp_sbc_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
136                            A2dpCodecConfig* a2dp_codec_config,
137                            a2dp_source_read_callback_t read_callback,
138                            a2dp_source_enqueue_callback_t enqueue_callback) {
139   memset(&a2dp_sbc_encoder_cb, 0, sizeof(a2dp_sbc_encoder_cb));
140 
141   a2dp_sbc_encoder_cb.stats.session_start_us =
142       bluetooth::common::time_get_os_boottime_us();
143 
144   a2dp_sbc_encoder_cb.read_callback = read_callback;
145   a2dp_sbc_encoder_cb.enqueue_callback = enqueue_callback;
146   a2dp_sbc_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
147   a2dp_sbc_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
148   a2dp_sbc_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
149   a2dp_sbc_encoder_cb.timestamp = 0;
150 
151   // NOTE: Ignore the restart_input / restart_output flags - this initization
152   // happens when the connection is (re)started.
153   bool restart_input = false;
154   bool restart_output = false;
155   bool config_updated = false;
156   a2dp_sbc_encoder_update(a2dp_sbc_encoder_cb.peer_mtu, a2dp_codec_config,
157                           &restart_input, &restart_output, &config_updated);
158 }
159 
updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS * p_peer_params,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)160 bool A2dpCodecConfigSbcSource::updateEncoderUserConfig(
161     const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input,
162     bool* p_restart_output, bool* p_config_updated) {
163   a2dp_sbc_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
164   a2dp_sbc_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
165   a2dp_sbc_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
166   a2dp_sbc_encoder_cb.timestamp = 0;
167 
168   if (a2dp_sbc_encoder_cb.peer_mtu == 0) {
169     LOG_ERROR(
170         "%s: Cannot update the codec encoder for %s: "
171         "invalid peer MTU",
172         __func__, name().c_str());
173     return false;
174   }
175 
176   a2dp_sbc_encoder_update(a2dp_sbc_encoder_cb.peer_mtu, this, p_restart_input,
177                           p_restart_output, p_config_updated);
178   return true;
179 }
180 
181 // Update the A2DP SBC encoder.
182 // |peer_mtu| is the peer MTU.
183 // |a2dp_codec_config| is the A2DP codec to use for the update.
a2dp_sbc_encoder_update(uint16_t peer_mtu,A2dpCodecConfig * a2dp_codec_config,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)184 static void a2dp_sbc_encoder_update(uint16_t peer_mtu,
185                                     A2dpCodecConfig* a2dp_codec_config,
186                                     bool* p_restart_input,
187                                     bool* p_restart_output,
188                                     bool* p_config_updated) {
189   SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
190   uint8_t codec_info[AVDT_CODEC_SIZE];
191   uint16_t s16SamplingFreq;
192   int16_t s16BitPool = 0;
193   int16_t s16BitRate;
194   int16_t s16FrameLen;
195   uint8_t protect = 0;
196   int min_bitpool;
197   int max_bitpool;
198 
199   *p_restart_input = false;
200   *p_restart_output = false;
201   *p_config_updated = false;
202   if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
203     LOG_ERROR(
204         "%s: Cannot update the codec encoder for %s: "
205         "invalid codec config",
206         __func__, a2dp_codec_config->name().c_str());
207     return;
208   }
209   const uint8_t* p_codec_info = codec_info;
210   min_bitpool = A2DP_GetMinBitpoolSbc(p_codec_info);
211   max_bitpool = A2DP_GetMaxBitpoolSbc(p_codec_info);
212 
213   // The feeding parameters
214   tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_sbc_encoder_cb.feeding_params;
215   p_feeding_params->sample_rate = A2DP_GetTrackSampleRateSbc(p_codec_info);
216   p_feeding_params->bits_per_sample =
217       a2dp_codec_config->getAudioBitsPerSample();
218   p_feeding_params->channel_count = A2DP_GetTrackChannelCountSbc(p_codec_info);
219   LOG_INFO("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
220            p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
221            p_feeding_params->channel_count);
222   a2dp_sbc_feeding_reset();
223 
224   // The codec parameters
225   p_encoder_params->s16ChannelMode = A2DP_GetChannelModeCodeSbc(p_codec_info);
226   p_encoder_params->s16NumOfSubBands =
227       A2DP_GetNumberOfSubbandsSbc(p_codec_info);
228   p_encoder_params->s16NumOfBlocks = A2DP_GetNumberOfBlocksSbc(p_codec_info);
229   p_encoder_params->s16AllocationMethod =
230       A2DP_GetAllocationMethodCodeSbc(p_codec_info);
231   p_encoder_params->s16SamplingFreq =
232       A2DP_GetSamplingFrequencyCodeSbc(p_codec_info);
233   p_encoder_params->s16NumOfChannels =
234       A2DP_GetTrackChannelCountSbc(p_codec_info);
235 
236   // Reset invalid parameters
237   if (!p_encoder_params->s16NumOfSubBands) {
238     LOG_WARN("%s: SubBands are set to 0, resetting to max (%d)", __func__,
239              SBC_MAX_NUM_OF_SUBBANDS);
240     p_encoder_params->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS;
241   }
242   if (!p_encoder_params->s16NumOfBlocks) {
243     LOG_WARN("%s: Blocks are set to 0, resetting to max (%d)", __func__,
244              SBC_MAX_NUM_OF_BLOCKS);
245     p_encoder_params->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS;
246   }
247   if (!p_encoder_params->s16NumOfChannels) {
248     LOG_WARN("%s: Channels are set to 0, resetting to max (%d)", __func__,
249              SBC_MAX_NUM_OF_CHANNELS);
250     p_encoder_params->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS;
251   }
252 
253   uint16_t mtu_size = A2DP_SBC_BUFFER_SIZE - A2DP_SBC_OFFSET - sizeof(BT_HDR);
254   if (mtu_size < peer_mtu) {
255     a2dp_sbc_encoder_cb.TxAaMtuSize = mtu_size;
256   } else {
257     a2dp_sbc_encoder_cb.TxAaMtuSize = peer_mtu;
258   }
259 
260   if (p_encoder_params->s16SamplingFreq == SBC_sf16000)
261     s16SamplingFreq = 16000;
262   else if (p_encoder_params->s16SamplingFreq == SBC_sf32000)
263     s16SamplingFreq = 32000;
264   else if (p_encoder_params->s16SamplingFreq == SBC_sf44100)
265     s16SamplingFreq = 44100;
266   else
267     s16SamplingFreq = 48000;
268 
269   // Set the initial target bit rate
270   p_encoder_params->u16BitRate = a2dp_sbc_source_rate();
271 
272   LOG_INFO("%s: MTU=%d, peer_mtu=%d min_bitpool=%d max_bitpool=%d", __func__,
273            a2dp_sbc_encoder_cb.TxAaMtuSize, peer_mtu, min_bitpool, max_bitpool);
274   LOG_INFO(
275       "%s: ChannelMode=%d, NumOfSubBands=%d, NumOfBlocks=%d, "
276       "AllocationMethod=%d, BitRate=%d, SamplingFreq=%d BitPool=%d",
277       __func__, p_encoder_params->s16ChannelMode,
278       p_encoder_params->s16NumOfSubBands, p_encoder_params->s16NumOfBlocks,
279       p_encoder_params->s16AllocationMethod, p_encoder_params->u16BitRate,
280       s16SamplingFreq, p_encoder_params->s16BitPool);
281 
282   do {
283     if ((p_encoder_params->s16ChannelMode == SBC_JOINT_STEREO) ||
284         (p_encoder_params->s16ChannelMode == SBC_STEREO)) {
285       s16BitPool = (int16_t)((p_encoder_params->u16BitRate *
286                               p_encoder_params->s16NumOfSubBands * 1000 /
287                               s16SamplingFreq) -
288                              ((32 + (4 * p_encoder_params->s16NumOfSubBands *
289                                      p_encoder_params->s16NumOfChannels) +
290                                ((p_encoder_params->s16ChannelMode - 2) *
291                                 p_encoder_params->s16NumOfSubBands)) /
292                               p_encoder_params->s16NumOfBlocks));
293 
294       s16FrameLen = 4 +
295                     (4 * p_encoder_params->s16NumOfSubBands *
296                      p_encoder_params->s16NumOfChannels) /
297                         8 +
298                     (((p_encoder_params->s16ChannelMode - 2) *
299                       p_encoder_params->s16NumOfSubBands) +
300                      (p_encoder_params->s16NumOfBlocks * s16BitPool)) /
301                         8;
302 
303       s16BitRate = (8 * s16FrameLen * s16SamplingFreq) /
304                    (p_encoder_params->s16NumOfSubBands *
305                     p_encoder_params->s16NumOfBlocks * 1000);
306 
307       if (s16BitRate > p_encoder_params->u16BitRate) s16BitPool--;
308 
309       if (p_encoder_params->s16NumOfSubBands == 8)
310         s16BitPool = (s16BitPool > 255) ? 255 : s16BitPool;
311       else
312         s16BitPool = (s16BitPool > 128) ? 128 : s16BitPool;
313     } else {
314       s16BitPool =
315           (int16_t)(((p_encoder_params->s16NumOfSubBands *
316                       p_encoder_params->u16BitRate * 1000) /
317                      (s16SamplingFreq * p_encoder_params->s16NumOfChannels)) -
318                     (((32 / p_encoder_params->s16NumOfChannels) +
319                       (4 * p_encoder_params->s16NumOfSubBands)) /
320                      p_encoder_params->s16NumOfBlocks));
321 
322       p_encoder_params->s16BitPool =
323           (s16BitPool > (16 * p_encoder_params->s16NumOfSubBands))
324               ? (16 * p_encoder_params->s16NumOfSubBands)
325               : s16BitPool;
326     }
327 
328     if (s16BitPool < 0) s16BitPool = 0;
329 
330     LOG_VERBOSE("%s: bitpool candidate: %d (%d kbps)", __func__, s16BitPool,
331                 p_encoder_params->u16BitRate);
332 
333     if (s16BitPool > max_bitpool) {
334       LOG_VERBOSE("%s: computed bitpool too large (%d)", __func__, s16BitPool);
335       /* Decrease bitrate */
336       p_encoder_params->u16BitRate -= A2DP_SBC_BITRATE_STEP;
337       /* Record that we have decreased the bitrate */
338       protect |= 1;
339     } else if (s16BitPool < min_bitpool) {
340       LOG_WARN("%s: computed bitpool too small (%d)", __func__, s16BitPool);
341 
342       /* Increase bitrate */
343       uint16_t previous_u16BitRate = p_encoder_params->u16BitRate;
344       p_encoder_params->u16BitRate += A2DP_SBC_BITRATE_STEP;
345       /* Record that we have increased the bitrate */
346       protect |= 2;
347       /* Check over-flow */
348       if (p_encoder_params->u16BitRate < previous_u16BitRate) protect |= 3;
349     } else {
350       break;
351     }
352     /* In case we have already increased and decreased the bitrate, just stop */
353     if (protect == 3) {
354       LOG_ERROR("%s: could not find bitpool in range", __func__);
355       break;
356     }
357   } while (true);
358 
359   /* Finally update the bitpool in the encoder structure */
360   p_encoder_params->s16BitPool = s16BitPool;
361 
362   LOG_INFO("%s: final bit rate %d, final bit pool %d", __func__,
363            p_encoder_params->u16BitRate, p_encoder_params->s16BitPool);
364 
365   /* Reset the SBC encoder */
366   SBC_Encoder_Init(&a2dp_sbc_encoder_cb.sbc_encoder_params);
367   a2dp_sbc_encoder_cb.tx_sbc_frames = calculate_max_frames_per_packet();
368 }
369 
a2dp_sbc_encoder_cleanup(void)370 void a2dp_sbc_encoder_cleanup(void) {
371   memset(&a2dp_sbc_encoder_cb, 0, sizeof(a2dp_sbc_encoder_cb));
372 }
373 
a2dp_sbc_feeding_reset(void)374 void a2dp_sbc_feeding_reset(void) {
375   /* By default, just clear the entire state */
376   memset(&a2dp_sbc_encoder_cb.feeding_state, 0,
377          sizeof(a2dp_sbc_encoder_cb.feeding_state));
378 
379   a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick =
380       (a2dp_sbc_encoder_cb.feeding_params.sample_rate *
381        a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8 *
382        a2dp_sbc_encoder_cb.feeding_params.channel_count *
383        A2DP_SBC_ENCODER_INTERVAL_MS) /
384       1000;
385 
386   LOG_INFO("%s: PCM bytes per tick %u", __func__,
387            a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick);
388 }
389 
a2dp_sbc_feeding_flush(void)390 void a2dp_sbc_feeding_flush(void) {
391   a2dp_sbc_encoder_cb.feeding_state.counter = 0.0f;
392   a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue = 0;
393 }
394 
a2dp_sbc_get_encoder_interval_ms(void)395 uint64_t a2dp_sbc_get_encoder_interval_ms(void) {
396   return A2DP_SBC_ENCODER_INTERVAL_MS;
397 }
398 
a2dp_sbc_send_frames(uint64_t timestamp_us)399 void a2dp_sbc_send_frames(uint64_t timestamp_us) {
400   uint8_t nb_frame = 0;
401   uint8_t nb_iterations = 0;
402 
403   a2dp_sbc_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
404   LOG_VERBOSE("%s: Sending %d frames per iteration, %d iterations", __func__,
405               nb_frame, nb_iterations);
406   if (nb_frame == 0) return;
407 
408   for (uint8_t counter = 0; counter < nb_iterations; counter++) {
409     // Transcode frame and enqueue
410     a2dp_sbc_encode_frames(nb_frame);
411   }
412 }
413 
414 // Obtains the number of frames to send and number of iterations
415 // to be used. |num_of_iterations| and |num_of_frames| parameters
416 // are used as output param for returning the respective values.
a2dp_sbc_get_num_frame_iteration(uint8_t * num_of_iterations,uint8_t * num_of_frames,uint64_t timestamp_us)417 static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations,
418                                              uint8_t* num_of_frames,
419                                              uint64_t timestamp_us) {
420   uint8_t nof = 0;
421   uint8_t noi = 1;
422 
423   uint32_t projected_nof = 0;
424   uint32_t pcm_bytes_per_frame =
425       a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfSubBands *
426       a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfBlocks *
427       a2dp_sbc_encoder_cb.feeding_params.channel_count *
428       a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8;
429   LOG_VERBOSE("%s: pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
430 
431   uint32_t us_this_tick = A2DP_SBC_ENCODER_INTERVAL_MS * 1000;
432   uint64_t now_us = timestamp_us;
433   if (a2dp_sbc_encoder_cb.feeding_state.last_frame_us != 0)
434     us_this_tick = (now_us - a2dp_sbc_encoder_cb.feeding_state.last_frame_us);
435   a2dp_sbc_encoder_cb.feeding_state.last_frame_us = now_us;
436 
437   a2dp_sbc_encoder_cb.feeding_state.counter +=
438       (float)a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick * us_this_tick /
439       (A2DP_SBC_ENCODER_INTERVAL_MS * 1000);
440 
441   /* Calculate the number of frames pending for this media tick */
442   projected_nof =
443       a2dp_sbc_encoder_cb.feeding_state.counter / pcm_bytes_per_frame;
444   // Update the stats
445   a2dp_sbc_encoder_cb.stats.media_read_total_expected_frames += projected_nof;
446 
447   if (projected_nof > MAX_PCM_FRAME_NUM_PER_TICK) {
448     LOG_WARN("%s: limiting frames to be sent from %d to %d", __func__,
449              projected_nof, MAX_PCM_FRAME_NUM_PER_TICK);
450 
451     // Update the stats
452     size_t delta = projected_nof - MAX_PCM_FRAME_NUM_PER_TICK;
453     a2dp_sbc_encoder_cb.stats.media_read_total_dropped_frames += delta;
454 
455     projected_nof = MAX_PCM_FRAME_NUM_PER_TICK;
456   }
457 
458   LOG_VERBOSE("%s: frames for available PCM data %u", __func__, projected_nof);
459 
460   if (a2dp_sbc_encoder_cb.is_peer_edr) {
461     if (!a2dp_sbc_encoder_cb.tx_sbc_frames) {
462       LOG_ERROR("%s: tx_sbc_frames not updated, update from here", __func__);
463       a2dp_sbc_encoder_cb.tx_sbc_frames = calculate_max_frames_per_packet();
464     }
465 
466     nof = a2dp_sbc_encoder_cb.tx_sbc_frames;
467     if (!nof) {
468       LOG_ERROR("%s: number of frames not updated, set calculated values",
469                 __func__);
470       nof = projected_nof;
471       noi = 1;
472     } else {
473       if (nof < projected_nof) {
474         noi = projected_nof / nof;  // number of iterations would vary
475         if (noi > A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK) {
476           LOG_ERROR("%s: Audio Congestion (iterations:%d > max (%d))", __func__,
477                     noi, A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK);
478           noi = A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK;
479           a2dp_sbc_encoder_cb.feeding_state.counter =
480               noi * nof * pcm_bytes_per_frame;
481         }
482         projected_nof = nof;
483       } else {
484         noi = 1;  // number of iterations is 1
485         LOG_VERBOSE("%s: reducing frames for available PCM data", __func__);
486         nof = projected_nof;
487       }
488     }
489   } else {
490     // For BR cases nof will be same as the value retrieved at projected_nof
491     LOG_VERBOSE("%s: headset BR, number of frames %u", __func__, nof);
492     if (projected_nof > MAX_PCM_FRAME_NUM_PER_TICK) {
493       LOG_ERROR("%s: Audio Congestion (frames: %d > max (%d))", __func__,
494                 projected_nof, MAX_PCM_FRAME_NUM_PER_TICK);
495 
496       // Update the stats
497       size_t delta = projected_nof - MAX_PCM_FRAME_NUM_PER_TICK;
498       a2dp_sbc_encoder_cb.stats.media_read_total_dropped_frames += delta;
499 
500       projected_nof = MAX_PCM_FRAME_NUM_PER_TICK;
501       a2dp_sbc_encoder_cb.feeding_state.counter =
502           noi * projected_nof * pcm_bytes_per_frame;
503     }
504     nof = projected_nof;
505   }
506   a2dp_sbc_encoder_cb.feeding_state.counter -= noi * nof * pcm_bytes_per_frame;
507   LOG_VERBOSE("%s: effective num of frames %u, iterations %u", __func__, nof,
508               noi);
509 
510   *num_of_frames = nof;
511   *num_of_iterations = noi;
512 }
513 
a2dp_sbc_encode_frames(uint8_t nb_frame)514 static void a2dp_sbc_encode_frames(uint8_t nb_frame) {
515   SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
516   uint8_t remain_nb_frame = nb_frame;
517   uint16_t blocm_x_subband =
518       p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks;
519 
520   uint8_t last_frame_len = 0;
521 
522   while (nb_frame) {
523     BT_HDR* p_buf = (BT_HDR*)osi_malloc(A2DP_SBC_BUFFER_SIZE);
524     uint32_t bytes_read = 0;
525 
526     p_buf->offset = A2DP_SBC_OFFSET;
527     p_buf->len = 0;
528     p_buf->layer_specific = 0;
529     a2dp_sbc_encoder_cb.stats.media_read_total_expected_packets++;
530 
531     do {
532       /* Fill allocated buffer with 0 */
533       memset(a2dp_sbc_encoder_cb.pcmBuffer, 0,
534              blocm_x_subband * p_encoder_params->s16NumOfChannels);
535       //
536       // Read the PCM data and encode it. If necessary, upsample the data.
537       //
538       uint32_t num_bytes = 0;
539       if (a2dp_sbc_read_feeding(&num_bytes)) {
540         uint8_t* output = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
541         int16_t* input = a2dp_sbc_encoder_cb.pcmBuffer;
542         uint16_t output_len = SBC_Encode(p_encoder_params, input, output);
543         last_frame_len = output_len;
544 
545         /* Update SBC frame length */
546         p_buf->len += output_len;
547         nb_frame--;
548         p_buf->layer_specific++;
549 
550         bytes_read += num_bytes;
551       } else {
552         LOG_WARN("%s: underflow %d, %d", __func__, nb_frame,
553                  a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue);
554         a2dp_sbc_encoder_cb.feeding_state.counter +=
555             nb_frame * p_encoder_params->s16NumOfSubBands *
556             p_encoder_params->s16NumOfBlocks *
557             a2dp_sbc_encoder_cb.feeding_params.channel_count *
558             a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8;
559         /* no more pcm to read */
560         nb_frame = 0;
561       }
562     } while (
563         ((p_buf->len + last_frame_len) < a2dp_sbc_encoder_cb.TxAaMtuSize) &&
564         (p_buf->layer_specific < 0x0F) && nb_frame);
565 
566     if (p_buf->len) {
567       /*
568        * Timestamp of the media packet header represent the TS of the
569        * first SBC frame, i.e the timestamp before including this frame.
570        */
571       *((uint32_t*)(p_buf + 1)) = a2dp_sbc_encoder_cb.timestamp;
572 
573       a2dp_sbc_encoder_cb.timestamp += p_buf->layer_specific * blocm_x_subband;
574 
575       uint8_t done_nb_frame = remain_nb_frame - nb_frame;
576       remain_nb_frame = nb_frame;
577       if (!a2dp_sbc_encoder_cb.enqueue_callback(p_buf, done_nb_frame,
578                                                 bytes_read))
579         return;
580     } else {
581       a2dp_sbc_encoder_cb.stats.media_read_total_dropped_packets++;
582       osi_free(p_buf);
583     }
584   }
585 }
586 
a2dp_sbc_read_feeding(uint32_t * bytes_read)587 static bool a2dp_sbc_read_feeding(uint32_t* bytes_read) {
588   SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
589   uint16_t blocm_x_subband =
590       p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks;
591   uint32_t read_size;
592   uint32_t sbc_sampling = 48000;
593   uint32_t src_samples;
594   uint16_t bytes_needed = blocm_x_subband * p_encoder_params->s16NumOfChannels *
595                           a2dp_sbc_encoder_cb.feeding_params.bits_per_sample /
596                           8;
597   static uint16_t up_sampled_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS *
598                                     SBC_MAX_NUM_OF_CHANNELS *
599                                     SBC_MAX_NUM_OF_SUBBANDS * 2];
600   static uint16_t read_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS *
601                               SBC_MAX_NUM_OF_CHANNELS *
602                               SBC_MAX_NUM_OF_SUBBANDS];
603   uint32_t src_size_used;
604   uint32_t dst_size_used;
605   bool fract_needed;
606   int32_t fract_max;
607   int32_t fract_threshold;
608   uint32_t nb_byte_read;
609 
610   /* Get the SBC sampling rate */
611   switch (p_encoder_params->s16SamplingFreq) {
612     case SBC_sf48000:
613       sbc_sampling = 48000;
614       break;
615     case SBC_sf44100:
616       sbc_sampling = 44100;
617       break;
618     case SBC_sf32000:
619       sbc_sampling = 32000;
620       break;
621     case SBC_sf16000:
622       sbc_sampling = 16000;
623       break;
624   }
625 
626   a2dp_sbc_encoder_cb.stats.media_read_total_expected_reads_count++;
627   if (sbc_sampling == a2dp_sbc_encoder_cb.feeding_params.sample_rate) {
628     read_size =
629         bytes_needed - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue;
630     a2dp_sbc_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
631     nb_byte_read = a2dp_sbc_encoder_cb.read_callback(
632         ((uint8_t*)a2dp_sbc_encoder_cb.pcmBuffer) +
633             a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue,
634         read_size);
635     a2dp_sbc_encoder_cb.stats.media_read_total_actual_read_bytes +=
636         nb_byte_read;
637 
638     *bytes_read = nb_byte_read;
639     if (nb_byte_read != read_size) {
640       a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue += nb_byte_read;
641       return false;
642     }
643     a2dp_sbc_encoder_cb.stats.media_read_total_actual_reads_count++;
644     a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue = 0;
645     return true;
646   }
647 
648   /*
649    * Some Feeding PCM frequencies require to split the number of sample
650    * to read.
651    * E.g 128 / 6 = 21.3333 => read 22 and 21 and 21 => max = 2; threshold = 0
652    */
653   fract_needed = false; /* Default */
654   switch (a2dp_sbc_encoder_cb.feeding_params.sample_rate) {
655     case 32000:
656     case 8000:
657       fract_needed = true;
658       fract_max = 2;       /* 0, 1 and 2 */
659       fract_threshold = 0; /* Add one for the first */
660       break;
661     case 16000:
662       fract_needed = true;
663       fract_max = 2;       /* 0, 1 and 2 */
664       fract_threshold = 1; /* Add one for the first two frames*/
665       break;
666   }
667 
668   /* Compute number of sample to read from source */
669   src_samples = blocm_x_subband;
670   src_samples *= a2dp_sbc_encoder_cb.feeding_params.sample_rate;
671   src_samples /= sbc_sampling;
672 
673   /* The previous division may have a remainder not null */
674   if (fract_needed) {
675     if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_counter <= fract_threshold) {
676       src_samples++; /* for every read before threshold add one sample */
677     }
678 
679     /* do nothing if counter >= threshold */
680     a2dp_sbc_encoder_cb.feeding_state.aa_feed_counter++; /* one more read */
681     if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_counter > fract_max) {
682       a2dp_sbc_encoder_cb.feeding_state.aa_feed_counter = 0;
683     }
684   }
685 
686   /* Compute number of bytes to read from source */
687   read_size = src_samples;
688   read_size *= a2dp_sbc_encoder_cb.feeding_params.channel_count;
689   read_size *= (a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8);
690   a2dp_sbc_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
691 
692   /* Read Data from UIPC channel */
693   nb_byte_read =
694       a2dp_sbc_encoder_cb.read_callback((uint8_t*)read_buffer, read_size);
695   a2dp_sbc_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
696 
697   if (nb_byte_read < read_size) {
698     if (nb_byte_read == 0) return false;
699 
700     /* Fill the unfilled part of the read buffer with silence (0) */
701     memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
702     nb_byte_read = read_size;
703   }
704   a2dp_sbc_encoder_cb.stats.media_read_total_actual_reads_count++;
705 
706   /* Initialize PCM up-sampling engine */
707   a2dp_sbc_init_up_sample(a2dp_sbc_encoder_cb.feeding_params.sample_rate,
708                           sbc_sampling,
709                           a2dp_sbc_encoder_cb.feeding_params.bits_per_sample,
710                           a2dp_sbc_encoder_cb.feeding_params.channel_count);
711 
712   /*
713    * Re-sample the read buffer.
714    * The output PCM buffer will be stereo, 16 bit per sample.
715    */
716   dst_size_used = a2dp_sbc_up_sample(
717       (uint8_t*)read_buffer,
718       (uint8_t*)up_sampled_buffer +
719           a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue,
720       nb_byte_read, sizeof(up_sampled_buffer) -
721                         a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue,
722       &src_size_used);
723 
724   /* update the residue */
725   a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue += dst_size_used;
726 
727   /* only copy the pcm sample when we have up-sampled enough PCM */
728   if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue < bytes_needed)
729     return false;
730 
731   /* Copy the output pcm samples in SBC encoding buffer */
732   memcpy((uint8_t*)a2dp_sbc_encoder_cb.pcmBuffer, (uint8_t*)up_sampled_buffer,
733          bytes_needed);
734   /* update the residue */
735   a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue -= bytes_needed;
736 
737   if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue != 0) {
738     memcpy((uint8_t*)up_sampled_buffer,
739            (uint8_t*)up_sampled_buffer + bytes_needed,
740            a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue);
741   }
742   return true;
743 }
744 
calculate_max_frames_per_packet(void)745 static uint8_t calculate_max_frames_per_packet(void) {
746   uint16_t effective_mtu_size = a2dp_sbc_encoder_cb.TxAaMtuSize;
747   SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
748   uint16_t result = 0;
749   uint32_t frame_len;
750 
751   LOG_VERBOSE("%s: original AVDTP MTU size: %d", __func__,
752               a2dp_sbc_encoder_cb.TxAaMtuSize);
753   if (a2dp_sbc_encoder_cb.is_peer_edr &&
754       !a2dp_sbc_encoder_cb.peer_supports_3mbps) {
755     // This condition would be satisfied only if the remote device is
756     // EDR and supports only 2 Mbps, but the effective AVDTP MTU size
757     // exceeds the 2DH5 packet size.
758     LOG_VERBOSE("%s: The remote device is EDR but does not support 3 Mbps",
759                 __func__);
760 
761     if (effective_mtu_size > MAX_2MBPS_AVDTP_MTU) {
762       LOG_WARN("%s: Restricting AVDTP MTU size to %d", __func__,
763                MAX_2MBPS_AVDTP_MTU);
764       effective_mtu_size = MAX_2MBPS_AVDTP_MTU;
765       a2dp_sbc_encoder_cb.TxAaMtuSize = effective_mtu_size;
766     }
767   }
768 
769   if (!p_encoder_params->s16NumOfSubBands) {
770     LOG_ERROR("%s: SubBands are set to 0, resetting to %d", __func__,
771               SBC_MAX_NUM_OF_SUBBANDS);
772     p_encoder_params->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS;
773   }
774   if (!p_encoder_params->s16NumOfBlocks) {
775     LOG_ERROR("%s: Blocks are set to 0, resetting to %d", __func__,
776               SBC_MAX_NUM_OF_BLOCKS);
777     p_encoder_params->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS;
778   }
779   if (!p_encoder_params->s16NumOfChannels) {
780     LOG_ERROR("%s: Channels are set to 0, resetting to %d", __func__,
781               SBC_MAX_NUM_OF_CHANNELS);
782     p_encoder_params->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS;
783   }
784 
785   frame_len = a2dp_sbc_frame_length();
786 
787   LOG_VERBOSE("%s: Effective Tx MTU to be considered: %d", __func__,
788               effective_mtu_size);
789 
790   switch (p_encoder_params->s16SamplingFreq) {
791     case SBC_sf44100:
792       if (frame_len == 0) {
793         LOG_ERROR("%s: Calculating frame length, resetting it to default %d",
794                   __func__, A2DP_SBC_MAX_HQ_FRAME_SIZE_44_1);
795         frame_len = A2DP_SBC_MAX_HQ_FRAME_SIZE_44_1;
796       }
797       result = (effective_mtu_size - A2DP_HDR_SIZE) / frame_len;
798       LOG_VERBOSE("%s: Max number of SBC frames: %d", __func__, result);
799       break;
800 
801     case SBC_sf48000:
802       if (frame_len == 0) {
803         LOG_ERROR("%s: Calculating frame length, resetting it to default %d",
804                   __func__, A2DP_SBC_MAX_HQ_FRAME_SIZE_48);
805         frame_len = A2DP_SBC_MAX_HQ_FRAME_SIZE_48;
806       }
807       result = (effective_mtu_size - A2DP_HDR_SIZE) / frame_len;
808       LOG_VERBOSE("%s: Max number of SBC frames: %d", __func__, result);
809       break;
810 
811     default:
812       LOG_ERROR("%s: Max number of SBC frames: %d", __func__, result);
813       break;
814   }
815   return result;
816 }
817 
a2dp_sbc_source_rate()818 static uint16_t a2dp_sbc_source_rate() {
819   uint16_t rate = A2DP_SBC_DEFAULT_BITRATE;
820 
821   /* restrict bitrate if a2dp link is non-edr */
822   if (!a2dp_sbc_encoder_cb.is_peer_edr) {
823     rate = A2DP_SBC_NON_EDR_MAX_RATE;
824     LOG_VERBOSE("%s: non-edr a2dp sink detected, restrict rate to %d", __func__,
825                 rate);
826   }
827 
828   return rate;
829 }
830 
a2dp_sbc_frame_length(void)831 static uint32_t a2dp_sbc_frame_length(void) {
832   SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
833   uint32_t frame_len = 0;
834 
835   LOG_VERBOSE(
836       "%s: channel mode: %d, sub-band: %d, number of block: %d, "
837       "bitpool: %d, sampling frequency: %d, num channels: %d",
838       __func__, p_encoder_params->s16ChannelMode,
839       p_encoder_params->s16NumOfSubBands, p_encoder_params->s16NumOfBlocks,
840       p_encoder_params->s16BitPool, p_encoder_params->s16SamplingFreq,
841       p_encoder_params->s16NumOfChannels);
842 
843   switch (p_encoder_params->s16ChannelMode) {
844     case SBC_MONO:
845       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
846     case SBC_DUAL:
847       frame_len = A2DP_SBC_FRAME_HEADER_SIZE_BYTES +
848                   ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS *
849                               p_encoder_params->s16NumOfSubBands *
850                               p_encoder_params->s16NumOfChannels) /
851                    CHAR_BIT) +
852                   ((uint32_t)(p_encoder_params->s16NumOfBlocks *
853                               p_encoder_params->s16NumOfChannels *
854                               p_encoder_params->s16BitPool) /
855                    CHAR_BIT);
856       break;
857     case SBC_STEREO:
858       frame_len = A2DP_SBC_FRAME_HEADER_SIZE_BYTES +
859                   ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS *
860                               p_encoder_params->s16NumOfSubBands *
861                               p_encoder_params->s16NumOfChannels) /
862                    CHAR_BIT) +
863                   ((uint32_t)(p_encoder_params->s16NumOfBlocks *
864                               p_encoder_params->s16BitPool) /
865                    CHAR_BIT);
866       break;
867     case SBC_JOINT_STEREO:
868       frame_len = A2DP_SBC_FRAME_HEADER_SIZE_BYTES +
869                   ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS *
870                               p_encoder_params->s16NumOfSubBands *
871                               p_encoder_params->s16NumOfChannels) /
872                    CHAR_BIT) +
873                   ((uint32_t)(p_encoder_params->s16NumOfSubBands +
874                               (p_encoder_params->s16NumOfBlocks *
875                                p_encoder_params->s16BitPool)) /
876                    CHAR_BIT);
877       break;
878     default:
879       LOG_VERBOSE("%s: Invalid channel number: %d", __func__,
880                   p_encoder_params->s16ChannelMode);
881       break;
882   }
883   LOG_VERBOSE("%s: calculated frame length: %d", __func__, frame_len);
884   return frame_len;
885 }
886 
a2dp_sbc_get_bitrate()887 uint32_t a2dp_sbc_get_bitrate() {
888   SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
889   LOG_INFO("%s: bit rate %d ", __func__, p_encoder_params->u16BitRate);
890   return p_encoder_params->u16BitRate * 1000;
891 }
892 
encoderIntervalMs() const893 uint64_t A2dpCodecConfigSbcSource::encoderIntervalMs() const {
894   return a2dp_sbc_get_encoder_interval_ms();
895 }
896 
getEffectiveMtu() const897 int A2dpCodecConfigSbcSource::getEffectiveMtu() const {
898   return a2dp_sbc_encoder_cb.TxAaMtuSize;
899 }
900 
debug_codec_dump(int fd)901 void A2dpCodecConfigSbcSource::debug_codec_dump(int fd) {
902   a2dp_sbc_encoder_stats_t* stats = &a2dp_sbc_encoder_cb.stats;
903 
904   A2dpCodecConfig::debug_codec_dump(fd);
905 
906   uint8_t codec_info[AVDT_CODEC_SIZE];
907   if (copyOutOtaCodecConfig(codec_info)) {
908     dprintf(fd,
909             "  Block length                                            : %d\n",
910             A2DP_GetNumberOfBlocksSbc(codec_info));
911     dprintf(fd,
912             "  Number of subbands                                      : %d\n",
913             A2DP_GetNumberOfSubbandsSbc(codec_info));
914     dprintf(fd,
915             "  Allocation method                                       : %d\n",
916             A2DP_GetAllocationMethodCodeSbc(codec_info));
917     dprintf(
918         fd,
919         "  Bitpool (min/max)                                       : %d / %d\n",
920         A2DP_GetMinBitpoolSbc(codec_info), A2DP_GetMaxBitpoolSbc(codec_info));
921   }
922 
923   dprintf(fd,
924           "  Packet counts (expected/dropped)                        : %zu / "
925           "%zu\n",
926           stats->media_read_total_expected_packets,
927           stats->media_read_total_dropped_packets);
928 
929   dprintf(fd,
930           "  PCM read counts (expected/actual)                       : %zu / "
931           "%zu\n",
932           stats->media_read_total_expected_reads_count,
933           stats->media_read_total_actual_reads_count);
934 
935   dprintf(fd,
936           "  PCM read bytes (expected/actual)                        : %zu / "
937           "%zu\n",
938           stats->media_read_total_expected_read_bytes,
939           stats->media_read_total_actual_read_bytes);
940 
941   dprintf(fd,
942           "  Frames counts (expected/dropped)                        : %zu / "
943           "%zu\n",
944           stats->media_read_total_expected_frames,
945           stats->media_read_total_dropped_frames);
946 }
947