• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "a2dp_vendor_ldac_encoder"
18 #define ATRACE_TAG ATRACE_TAG_AUDIO
19 
20 #include "a2dp_vendor_ldac_encoder.h"
21 
22 #ifndef OS_GENERIC
23 #include <cutils/trace.h>
24 #endif
25 #include <dlfcn.h>
26 #include <inttypes.h>
27 #include <stdio.h>
28 #include <string.h>
29 
30 #include <ldacBT.h>
31 
32 #include "a2dp_vendor.h"
33 #include "a2dp_vendor_ldac.h"
34 #include "a2dp_vendor_ldac_abr.h"
35 #include "bt_common.h"
36 #include "common/time_util.h"
37 #include "osi/include/log.h"
38 #include "osi/include/osi.h"
39 
40 //
41 // Encoder for LDAC Source Codec
42 //
43 
44 //
45 // The LDAC encoder shared library, and the functions to use
46 //
47 static const char* LDAC_ENCODER_LIB_NAME = "libldacBT_enc.so";
48 static void* ldac_encoder_lib_handle = NULL;
49 
50 static const char* LDAC_GET_HANDLE_NAME = "ldacBT_get_handle";
51 typedef HANDLE_LDAC_BT (*tLDAC_GET_HANDLE)(void);
52 
53 static const char* LDAC_FREE_HANDLE_NAME = "ldacBT_free_handle";
54 typedef void (*tLDAC_FREE_HANDLE)(HANDLE_LDAC_BT hLdacParam);
55 
56 static const char* LDAC_CLOSE_HANDLE_NAME = "ldacBT_close_handle";
57 typedef void (*tLDAC_CLOSE_HANDLE)(HANDLE_LDAC_BT hLdacParam);
58 
59 static const char* LDAC_GET_VERSION_NAME = "ldacBT_get_version";
60 typedef int (*tLDAC_GET_VERSION)(void);
61 
62 static const char* LDAC_GET_BITRATE_NAME = "ldacBT_get_bitrate";
63 typedef int (*tLDAC_GET_BITRATE)(HANDLE_LDAC_BT hLdacParam);
64 
65 static const char* LDAC_GET_SAMPLING_FREQ_NAME = "ldacBT_get_sampling_freq";
66 typedef int (*tLDAC_GET_SAMPLING_FREQ)(HANDLE_LDAC_BT hLdacParam);
67 
68 static const char* LDAC_INIT_HANDLE_ENCODE_NAME = "ldacBT_init_handle_encode";
69 typedef int (*tLDAC_INIT_HANDLE_ENCODE)(HANDLE_LDAC_BT hLdacParam, int mtu,
70                                         int eqmid, int channel_mode,
71                                         LDACBT_SMPL_FMT_T fmt,
72                                         int sampling_freq);
73 
74 static const char* LDAC_ENCODE_NAME = "ldacBT_encode";
75 typedef int (*tLDAC_ENCODE)(HANDLE_LDAC_BT hLdacParam, void* p_pcm,
76                             int* p_pcm_encoded_byte, unsigned char* p_stream,
77                             int* pframe_length_wrote, int* pframe_num);
78 
79 static const char* LDAC_SET_EQMID_NAME = "ldacBT_set_eqmid";
80 typedef int (*tLDAC_SET_EQMID)(HANDLE_LDAC_BT hLdacParam, int eqmid);
81 
82 static const char* LDAC_ALTER_EQMID_PRIORITY_NAME =
83     "ldacBT_alter_eqmid_priority";
84 typedef int (*tLDAC_ALTER_EQMID_PRIORITY)(HANDLE_LDAC_BT hLdacParam,
85                                           int priority);
86 
87 static const char* LDAC_GET_EQMID_NAME = "ldacBT_get_eqmid";
88 typedef int (*tLDAC_GET_EQMID)(HANDLE_LDAC_BT hLdacParam);
89 
90 static const char* LDAC_GET_ERROR_CODE_NAME = "ldacBT_get_error_code";
91 typedef int (*tLDAC_GET_ERROR_CODE)(HANDLE_LDAC_BT hLdacParam);
92 
93 static tLDAC_GET_HANDLE ldac_get_handle_func;
94 static tLDAC_FREE_HANDLE ldac_free_handle_func;
95 static tLDAC_CLOSE_HANDLE ldac_close_handle_func;
96 static tLDAC_GET_VERSION ldac_get_version_func;
97 static tLDAC_GET_BITRATE ldac_get_bitrate_func;
98 static tLDAC_GET_SAMPLING_FREQ ldac_get_sampling_freq_func;
99 static tLDAC_INIT_HANDLE_ENCODE ldac_init_handle_encode_func;
100 static tLDAC_ENCODE ldac_encode_func;
101 static tLDAC_SET_EQMID ldac_set_eqmid_func;
102 static tLDAC_ALTER_EQMID_PRIORITY ldac_alter_eqmid_priority_func;
103 static tLDAC_GET_EQMID ldac_get_eqmid_func;
104 static tLDAC_GET_ERROR_CODE ldac_get_error_code_func;
105 
106 // A2DP LDAC encoder interval in milliseconds
107 #define A2DP_LDAC_ENCODER_INTERVAL_MS 20
108 #define A2DP_LDAC_MEDIA_BYTES_PER_FRAME 128
109 
110 // offset
111 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
112 #define A2DP_LDAC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_LDAC_MPL_HDR_LEN + 1)
113 #else
114 #define A2DP_LDAC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_LDAC_MPL_HDR_LEN)
115 #endif
116 
117 typedef struct {
118   uint32_t sample_rate;
119   uint8_t channel_mode;
120   uint8_t bits_per_sample;
121   int quality_mode_index;
122   int pcm_wlength;
123   LDACBT_SMPL_FMT_T pcm_fmt;
124 } tA2DP_LDAC_ENCODER_PARAMS;
125 
126 typedef struct {
127   uint32_t counter;
128   uint32_t bytes_per_tick; /* pcm bytes read each media task tick */
129   uint64_t last_frame_us;
130 } tA2DP_LDAC_FEEDING_STATE;
131 
132 typedef struct {
133   uint64_t session_start_us;
134 
135   size_t media_read_total_expected_packets;
136   size_t media_read_total_expected_reads_count;
137   size_t media_read_total_expected_read_bytes;
138 
139   size_t media_read_total_dropped_packets;
140   size_t media_read_total_actual_reads_count;
141   size_t media_read_total_actual_read_bytes;
142 } a2dp_ldac_encoder_stats_t;
143 
144 typedef struct {
145   a2dp_source_read_callback_t read_callback;
146   a2dp_source_enqueue_callback_t enqueue_callback;
147   uint16_t TxAaMtuSize;
148   size_t TxQueueLength;
149 
150   bool use_SCMS_T;
151   bool is_peer_edr;          // True if the peer device supports EDR
152   bool peer_supports_3mbps;  // True if the peer device supports 3Mbps EDR
153   uint16_t peer_mtu;         // MTU of the A2DP peer
154   uint32_t timestamp;        // Timestamp for the A2DP frames
155 
156   HANDLE_LDAC_BT ldac_handle;
157   bool has_ldac_handle;  // True if ldac_handle is valid
158 
159   HANDLE_LDAC_ABR ldac_abr_handle;
160   bool has_ldac_abr_handle;
161   int last_ldac_abr_eqmid;
162   size_t ldac_abr_adjustments;
163 
164   tA2DP_FEEDING_PARAMS feeding_params;
165   tA2DP_LDAC_ENCODER_PARAMS ldac_encoder_params;
166   tA2DP_LDAC_FEEDING_STATE ldac_feeding_state;
167 
168   a2dp_ldac_encoder_stats_t stats;
169 } tA2DP_LDAC_ENCODER_CB;
170 
171 static bool ldac_abr_loaded = false;
172 
173 static tA2DP_LDAC_ENCODER_CB a2dp_ldac_encoder_cb;
174 
175 static void a2dp_vendor_ldac_encoder_update(uint16_t peer_mtu,
176                                             A2dpCodecConfig* a2dp_codec_config,
177                                             bool* p_restart_input,
178                                             bool* p_restart_output,
179                                             bool* p_config_updated);
180 static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations,
181                                               uint8_t* num_of_frames,
182                                               uint64_t timestamp_us);
183 static void a2dp_ldac_encode_frames(uint8_t nb_frame);
184 static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read);
185 static std::string quality_mode_index_to_name(int quality_mode_index);
186 
load_func(const char * func_name)187 static void* load_func(const char* func_name) {
188   void* func_ptr = dlsym(ldac_encoder_lib_handle, func_name);
189   if (func_ptr == NULL) {
190     LOG_ERROR(LOG_TAG,
191               "%s: cannot find function '%s' in the encoder library: %s",
192               __func__, func_name, dlerror());
193     A2DP_VendorUnloadEncoderLdac();
194     return NULL;
195   }
196   return func_ptr;
197 }
198 
A2DP_VendorLoadEncoderLdac(void)199 bool A2DP_VendorLoadEncoderLdac(void) {
200   if (ldac_encoder_lib_handle != NULL) return true;  // Already loaded
201 
202   // Initialize the control block
203   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
204 
205   // Open the encoder library
206   ldac_encoder_lib_handle = dlopen(LDAC_ENCODER_LIB_NAME, RTLD_NOW);
207   if (ldac_encoder_lib_handle == NULL) {
208     LOG_ERROR(LOG_TAG, "%s: cannot open LDAC encoder library %s: %s", __func__,
209               LDAC_ENCODER_LIB_NAME, dlerror());
210     return false;
211   }
212 
213   // Load all functions
214   ldac_get_handle_func = (tLDAC_GET_HANDLE)load_func(LDAC_GET_HANDLE_NAME);
215   if (ldac_get_handle_func == NULL) return false;
216   ldac_free_handle_func = (tLDAC_FREE_HANDLE)load_func(LDAC_FREE_HANDLE_NAME);
217   if (ldac_free_handle_func == NULL) return false;
218   ldac_close_handle_func =
219       (tLDAC_CLOSE_HANDLE)load_func(LDAC_CLOSE_HANDLE_NAME);
220   if (ldac_close_handle_func == NULL) return false;
221   ldac_get_version_func = (tLDAC_GET_VERSION)load_func(LDAC_GET_VERSION_NAME);
222   if (ldac_get_version_func == NULL) return false;
223   ldac_get_bitrate_func = (tLDAC_GET_BITRATE)load_func(LDAC_GET_BITRATE_NAME);
224   if (ldac_get_bitrate_func == NULL) return false;
225   ldac_get_sampling_freq_func =
226       (tLDAC_GET_SAMPLING_FREQ)load_func(LDAC_GET_SAMPLING_FREQ_NAME);
227   if (ldac_get_sampling_freq_func == NULL) return false;
228   ldac_init_handle_encode_func =
229       (tLDAC_INIT_HANDLE_ENCODE)load_func(LDAC_INIT_HANDLE_ENCODE_NAME);
230   if (ldac_init_handle_encode_func == NULL) return false;
231   ldac_encode_func = (tLDAC_ENCODE)load_func(LDAC_ENCODE_NAME);
232   if (ldac_encode_func == NULL) return false;
233   ldac_set_eqmid_func = (tLDAC_SET_EQMID)load_func(LDAC_SET_EQMID_NAME);
234   if (ldac_set_eqmid_func == NULL) return false;
235   ldac_alter_eqmid_priority_func =
236       (tLDAC_ALTER_EQMID_PRIORITY)load_func(LDAC_ALTER_EQMID_PRIORITY_NAME);
237   if (ldac_alter_eqmid_priority_func == NULL) return false;
238   ldac_get_eqmid_func = (tLDAC_GET_EQMID)load_func(LDAC_GET_EQMID_NAME);
239   if (ldac_get_eqmid_func == NULL) return false;
240   ldac_get_error_code_func =
241       (tLDAC_GET_ERROR_CODE)load_func(LDAC_GET_ERROR_CODE_NAME);
242   if (ldac_get_error_code_func == NULL) return false;
243 
244   if (!A2DP_VendorLoadLdacAbr()) {
245     LOG_WARN(LOG_TAG, "%s: cannot load the LDAC ABR library", __func__);
246     ldac_abr_loaded = false;
247   } else {
248     ldac_abr_loaded = true;
249   }
250   return true;
251 }
252 
A2DP_VendorUnloadEncoderLdac(void)253 void A2DP_VendorUnloadEncoderLdac(void) {
254   // Cleanup any LDAC-related state
255   if (a2dp_ldac_encoder_cb.has_ldac_handle && ldac_free_handle_func != NULL)
256     ldac_free_handle_func(a2dp_ldac_encoder_cb.ldac_handle);
257   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
258 
259   ldac_get_handle_func = NULL;
260   ldac_free_handle_func = NULL;
261   ldac_close_handle_func = NULL;
262   ldac_get_version_func = NULL;
263   ldac_get_bitrate_func = NULL;
264   ldac_get_sampling_freq_func = NULL;
265   ldac_init_handle_encode_func = NULL;
266   ldac_encode_func = NULL;
267   ldac_set_eqmid_func = NULL;
268   ldac_alter_eqmid_priority_func = NULL;
269   ldac_get_eqmid_func = NULL;
270   ldac_get_error_code_func = NULL;
271 
272   if (ldac_encoder_lib_handle != NULL) {
273     dlclose(ldac_encoder_lib_handle);
274     ldac_encoder_lib_handle = NULL;
275   }
276 }
277 
a2dp_vendor_ldac_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)278 void a2dp_vendor_ldac_encoder_init(
279     const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
280     A2dpCodecConfig* a2dp_codec_config,
281     a2dp_source_read_callback_t read_callback,
282     a2dp_source_enqueue_callback_t enqueue_callback) {
283   if (a2dp_ldac_encoder_cb.has_ldac_handle)
284     ldac_free_handle_func(a2dp_ldac_encoder_cb.ldac_handle);
285   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle)
286     a2dp_ldac_abr_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
287   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
288 
289   a2dp_ldac_encoder_cb.stats.session_start_us =
290       bluetooth::common::time_get_os_boottime_us();
291 
292   a2dp_ldac_encoder_cb.read_callback = read_callback;
293   a2dp_ldac_encoder_cb.enqueue_callback = enqueue_callback;
294   a2dp_ldac_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
295   a2dp_ldac_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
296   a2dp_ldac_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
297   a2dp_ldac_encoder_cb.timestamp = 0;
298   a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
299   a2dp_ldac_encoder_cb.has_ldac_abr_handle = false;
300   a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
301   a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
302 
303   a2dp_ldac_encoder_cb.use_SCMS_T = false;  // TODO: should be a parameter
304 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
305   a2dp_ldac_encoder_cb.use_SCMS_T = true;
306 #endif
307 
308   // NOTE: Ignore the restart_input / restart_output flags - this initization
309   // happens when the connection is (re)started.
310   bool restart_input = false;
311   bool restart_output = false;
312   bool config_updated = false;
313   a2dp_vendor_ldac_encoder_update(a2dp_ldac_encoder_cb.peer_mtu,
314                                   a2dp_codec_config, &restart_input,
315                                   &restart_output, &config_updated);
316 }
317 
updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS * p_peer_params,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)318 bool A2dpCodecConfigLdacSource::updateEncoderUserConfig(
319     const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input,
320     bool* p_restart_output, bool* p_config_updated) {
321   a2dp_ldac_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
322   a2dp_ldac_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
323   a2dp_ldac_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
324   a2dp_ldac_encoder_cb.timestamp = 0;
325 
326   if (a2dp_ldac_encoder_cb.peer_mtu == 0) {
327     LOG_ERROR(LOG_TAG,
328               "%s: Cannot update the codec encoder for %s: "
329               "invalid peer MTU",
330               __func__, name().c_str());
331     return false;
332   }
333 
334   a2dp_vendor_ldac_encoder_update(a2dp_ldac_encoder_cb.peer_mtu, this,
335                                   p_restart_input, p_restart_output,
336                                   p_config_updated);
337   return true;
338 }
339 
340 // Update the A2DP LDAC encoder.
341 // |peer_mtu| is the peer MTU.
342 // |a2dp_codec_config| is the A2DP codec to use for the update.
a2dp_vendor_ldac_encoder_update(uint16_t peer_mtu,A2dpCodecConfig * a2dp_codec_config,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)343 static void a2dp_vendor_ldac_encoder_update(uint16_t peer_mtu,
344                                             A2dpCodecConfig* a2dp_codec_config,
345                                             bool* p_restart_input,
346                                             bool* p_restart_output,
347                                             bool* p_config_updated) {
348   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
349       &a2dp_ldac_encoder_cb.ldac_encoder_params;
350   uint8_t codec_info[AVDT_CODEC_SIZE];
351 
352   *p_restart_input = false;
353   *p_restart_output = false;
354   *p_config_updated = false;
355 
356   if (!a2dp_ldac_encoder_cb.has_ldac_handle) {
357     a2dp_ldac_encoder_cb.ldac_handle = ldac_get_handle_func();
358     if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
359       LOG_ERROR(LOG_TAG, "%s: Cannot get LDAC encoder handle", __func__);
360       return;  // TODO: Return an error?
361     }
362     a2dp_ldac_encoder_cb.has_ldac_handle = true;
363   }
364   CHECK(a2dp_ldac_encoder_cb.ldac_handle != nullptr);
365 
366   if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
367     LOG_ERROR(LOG_TAG,
368               "%s: Cannot update the codec encoder for %s: "
369               "invalid codec config",
370               __func__, a2dp_codec_config->name().c_str());
371     return;
372   }
373   const uint8_t* p_codec_info = codec_info;
374   btav_a2dp_codec_config_t codec_config = a2dp_codec_config->getCodecConfig();
375 
376   // The feeding parameters
377   tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_ldac_encoder_cb.feeding_params;
378   p_feeding_params->sample_rate =
379       A2DP_VendorGetTrackSampleRateLdac(p_codec_info);
380   p_feeding_params->bits_per_sample =
381       a2dp_codec_config->getAudioBitsPerSample();
382   p_feeding_params->channel_count =
383       A2DP_VendorGetTrackChannelCountLdac(p_codec_info);
384   LOG_DEBUG(LOG_TAG, "%s: sample_rate=%u bits_per_sample=%u channel_count=%u",
385             __func__, p_feeding_params->sample_rate,
386             p_feeding_params->bits_per_sample, p_feeding_params->channel_count);
387   a2dp_vendor_ldac_feeding_reset();
388 
389   // The codec parameters
390   p_encoder_params->sample_rate =
391       a2dp_ldac_encoder_cb.feeding_params.sample_rate;
392   p_encoder_params->channel_mode =
393       A2DP_VendorGetChannelModeCodeLdac(p_codec_info);
394 
395   uint16_t mtu_size =
396       BT_DEFAULT_BUFFER_SIZE - A2DP_LDAC_OFFSET - sizeof(BT_HDR);
397   if (mtu_size < peer_mtu) {
398     a2dp_ldac_encoder_cb.TxAaMtuSize = mtu_size;
399   } else {
400     a2dp_ldac_encoder_cb.TxAaMtuSize = peer_mtu;
401   }
402 
403   // Set the quality mode index
404   int old_quality_mode_index = p_encoder_params->quality_mode_index;
405   if (codec_config.codec_specific_1 != 0) {
406     p_encoder_params->quality_mode_index = codec_config.codec_specific_1 % 10;
407     LOG_DEBUG(LOG_TAG, "%s: setting quality mode to %s", __func__,
408               quality_mode_index_to_name(p_encoder_params->quality_mode_index)
409                   .c_str());
410   } else {
411     p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_ABR;
412     LOG_DEBUG(LOG_TAG, "%s: setting quality mode to default %s", __func__,
413               quality_mode_index_to_name(p_encoder_params->quality_mode_index)
414                   .c_str());
415   }
416 
417   int ldac_eqmid = LDAC_ABR_MODE_EQMID;
418   if (p_encoder_params->quality_mode_index == A2DP_LDAC_QUALITY_ABR) {
419     if (!ldac_abr_loaded) {
420       p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
421       LOG_WARN(
422           LOG_TAG,
423           "%s: LDAC ABR library is not loaded, resetting quality mode to %s",
424           __func__,
425           quality_mode_index_to_name(p_encoder_params->quality_mode_index)
426               .c_str());
427     } else {
428       LOG_DEBUG(LOG_TAG, "%s: changing mode from %s to %s", __func__,
429                 quality_mode_index_to_name(old_quality_mode_index).c_str(),
430                 quality_mode_index_to_name(p_encoder_params->quality_mode_index)
431                     .c_str());
432       if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
433         LOG_DEBUG(LOG_TAG, "%s: already in LDAC ABR mode, do nothing.",
434                   __func__);
435       } else {
436         LOG_DEBUG(LOG_TAG, "%s: get and init LDAC ABR handle.", __func__);
437         a2dp_ldac_encoder_cb.ldac_abr_handle = a2dp_ldac_abr_get_handle();
438         if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
439           a2dp_ldac_encoder_cb.has_ldac_abr_handle = true;
440           a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
441           a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
442           a2dp_ldac_abr_init(a2dp_ldac_encoder_cb.ldac_abr_handle,
443                              A2DP_LDAC_ENCODER_INTERVAL_MS);
444         } else {
445           p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
446           LOG_DEBUG(
447               LOG_TAG,
448               "%s: get LDAC ABR handle failed, resetting quality mode to %s.",
449               __func__,
450               quality_mode_index_to_name(p_encoder_params->quality_mode_index)
451                   .c_str());
452         }
453       }
454     }
455   } else {
456     ldac_eqmid = p_encoder_params->quality_mode_index;
457     LOG_DEBUG(LOG_TAG, "%s: in %s mode, free LDAC ABR handle.", __func__,
458               quality_mode_index_to_name(ldac_eqmid).c_str());
459     if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
460       a2dp_ldac_abr_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
461       a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
462       a2dp_ldac_encoder_cb.has_ldac_abr_handle = false;
463       a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
464       a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
465     }
466   }
467 
468   if (p_encoder_params->quality_mode_index != old_quality_mode_index)
469     *p_config_updated = true;
470 
471   p_encoder_params->pcm_wlength =
472       a2dp_ldac_encoder_cb.feeding_params.bits_per_sample >> 3;
473   // Set the Audio format from pcm_wlength
474   p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16;
475   if (p_encoder_params->pcm_wlength == 2)
476     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16;
477   else if (p_encoder_params->pcm_wlength == 3)
478     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S24;
479   else if (p_encoder_params->pcm_wlength == 4)
480     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S32;
481 
482   LOG_DEBUG(LOG_TAG, "%s: MTU=%d, peer_mtu=%d", __func__,
483             a2dp_ldac_encoder_cb.TxAaMtuSize, peer_mtu);
484   LOG_DEBUG(LOG_TAG,
485             "%s: sample_rate: %d channel_mode: %d "
486             "quality_mode_index: %d pcm_wlength: %d pcm_fmt: %d",
487             __func__, p_encoder_params->sample_rate,
488             p_encoder_params->channel_mode,
489             p_encoder_params->quality_mode_index, p_encoder_params->pcm_wlength,
490             p_encoder_params->pcm_fmt);
491 
492   // Initialize the encoder.
493   // NOTE: MTU in the initialization must include the AVDT media header size.
494   int result = ldac_init_handle_encode_func(
495       a2dp_ldac_encoder_cb.ldac_handle,
496       a2dp_ldac_encoder_cb.TxAaMtuSize + AVDT_MEDIA_HDR_SIZE, ldac_eqmid,
497       p_encoder_params->channel_mode, p_encoder_params->pcm_fmt,
498       p_encoder_params->sample_rate);
499   if (result != 0) {
500     int err_code = ldac_get_error_code_func(a2dp_ldac_encoder_cb.ldac_handle);
501     LOG_ERROR(LOG_TAG,
502               "%s: error initializing the LDAC encoder: %d api_error = %d "
503               "handle_error = %d block_error = %d error_code = 0x%x",
504               __func__, result, LDACBT_API_ERR(err_code),
505               LDACBT_HANDLE_ERR(err_code), LDACBT_BLOCK_ERR(err_code),
506               err_code);
507   }
508 }
509 
a2dp_vendor_ldac_encoder_cleanup(void)510 void a2dp_vendor_ldac_encoder_cleanup(void) {
511   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle)
512     a2dp_ldac_abr_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
513   if (a2dp_ldac_encoder_cb.has_ldac_handle)
514     ldac_free_handle_func(a2dp_ldac_encoder_cb.ldac_handle);
515   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
516 }
517 
a2dp_vendor_ldac_feeding_reset(void)518 void a2dp_vendor_ldac_feeding_reset(void) {
519   /* By default, just clear the entire state */
520   memset(&a2dp_ldac_encoder_cb.ldac_feeding_state, 0,
521          sizeof(a2dp_ldac_encoder_cb.ldac_feeding_state));
522 
523   a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick =
524       (a2dp_ldac_encoder_cb.feeding_params.sample_rate *
525        a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8 *
526        a2dp_ldac_encoder_cb.feeding_params.channel_count *
527        A2DP_LDAC_ENCODER_INTERVAL_MS) /
528       1000;
529 
530   LOG_DEBUG(LOG_TAG, "%s: PCM bytes per tick %u", __func__,
531             a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick);
532 }
533 
a2dp_vendor_ldac_feeding_flush(void)534 void a2dp_vendor_ldac_feeding_flush(void) {
535   a2dp_ldac_encoder_cb.ldac_feeding_state.counter = 0;
536 }
537 
a2dp_vendor_ldac_get_encoder_interval_ms(void)538 uint64_t a2dp_vendor_ldac_get_encoder_interval_ms(void) {
539   return A2DP_LDAC_ENCODER_INTERVAL_MS;
540 }
541 
a2dp_vendor_ldac_send_frames(uint64_t timestamp_us)542 void a2dp_vendor_ldac_send_frames(uint64_t timestamp_us) {
543   uint8_t nb_frame = 0;
544   uint8_t nb_iterations = 0;
545 
546   a2dp_ldac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
547   LOG_VERBOSE(LOG_TAG, "%s: Sending %d frames per iteration, %d iterations",
548               __func__, nb_frame, nb_iterations);
549   if (nb_frame == 0) return;
550 
551   for (uint8_t counter = 0; counter < nb_iterations; counter++) {
552     if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
553       int flag_enable = 1;
554       int prev_eqmid = a2dp_ldac_encoder_cb.last_ldac_abr_eqmid;
555       a2dp_ldac_encoder_cb.last_ldac_abr_eqmid =
556           a2dp_ldac_abr_proc(a2dp_ldac_encoder_cb.ldac_handle,
557                              a2dp_ldac_encoder_cb.ldac_abr_handle,
558                              a2dp_ldac_encoder_cb.TxQueueLength, flag_enable);
559       if (prev_eqmid != a2dp_ldac_encoder_cb.last_ldac_abr_eqmid)
560         a2dp_ldac_encoder_cb.ldac_abr_adjustments++;
561 #ifndef OS_GENERIC
562       ATRACE_INT("LDAC ABR level", a2dp_ldac_encoder_cb.last_ldac_abr_eqmid);
563 #endif
564     }
565     // Transcode frame and enqueue
566     a2dp_ldac_encode_frames(nb_frame);
567   }
568 }
569 
570 // Obtains the number of frames to send and number of iterations
571 // to be used. |num_of_iterations| and |num_of_frames| parameters
572 // are used as output param for returning the respective values.
a2dp_ldac_get_num_frame_iteration(uint8_t * num_of_iterations,uint8_t * num_of_frames,uint64_t timestamp_us)573 static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations,
574                                               uint8_t* num_of_frames,
575                                               uint64_t timestamp_us) {
576   uint32_t result = 0;
577   uint8_t nof = 0;
578   uint8_t noi = 1;
579 
580   uint32_t pcm_bytes_per_frame =
581       A2DP_LDAC_MEDIA_BYTES_PER_FRAME *
582       a2dp_ldac_encoder_cb.feeding_params.channel_count *
583       a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
584   LOG_VERBOSE(LOG_TAG, "%s: pcm_bytes_per_frame %u", __func__,
585               pcm_bytes_per_frame);
586 
587   uint32_t us_this_tick = A2DP_LDAC_ENCODER_INTERVAL_MS * 1000;
588   uint64_t now_us = timestamp_us;
589   if (a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us != 0)
590     us_this_tick =
591         (now_us - a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us);
592   a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us = now_us;
593 
594   a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
595       a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick * us_this_tick /
596       (A2DP_LDAC_ENCODER_INTERVAL_MS * 1000);
597 
598   result =
599       a2dp_ldac_encoder_cb.ldac_feeding_state.counter / pcm_bytes_per_frame;
600   a2dp_ldac_encoder_cb.ldac_feeding_state.counter -=
601       result * pcm_bytes_per_frame;
602   nof = result;
603 
604   LOG_VERBOSE(LOG_TAG, "%s: effective num of frames %u, iterations %u",
605               __func__, nof, noi);
606 
607   *num_of_frames = nof;
608   *num_of_iterations = noi;
609 }
610 
a2dp_ldac_encode_frames(uint8_t nb_frame)611 static void a2dp_ldac_encode_frames(uint8_t nb_frame) {
612   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
613       &a2dp_ldac_encoder_cb.ldac_encoder_params;
614   uint8_t remain_nb_frame = nb_frame;
615   uint16_t ldac_frame_size;
616   uint8_t read_buffer[LDACBT_MAX_LSU * 4 /* byte/sample */ * 2 /* ch */];
617 
618   switch (p_encoder_params->sample_rate) {
619     case 176400:
620     case 192000:
621       ldac_frame_size = 512;  // sample/ch
622       break;
623     case 88200:
624     case 96000:
625       ldac_frame_size = 256;  // sample/ch
626       break;
627     case 44100:
628     case 48000:
629     default:
630       ldac_frame_size = 128;  // sample/ch
631       break;
632   }
633 
634   uint32_t count;
635   int32_t encode_count = 0;
636   int32_t out_frames = 0;
637   int written = 0;
638 
639   uint32_t bytes_read = 0;
640   while (nb_frame) {
641     BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
642     p_buf->offset = A2DP_LDAC_OFFSET;
643     p_buf->len = 0;
644     p_buf->layer_specific = 0;
645     a2dp_ldac_encoder_cb.stats.media_read_total_expected_packets++;
646 
647     count = 0;
648     do {
649       //
650       // Read the PCM data and encode it
651       //
652       uint32_t temp_bytes_read = 0;
653       if (a2dp_ldac_read_feeding(read_buffer, &temp_bytes_read)) {
654         bytes_read += temp_bytes_read;
655         uint8_t* packet = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
656         if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
657           LOG_ERROR(LOG_TAG, "%s: invalid LDAC handle", __func__);
658           a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
659           osi_free(p_buf);
660           return;
661         }
662         int result = ldac_encode_func(
663             a2dp_ldac_encoder_cb.ldac_handle, read_buffer, (int*)&encode_count,
664             packet + count, (int*)&written, (int*)&out_frames);
665         if (result != 0) {
666           int err_code =
667               ldac_get_error_code_func(a2dp_ldac_encoder_cb.ldac_handle);
668           LOG_ERROR(LOG_TAG,
669                     "%s: LDAC encoding error: %d api_error = %d "
670                     "handle_error = %d block_error = %d error_code = 0x%x",
671                     __func__, result, LDACBT_API_ERR(err_code),
672                     LDACBT_HANDLE_ERR(err_code), LDACBT_BLOCK_ERR(err_code),
673                     err_code);
674           a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
675           osi_free(p_buf);
676           return;
677         }
678         count += written;
679         p_buf->len += written;
680         nb_frame--;
681         p_buf->layer_specific += out_frames;  // added a frame to the buffer
682       } else {
683         LOG_WARN(LOG_TAG, "%s: underflow %d", __func__, nb_frame);
684         a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
685             nb_frame * LDACBT_ENC_LSU *
686             a2dp_ldac_encoder_cb.feeding_params.channel_count *
687             a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
688 
689         // no more pcm to read
690         nb_frame = 0;
691       }
692     } while ((written == 0) && nb_frame);
693 
694     if (p_buf->len) {
695       /*
696        * Timestamp of the media packet header represent the TS of the
697        * first frame, i.e the timestamp before including this frame.
698        */
699       *((uint32_t*)(p_buf + 1)) = a2dp_ldac_encoder_cb.timestamp;
700 
701       a2dp_ldac_encoder_cb.timestamp += p_buf->layer_specific * ldac_frame_size;
702 
703       uint8_t done_nb_frame = remain_nb_frame - nb_frame;
704       remain_nb_frame = nb_frame;
705       if (!a2dp_ldac_encoder_cb.enqueue_callback(p_buf, done_nb_frame,
706                                                  bytes_read))
707         return;
708     } else {
709       // NOTE: Unlike the execution path for other codecs, it is normal for
710       // LDAC to NOT write encoded data to the last buffer if there wasn't
711       // enough data to write to. That data is accumulated internally by
712       // the codec and included in the next iteration. Therefore, here we
713       // don't increment the "media_read_total_dropped_packets" counter.
714       osi_free(p_buf);
715     }
716   }
717 }
718 
a2dp_ldac_read_feeding(uint8_t * read_buffer,uint32_t * bytes_read)719 static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) {
720   uint32_t read_size = LDACBT_ENC_LSU *
721                        a2dp_ldac_encoder_cb.feeding_params.channel_count *
722                        a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
723 
724   a2dp_ldac_encoder_cb.stats.media_read_total_expected_reads_count++;
725   a2dp_ldac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
726 
727   /* Read Data from UIPC channel */
728   uint32_t nb_byte_read =
729       a2dp_ldac_encoder_cb.read_callback(read_buffer, read_size);
730   a2dp_ldac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
731 
732   if (nb_byte_read < read_size) {
733     if (nb_byte_read == 0) return false;
734 
735     /* Fill the unfilled part of the read buffer with silence (0) */
736     memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
737     nb_byte_read = read_size;
738   }
739   a2dp_ldac_encoder_cb.stats.media_read_total_actual_reads_count++;
740 
741   *bytes_read = nb_byte_read;
742   return true;
743 }
744 
quality_mode_index_to_name(int quality_mode_index)745 static std::string quality_mode_index_to_name(int quality_mode_index) {
746   switch (quality_mode_index) {
747     case A2DP_LDAC_QUALITY_HIGH:
748       return "HIGH";
749     case A2DP_LDAC_QUALITY_MID:
750       return "MID";
751     case A2DP_LDAC_QUALITY_LOW:
752       return "LOW";
753     case A2DP_LDAC_QUALITY_ABR:
754       return "ABR";
755     default:
756       return "Unknown";
757   }
758 }
759 
a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length)760 void a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length) {
761   a2dp_ldac_encoder_cb.TxQueueLength = transmit_queue_length;
762 }
763 
encoderIntervalMs() const764 uint64_t A2dpCodecConfigLdacSource::encoderIntervalMs() const {
765   return a2dp_vendor_ldac_get_encoder_interval_ms();
766 }
767 
getEffectiveMtu() const768 int A2dpCodecConfigLdacSource::getEffectiveMtu() const {
769   return a2dp_ldac_encoder_cb.TxAaMtuSize;
770 }
771 
debug_codec_dump(int fd)772 void A2dpCodecConfigLdacSource::debug_codec_dump(int fd) {
773   a2dp_ldac_encoder_stats_t* stats = &a2dp_ldac_encoder_cb.stats;
774   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
775       &a2dp_ldac_encoder_cb.ldac_encoder_params;
776 
777   A2dpCodecConfig::debug_codec_dump(fd);
778 
779   dprintf(fd,
780           "  Packet counts (expected/dropped)                        : %zu / "
781           "%zu\n",
782           stats->media_read_total_expected_packets,
783           stats->media_read_total_dropped_packets);
784 
785   dprintf(fd,
786           "  PCM read counts (expected/actual)                       : %zu / "
787           "%zu\n",
788           stats->media_read_total_expected_reads_count,
789           stats->media_read_total_actual_reads_count);
790 
791   dprintf(fd,
792           "  PCM read bytes (expected/actual)                        : %zu / "
793           "%zu\n",
794           stats->media_read_total_expected_read_bytes,
795           stats->media_read_total_actual_read_bytes);
796 
797   dprintf(
798       fd, "  LDAC quality mode                                       : %s\n",
799       quality_mode_index_to_name(p_encoder_params->quality_mode_index).c_str());
800 
801   dprintf(fd,
802           "  LDAC transmission bitrate (Kbps)                        : %d\n",
803           ldac_get_bitrate_func(a2dp_ldac_encoder_cb.ldac_handle));
804 
805   dprintf(fd,
806           "  LDAC saved transmit queue length                        : %zu\n",
807           a2dp_ldac_encoder_cb.TxQueueLength);
808   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
809     dprintf(fd,
810             "  LDAC adaptive bit rate encode quality mode index        : %d\n",
811             a2dp_ldac_encoder_cb.last_ldac_abr_eqmid);
812     dprintf(fd,
813             "  LDAC adaptive bit rate adjustments                      : %zu\n",
814             a2dp_ldac_encoder_cb.ldac_abr_adjustments);
815   }
816 }
817