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("%s: cannot find function '%s' in the encoder library: %s",
191               __func__, func_name, dlerror());
192     A2DP_VendorUnloadEncoderLdac();
193     return NULL;
194   }
195   return func_ptr;
196 }
197 
A2DP_VendorLoadEncoderLdac(void)198 bool A2DP_VendorLoadEncoderLdac(void) {
199   if (ldac_encoder_lib_handle != NULL) return true;  // Already loaded
200 
201   // Initialize the control block
202   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
203 
204   // Open the encoder library
205   ldac_encoder_lib_handle = dlopen(LDAC_ENCODER_LIB_NAME, RTLD_NOW);
206   if (ldac_encoder_lib_handle == NULL) {
207     LOG_ERROR("%s: cannot open LDAC encoder library %s: %s", __func__,
208               LDAC_ENCODER_LIB_NAME, dlerror());
209     return false;
210   }
211 
212   // Load all functions
213   ldac_get_handle_func = (tLDAC_GET_HANDLE)load_func(LDAC_GET_HANDLE_NAME);
214   if (ldac_get_handle_func == NULL) return false;
215   ldac_free_handle_func = (tLDAC_FREE_HANDLE)load_func(LDAC_FREE_HANDLE_NAME);
216   if (ldac_free_handle_func == NULL) return false;
217   ldac_close_handle_func =
218       (tLDAC_CLOSE_HANDLE)load_func(LDAC_CLOSE_HANDLE_NAME);
219   if (ldac_close_handle_func == NULL) return false;
220   ldac_get_version_func = (tLDAC_GET_VERSION)load_func(LDAC_GET_VERSION_NAME);
221   if (ldac_get_version_func == NULL) return false;
222   ldac_get_bitrate_func = (tLDAC_GET_BITRATE)load_func(LDAC_GET_BITRATE_NAME);
223   if (ldac_get_bitrate_func == NULL) return false;
224   ldac_get_sampling_freq_func =
225       (tLDAC_GET_SAMPLING_FREQ)load_func(LDAC_GET_SAMPLING_FREQ_NAME);
226   if (ldac_get_sampling_freq_func == NULL) return false;
227   ldac_init_handle_encode_func =
228       (tLDAC_INIT_HANDLE_ENCODE)load_func(LDAC_INIT_HANDLE_ENCODE_NAME);
229   if (ldac_init_handle_encode_func == NULL) return false;
230   ldac_encode_func = (tLDAC_ENCODE)load_func(LDAC_ENCODE_NAME);
231   if (ldac_encode_func == NULL) return false;
232   ldac_set_eqmid_func = (tLDAC_SET_EQMID)load_func(LDAC_SET_EQMID_NAME);
233   if (ldac_set_eqmid_func == NULL) return false;
234   ldac_alter_eqmid_priority_func =
235       (tLDAC_ALTER_EQMID_PRIORITY)load_func(LDAC_ALTER_EQMID_PRIORITY_NAME);
236   if (ldac_alter_eqmid_priority_func == NULL) return false;
237   ldac_get_eqmid_func = (tLDAC_GET_EQMID)load_func(LDAC_GET_EQMID_NAME);
238   if (ldac_get_eqmid_func == NULL) return false;
239   ldac_get_error_code_func =
240       (tLDAC_GET_ERROR_CODE)load_func(LDAC_GET_ERROR_CODE_NAME);
241   if (ldac_get_error_code_func == NULL) return false;
242 
243   if (!A2DP_VendorLoadLdacAbr()) {
244     LOG_WARN("%s: cannot load the LDAC ABR library", __func__);
245     ldac_abr_loaded = false;
246   } else {
247     ldac_abr_loaded = true;
248   }
249   return true;
250 }
251 
A2DP_VendorUnloadEncoderLdac(void)252 void A2DP_VendorUnloadEncoderLdac(void) {
253   // Cleanup any LDAC-related state
254   if (a2dp_ldac_encoder_cb.has_ldac_handle && ldac_free_handle_func != NULL)
255     ldac_free_handle_func(a2dp_ldac_encoder_cb.ldac_handle);
256   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
257 
258   ldac_get_handle_func = NULL;
259   ldac_free_handle_func = NULL;
260   ldac_close_handle_func = NULL;
261   ldac_get_version_func = NULL;
262   ldac_get_bitrate_func = NULL;
263   ldac_get_sampling_freq_func = NULL;
264   ldac_init_handle_encode_func = NULL;
265   ldac_encode_func = NULL;
266   ldac_set_eqmid_func = NULL;
267   ldac_alter_eqmid_priority_func = NULL;
268   ldac_get_eqmid_func = NULL;
269   ldac_get_error_code_func = NULL;
270 
271   if (ldac_encoder_lib_handle != NULL) {
272     dlclose(ldac_encoder_lib_handle);
273     ldac_encoder_lib_handle = NULL;
274   }
275 }
276 
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)277 void a2dp_vendor_ldac_encoder_init(
278     const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
279     A2dpCodecConfig* a2dp_codec_config,
280     a2dp_source_read_callback_t read_callback,
281     a2dp_source_enqueue_callback_t enqueue_callback) {
282   if (a2dp_ldac_encoder_cb.has_ldac_handle)
283     ldac_free_handle_func(a2dp_ldac_encoder_cb.ldac_handle);
284   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle)
285     a2dp_ldac_abr_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
286   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
287 
288   a2dp_ldac_encoder_cb.stats.session_start_us =
289       bluetooth::common::time_get_os_boottime_us();
290 
291   a2dp_ldac_encoder_cb.read_callback = read_callback;
292   a2dp_ldac_encoder_cb.enqueue_callback = enqueue_callback;
293   a2dp_ldac_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
294   a2dp_ldac_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
295   a2dp_ldac_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
296   a2dp_ldac_encoder_cb.timestamp = 0;
297   a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
298   a2dp_ldac_encoder_cb.has_ldac_abr_handle = false;
299   a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
300   a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
301 
302   a2dp_ldac_encoder_cb.use_SCMS_T = false;  // TODO: should be a parameter
303 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
304   a2dp_ldac_encoder_cb.use_SCMS_T = true;
305 #endif
306 
307   // NOTE: Ignore the restart_input / restart_output flags - this initization
308   // happens when the connection is (re)started.
309   bool restart_input = false;
310   bool restart_output = false;
311   bool config_updated = false;
312   a2dp_vendor_ldac_encoder_update(a2dp_ldac_encoder_cb.peer_mtu,
313                                   a2dp_codec_config, &restart_input,
314                                   &restart_output, &config_updated);
315 }
316 
updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS * p_peer_params,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)317 bool A2dpCodecConfigLdacSource::updateEncoderUserConfig(
318     const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input,
319     bool* p_restart_output, bool* p_config_updated) {
320   a2dp_ldac_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
321   a2dp_ldac_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
322   a2dp_ldac_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
323   a2dp_ldac_encoder_cb.timestamp = 0;
324 
325   if (a2dp_ldac_encoder_cb.peer_mtu == 0) {
326     LOG_ERROR(
327         "%s: Cannot update the codec encoder for %s: "
328         "invalid peer MTU",
329         __func__, name().c_str());
330     return false;
331   }
332 
333   a2dp_vendor_ldac_encoder_update(a2dp_ldac_encoder_cb.peer_mtu, this,
334                                   p_restart_input, p_restart_output,
335                                   p_config_updated);
336   return true;
337 }
338 
339 // Update the A2DP LDAC encoder.
340 // |peer_mtu| is the peer MTU.
341 // |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)342 static void a2dp_vendor_ldac_encoder_update(uint16_t peer_mtu,
343                                             A2dpCodecConfig* a2dp_codec_config,
344                                             bool* p_restart_input,
345                                             bool* p_restart_output,
346                                             bool* p_config_updated) {
347   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
348       &a2dp_ldac_encoder_cb.ldac_encoder_params;
349   uint8_t codec_info[AVDT_CODEC_SIZE];
350 
351   *p_restart_input = false;
352   *p_restart_output = false;
353   *p_config_updated = false;
354 
355   if (!a2dp_ldac_encoder_cb.has_ldac_handle) {
356     a2dp_ldac_encoder_cb.ldac_handle = ldac_get_handle_func();
357     if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
358       LOG_ERROR("%s: Cannot get LDAC encoder handle", __func__);
359       return;  // TODO: Return an error?
360     }
361     a2dp_ldac_encoder_cb.has_ldac_handle = true;
362   }
363   CHECK(a2dp_ldac_encoder_cb.ldac_handle != nullptr);
364 
365   if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
366     LOG_ERROR(
367         "%s: Cannot update the codec encoder for %s: "
368         "invalid codec config",
369         __func__, a2dp_codec_config->name().c_str());
370     return;
371   }
372   const uint8_t* p_codec_info = codec_info;
373   btav_a2dp_codec_config_t codec_config = a2dp_codec_config->getCodecConfig();
374 
375   // The feeding parameters
376   tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_ldac_encoder_cb.feeding_params;
377   p_feeding_params->sample_rate =
378       A2DP_VendorGetTrackSampleRateLdac(p_codec_info);
379   p_feeding_params->bits_per_sample =
380       a2dp_codec_config->getAudioBitsPerSample();
381   p_feeding_params->channel_count =
382       A2DP_VendorGetTrackChannelCountLdac(p_codec_info);
383   LOG_DEBUG("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
384             p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
385             p_feeding_params->channel_count);
386   a2dp_vendor_ldac_feeding_reset();
387 
388   // The codec parameters
389   p_encoder_params->sample_rate =
390       a2dp_ldac_encoder_cb.feeding_params.sample_rate;
391   p_encoder_params->channel_mode =
392       A2DP_VendorGetChannelModeCodeLdac(p_codec_info);
393 
394   uint16_t mtu_size =
395       BT_DEFAULT_BUFFER_SIZE - A2DP_LDAC_OFFSET - sizeof(BT_HDR);
396   if (mtu_size < peer_mtu) {
397     a2dp_ldac_encoder_cb.TxAaMtuSize = mtu_size;
398   } else {
399     a2dp_ldac_encoder_cb.TxAaMtuSize = peer_mtu;
400   }
401 
402   // Set the quality mode index
403   int old_quality_mode_index = p_encoder_params->quality_mode_index;
404   if (codec_config.codec_specific_1 != 0) {
405     p_encoder_params->quality_mode_index = codec_config.codec_specific_1 % 10;
406     LOG_DEBUG("%s: setting quality mode to %s", __func__,
407               quality_mode_index_to_name(p_encoder_params->quality_mode_index)
408                   .c_str());
409   } else {
410     p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_ABR;
411     LOG_DEBUG("%s: setting quality mode to default %s", __func__,
412               quality_mode_index_to_name(p_encoder_params->quality_mode_index)
413                   .c_str());
414   }
415 
416   int ldac_eqmid = LDAC_ABR_MODE_EQMID;
417   if (p_encoder_params->quality_mode_index == A2DP_LDAC_QUALITY_ABR) {
418     if (!ldac_abr_loaded) {
419       p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
420       LOG_WARN(
421 
422           "%s: LDAC ABR library is not loaded, resetting quality mode to %s",
423           __func__,
424           quality_mode_index_to_name(p_encoder_params->quality_mode_index)
425               .c_str());
426     } else {
427       LOG_DEBUG("%s: changing mode from %s to %s", __func__,
428                 quality_mode_index_to_name(old_quality_mode_index).c_str(),
429                 quality_mode_index_to_name(p_encoder_params->quality_mode_index)
430                     .c_str());
431       if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
432         LOG_DEBUG("%s: already in LDAC ABR mode, do nothing.", __func__);
433       } else {
434         LOG_DEBUG("%s: get and init LDAC ABR handle.", __func__);
435         a2dp_ldac_encoder_cb.ldac_abr_handle = a2dp_ldac_abr_get_handle();
436         if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
437           a2dp_ldac_encoder_cb.has_ldac_abr_handle = true;
438           a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
439           a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
440           a2dp_ldac_abr_init(a2dp_ldac_encoder_cb.ldac_abr_handle,
441                              A2DP_LDAC_ENCODER_INTERVAL_MS);
442         } else {
443           p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
444           LOG_DEBUG(
445 
446               "%s: get LDAC ABR handle failed, resetting quality mode to %s.",
447               __func__,
448               quality_mode_index_to_name(p_encoder_params->quality_mode_index)
449                   .c_str());
450         }
451       }
452     }
453   } else {
454     ldac_eqmid = p_encoder_params->quality_mode_index;
455     LOG_DEBUG("%s: in %s mode, free LDAC ABR handle.", __func__,
456               quality_mode_index_to_name(ldac_eqmid).c_str());
457     if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
458       a2dp_ldac_abr_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
459       a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
460       a2dp_ldac_encoder_cb.has_ldac_abr_handle = false;
461       a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
462       a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
463     }
464   }
465 
466   if (p_encoder_params->quality_mode_index != old_quality_mode_index)
467     *p_config_updated = true;
468 
469   p_encoder_params->pcm_wlength =
470       a2dp_ldac_encoder_cb.feeding_params.bits_per_sample >> 3;
471   // Set the Audio format from pcm_wlength
472   p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16;
473   if (p_encoder_params->pcm_wlength == 2)
474     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16;
475   else if (p_encoder_params->pcm_wlength == 3)
476     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S24;
477   else if (p_encoder_params->pcm_wlength == 4)
478     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S32;
479 
480   LOG_DEBUG("%s: MTU=%d, peer_mtu=%d", __func__,
481             a2dp_ldac_encoder_cb.TxAaMtuSize, peer_mtu);
482   LOG_DEBUG(
483       "%s: sample_rate: %d channel_mode: %d "
484       "quality_mode_index: %d pcm_wlength: %d pcm_fmt: %d",
485       __func__, p_encoder_params->sample_rate, p_encoder_params->channel_mode,
486       p_encoder_params->quality_mode_index, p_encoder_params->pcm_wlength,
487       p_encoder_params->pcm_fmt);
488 
489   // Initialize the encoder.
490   // NOTE: MTU in the initialization must include the AVDT media header size.
491   int result = ldac_init_handle_encode_func(
492       a2dp_ldac_encoder_cb.ldac_handle,
493       a2dp_ldac_encoder_cb.TxAaMtuSize + AVDT_MEDIA_HDR_SIZE, ldac_eqmid,
494       p_encoder_params->channel_mode, p_encoder_params->pcm_fmt,
495       p_encoder_params->sample_rate);
496   if (result != 0) {
497     int err_code = ldac_get_error_code_func(a2dp_ldac_encoder_cb.ldac_handle);
498     LOG_ERROR(
499         "%s: error initializing the LDAC encoder: %d api_error = %d "
500         "handle_error = %d block_error = %d error_code = 0x%x",
501         __func__, result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code),
502         LDACBT_BLOCK_ERR(err_code), err_code);
503   }
504 }
505 
a2dp_vendor_ldac_encoder_cleanup(void)506 void a2dp_vendor_ldac_encoder_cleanup(void) {
507   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle)
508     a2dp_ldac_abr_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
509   if (a2dp_ldac_encoder_cb.has_ldac_handle)
510     ldac_free_handle_func(a2dp_ldac_encoder_cb.ldac_handle);
511   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
512 }
513 
a2dp_vendor_ldac_feeding_reset(void)514 void a2dp_vendor_ldac_feeding_reset(void) {
515   /* By default, just clear the entire state */
516   memset(&a2dp_ldac_encoder_cb.ldac_feeding_state, 0,
517          sizeof(a2dp_ldac_encoder_cb.ldac_feeding_state));
518 
519   a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick =
520       (a2dp_ldac_encoder_cb.feeding_params.sample_rate *
521        a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8 *
522        a2dp_ldac_encoder_cb.feeding_params.channel_count *
523        A2DP_LDAC_ENCODER_INTERVAL_MS) /
524       1000;
525 
526   LOG_DEBUG("%s: PCM bytes per tick %u", __func__,
527             a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick);
528 }
529 
a2dp_vendor_ldac_feeding_flush(void)530 void a2dp_vendor_ldac_feeding_flush(void) {
531   a2dp_ldac_encoder_cb.ldac_feeding_state.counter = 0;
532 }
533 
a2dp_vendor_ldac_get_encoder_interval_ms(void)534 uint64_t a2dp_vendor_ldac_get_encoder_interval_ms(void) {
535   return A2DP_LDAC_ENCODER_INTERVAL_MS;
536 }
537 
a2dp_vendor_ldac_send_frames(uint64_t timestamp_us)538 void a2dp_vendor_ldac_send_frames(uint64_t timestamp_us) {
539   uint8_t nb_frame = 0;
540   uint8_t nb_iterations = 0;
541 
542   a2dp_ldac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
543   LOG_VERBOSE("%s: Sending %d frames per iteration, %d iterations", __func__,
544               nb_frame, nb_iterations);
545   if (nb_frame == 0) return;
546 
547   for (uint8_t counter = 0; counter < nb_iterations; counter++) {
548     if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
549       int flag_enable = 1;
550       int prev_eqmid = a2dp_ldac_encoder_cb.last_ldac_abr_eqmid;
551       a2dp_ldac_encoder_cb.last_ldac_abr_eqmid =
552           a2dp_ldac_abr_proc(a2dp_ldac_encoder_cb.ldac_handle,
553                              a2dp_ldac_encoder_cb.ldac_abr_handle,
554                              a2dp_ldac_encoder_cb.TxQueueLength, flag_enable);
555       if (prev_eqmid != a2dp_ldac_encoder_cb.last_ldac_abr_eqmid)
556         a2dp_ldac_encoder_cb.ldac_abr_adjustments++;
557 #ifndef OS_GENERIC
558       ATRACE_INT("LDAC ABR level", a2dp_ldac_encoder_cb.last_ldac_abr_eqmid);
559 #endif
560     }
561     // Transcode frame and enqueue
562     a2dp_ldac_encode_frames(nb_frame);
563   }
564 }
565 
566 // Obtains the number of frames to send and number of iterations
567 // to be used. |num_of_iterations| and |num_of_frames| parameters
568 // 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)569 static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations,
570                                               uint8_t* num_of_frames,
571                                               uint64_t timestamp_us) {
572   uint32_t result = 0;
573   uint8_t nof = 0;
574   uint8_t noi = 1;
575 
576   uint32_t pcm_bytes_per_frame =
577       A2DP_LDAC_MEDIA_BYTES_PER_FRAME *
578       a2dp_ldac_encoder_cb.feeding_params.channel_count *
579       a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
580   LOG_VERBOSE("%s: pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
581 
582   uint32_t us_this_tick = A2DP_LDAC_ENCODER_INTERVAL_MS * 1000;
583   uint64_t now_us = timestamp_us;
584   if (a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us != 0)
585     us_this_tick =
586         (now_us - a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us);
587   a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us = now_us;
588 
589   a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
590       a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick * us_this_tick /
591       (A2DP_LDAC_ENCODER_INTERVAL_MS * 1000);
592 
593   result =
594       a2dp_ldac_encoder_cb.ldac_feeding_state.counter / pcm_bytes_per_frame;
595   a2dp_ldac_encoder_cb.ldac_feeding_state.counter -=
596       result * pcm_bytes_per_frame;
597   nof = result;
598 
599   LOG_VERBOSE("%s: effective num of frames %u, iterations %u", __func__, nof,
600               noi);
601 
602   *num_of_frames = nof;
603   *num_of_iterations = noi;
604 }
605 
a2dp_ldac_encode_frames(uint8_t nb_frame)606 static void a2dp_ldac_encode_frames(uint8_t nb_frame) {
607   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
608       &a2dp_ldac_encoder_cb.ldac_encoder_params;
609   uint8_t remain_nb_frame = nb_frame;
610   uint16_t ldac_frame_size;
611   uint8_t read_buffer[LDACBT_MAX_LSU * 4 /* byte/sample */ * 2 /* ch */];
612 
613   switch (p_encoder_params->sample_rate) {
614     case 176400:
615     case 192000:
616       ldac_frame_size = 512;  // sample/ch
617       break;
618     case 88200:
619     case 96000:
620       ldac_frame_size = 256;  // sample/ch
621       break;
622     case 44100:
623     case 48000:
624     default:
625       ldac_frame_size = 128;  // sample/ch
626       break;
627   }
628 
629   uint32_t count;
630   int32_t encode_count = 0;
631   int32_t out_frames = 0;
632   int written = 0;
633 
634   uint32_t bytes_read = 0;
635   while (nb_frame) {
636     BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
637     p_buf->offset = A2DP_LDAC_OFFSET;
638     p_buf->len = 0;
639     p_buf->layer_specific = 0;
640     a2dp_ldac_encoder_cb.stats.media_read_total_expected_packets++;
641 
642     count = 0;
643     do {
644       //
645       // Read the PCM data and encode it
646       //
647       uint32_t temp_bytes_read = 0;
648       if (a2dp_ldac_read_feeding(read_buffer, &temp_bytes_read)) {
649         bytes_read += temp_bytes_read;
650         uint8_t* packet = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
651         if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
652           LOG_ERROR("%s: invalid LDAC handle", __func__);
653           a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
654           osi_free(p_buf);
655           return;
656         }
657         int result = ldac_encode_func(
658             a2dp_ldac_encoder_cb.ldac_handle, read_buffer, (int*)&encode_count,
659             packet + count, (int*)&written, (int*)&out_frames);
660         if (result != 0) {
661           int err_code =
662               ldac_get_error_code_func(a2dp_ldac_encoder_cb.ldac_handle);
663           LOG_ERROR(
664               "%s: LDAC encoding error: %d api_error = %d "
665               "handle_error = %d block_error = %d error_code = 0x%x",
666               __func__, result, LDACBT_API_ERR(err_code),
667               LDACBT_HANDLE_ERR(err_code), LDACBT_BLOCK_ERR(err_code),
668               err_code);
669           a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
670           osi_free(p_buf);
671           return;
672         }
673         count += written;
674         p_buf->len += written;
675         nb_frame--;
676         p_buf->layer_specific += out_frames;  // added a frame to the buffer
677       } else {
678         LOG_WARN("%s: underflow %d", __func__, nb_frame);
679         a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
680             nb_frame * LDACBT_ENC_LSU *
681             a2dp_ldac_encoder_cb.feeding_params.channel_count *
682             a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
683 
684         // no more pcm to read
685         nb_frame = 0;
686       }
687     } while ((written == 0) && nb_frame);
688 
689     if (p_buf->len) {
690       /*
691        * Timestamp of the media packet header represent the TS of the
692        * first frame, i.e the timestamp before including this frame.
693        */
694       *((uint32_t*)(p_buf + 1)) = a2dp_ldac_encoder_cb.timestamp;
695 
696       a2dp_ldac_encoder_cb.timestamp += p_buf->layer_specific * ldac_frame_size;
697 
698       uint8_t done_nb_frame = remain_nb_frame - nb_frame;
699       remain_nb_frame = nb_frame;
700       if (!a2dp_ldac_encoder_cb.enqueue_callback(p_buf, done_nb_frame,
701                                                  bytes_read))
702         return;
703     } else {
704       // NOTE: Unlike the execution path for other codecs, it is normal for
705       // LDAC to NOT write encoded data to the last buffer if there wasn't
706       // enough data to write to. That data is accumulated internally by
707       // the codec and included in the next iteration. Therefore, here we
708       // don't increment the "media_read_total_dropped_packets" counter.
709       osi_free(p_buf);
710     }
711   }
712 }
713 
a2dp_ldac_read_feeding(uint8_t * read_buffer,uint32_t * bytes_read)714 static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) {
715   uint32_t read_size = LDACBT_ENC_LSU *
716                        a2dp_ldac_encoder_cb.feeding_params.channel_count *
717                        a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
718 
719   a2dp_ldac_encoder_cb.stats.media_read_total_expected_reads_count++;
720   a2dp_ldac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
721 
722   /* Read Data from UIPC channel */
723   uint32_t nb_byte_read =
724       a2dp_ldac_encoder_cb.read_callback(read_buffer, read_size);
725   a2dp_ldac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
726 
727   if (nb_byte_read < read_size) {
728     if (nb_byte_read == 0) return false;
729 
730     /* Fill the unfilled part of the read buffer with silence (0) */
731     memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
732     nb_byte_read = read_size;
733   }
734   a2dp_ldac_encoder_cb.stats.media_read_total_actual_reads_count++;
735 
736   *bytes_read = nb_byte_read;
737   return true;
738 }
739 
quality_mode_index_to_name(int quality_mode_index)740 static std::string quality_mode_index_to_name(int quality_mode_index) {
741   switch (quality_mode_index) {
742     case A2DP_LDAC_QUALITY_HIGH:
743       return "HIGH";
744     case A2DP_LDAC_QUALITY_MID:
745       return "MID";
746     case A2DP_LDAC_QUALITY_LOW:
747       return "LOW";
748     case A2DP_LDAC_QUALITY_ABR:
749       return "ABR";
750     default:
751       return "Unknown";
752   }
753 }
754 
a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length)755 void a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length) {
756   a2dp_ldac_encoder_cb.TxQueueLength = transmit_queue_length;
757 }
758 
encoderIntervalMs() const759 uint64_t A2dpCodecConfigLdacSource::encoderIntervalMs() const {
760   return a2dp_vendor_ldac_get_encoder_interval_ms();
761 }
762 
getEffectiveMtu() const763 int A2dpCodecConfigLdacSource::getEffectiveMtu() const {
764   return a2dp_ldac_encoder_cb.TxAaMtuSize;
765 }
766 
debug_codec_dump(int fd)767 void A2dpCodecConfigLdacSource::debug_codec_dump(int fd) {
768   a2dp_ldac_encoder_stats_t* stats = &a2dp_ldac_encoder_cb.stats;
769   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
770       &a2dp_ldac_encoder_cb.ldac_encoder_params;
771 
772   A2dpCodecConfig::debug_codec_dump(fd);
773 
774   dprintf(fd,
775           "  Packet counts (expected/dropped)                        : %zu / "
776           "%zu\n",
777           stats->media_read_total_expected_packets,
778           stats->media_read_total_dropped_packets);
779 
780   dprintf(fd,
781           "  PCM read counts (expected/actual)                       : %zu / "
782           "%zu\n",
783           stats->media_read_total_expected_reads_count,
784           stats->media_read_total_actual_reads_count);
785 
786   dprintf(fd,
787           "  PCM read bytes (expected/actual)                        : %zu / "
788           "%zu\n",
789           stats->media_read_total_expected_read_bytes,
790           stats->media_read_total_actual_read_bytes);
791 
792   dprintf(
793       fd, "  LDAC quality mode                                       : %s\n",
794       quality_mode_index_to_name(p_encoder_params->quality_mode_index).c_str());
795 
796   dprintf(fd,
797           "  LDAC transmission bitrate (Kbps)                        : %d\n",
798           ldac_get_bitrate_func(a2dp_ldac_encoder_cb.ldac_handle));
799 
800   dprintf(fd,
801           "  LDAC saved transmit queue length                        : %zu\n",
802           a2dp_ldac_encoder_cb.TxQueueLength);
803   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
804     dprintf(fd,
805             "  LDAC adaptive bit rate encode quality mode index        : %d\n",
806             a2dp_ldac_encoder_cb.last_ldac_abr_eqmid);
807     dprintf(fd,
808             "  LDAC adaptive bit rate adjustments                      : %zu\n",
809             a2dp_ldac_encoder_cb.ldac_abr_adjustments);
810   }
811 }
812