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 "bluetooth-a2dp"
18 #define ATRACE_TAG ATRACE_TAG_AUDIO
19 
20 #include "a2dp_vendor_ldac_encoder.h"
21 
22 #ifdef __ANDROID__
23 #include <cutils/trace.h>
24 #endif
25 #include <bluetooth/log.h>
26 #include <dlfcn.h>
27 #include <inttypes.h>
28 #include <ldacBT_abr.h>
29 #include <string.h>
30 
31 #include "a2dp_vendor_ldac.h"
32 #include "common/time_util.h"
33 #include "internal_include/bt_target.h"
34 #include "os/log.h"
35 #include "osi/include/allocator.h"
36 #include "stack/include/bt_hdr.h"
37 
38 //
39 // Encoder for LDAC Source Codec
40 //
41 
42 // Initial EQMID for ABR mode.
43 #define LDAC_ABR_MODE_EQMID LDACBT_EQMID_SQ
44 
45 // A2DP LDAC encoder interval in milliseconds
46 #define A2DP_LDAC_ENCODER_INTERVAL_MS 20
47 #define A2DP_LDAC_MEDIA_BYTES_PER_FRAME 128
48 
49 // offset
50 #define A2DP_LDAC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_LDAC_MPL_HDR_LEN)
51 
52 using namespace bluetooth;
53 
54 namespace fmt {
55 template <>
56 struct formatter<LDACBT_SMPL_FMT_T> : enum_formatter<LDACBT_SMPL_FMT_T> {};
57 }  // namespace fmt
58 
59 typedef struct {
60   uint32_t sample_rate;
61   uint8_t channel_mode;
62   uint8_t bits_per_sample;
63   int quality_mode_index;
64   int pcm_wlength;
65   LDACBT_SMPL_FMT_T pcm_fmt;
66 } tA2DP_LDAC_ENCODER_PARAMS;
67 
68 typedef struct {
69   float counter;
70   uint32_t bytes_per_tick; /* pcm bytes read each media task tick */
71   uint64_t last_frame_us;
72 } tA2DP_LDAC_FEEDING_STATE;
73 
74 typedef struct {
75   uint64_t session_start_us;
76 
77   size_t media_read_total_expected_packets;
78   size_t media_read_total_expected_reads_count;
79   size_t media_read_total_expected_read_bytes;
80 
81   size_t media_read_total_dropped_packets;
82   size_t media_read_total_actual_reads_count;
83   size_t media_read_total_actual_read_bytes;
84 } a2dp_ldac_encoder_stats_t;
85 
86 typedef struct {
87   a2dp_source_read_callback_t read_callback;
88   a2dp_source_enqueue_callback_t enqueue_callback;
89   uint16_t TxAaMtuSize;
90   size_t TxQueueLength;
91 
92   bool use_SCMS_T;
93   tA2DP_ENCODER_INIT_PEER_PARAMS peer_params;
94   uint32_t timestamp;        // Timestamp for the A2DP frames
95 
96   HANDLE_LDAC_BT ldac_handle;
97   bool has_ldac_handle;  // True if ldac_handle is valid
98 
99   HANDLE_LDAC_ABR ldac_abr_handle;
100   bool has_ldac_abr_handle;
101   int last_ldac_abr_eqmid;
102   size_t ldac_abr_adjustments;
103 
104   tA2DP_FEEDING_PARAMS feeding_params;
105   tA2DP_LDAC_ENCODER_PARAMS ldac_encoder_params;
106   tA2DP_LDAC_FEEDING_STATE ldac_feeding_state;
107 
108   a2dp_ldac_encoder_stats_t stats;
109 } tA2DP_LDAC_ENCODER_CB;
110 
111 static bool ldac_abr_loaded = true;  // the library is statically linked
112 
113 static tA2DP_LDAC_ENCODER_CB a2dp_ldac_encoder_cb;
114 
115 static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config,
116                                             bool* p_restart_input,
117                                             bool* p_restart_output,
118                                             bool* p_config_updated);
119 static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations,
120                                               uint8_t* num_of_frames,
121                                               uint64_t timestamp_us);
122 static void a2dp_ldac_encode_frames(uint8_t nb_frame);
123 static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read);
124 static uint16_t adjust_effective_mtu(
125     const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params);
126 static std::string quality_mode_index_to_name(int quality_mode_index);
127 
A2DP_VendorLoadEncoderLdac(void)128 bool A2DP_VendorLoadEncoderLdac(void) {
129   // Nothing to do - the library is statically linked
130   return true;
131 }
132 
A2DP_VendorUnloadEncoderLdac(void)133 void A2DP_VendorUnloadEncoderLdac(void) {
134   // Cleanup any LDAC-related state
135   a2dp_vendor_ldac_encoder_cleanup();
136 }
137 
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)138 void a2dp_vendor_ldac_encoder_init(
139     const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
140     A2dpCodecConfig* a2dp_codec_config,
141     a2dp_source_read_callback_t read_callback,
142     a2dp_source_enqueue_callback_t enqueue_callback) {
143   a2dp_vendor_ldac_encoder_cleanup();
144 
145   a2dp_ldac_encoder_cb.stats.session_start_us =
146       bluetooth::common::time_get_os_boottime_us();
147 
148   a2dp_ldac_encoder_cb.read_callback = read_callback;
149   a2dp_ldac_encoder_cb.enqueue_callback = enqueue_callback;
150   a2dp_ldac_encoder_cb.peer_params = *p_peer_params;
151   a2dp_ldac_encoder_cb.timestamp = 0;
152   a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
153   a2dp_ldac_encoder_cb.has_ldac_abr_handle = false;
154   a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
155   a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
156 
157   a2dp_ldac_encoder_cb.use_SCMS_T = false;
158 
159   // NOTE: Ignore the restart_input / restart_output flags - this initization
160   // happens when the audio session is (re)started.
161   bool restart_input = false;
162   bool restart_output = false;
163   bool config_updated = false;
164   a2dp_vendor_ldac_encoder_update(a2dp_codec_config, &restart_input,
165                                   &restart_output, &config_updated);
166 }
167 
168 // Update the A2DP LDAC encoder.
169 // |a2dp_codec_config| is the A2DP codec to use for the update.
a2dp_vendor_ldac_encoder_update(A2dpCodecConfig * a2dp_codec_config,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)170 static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config,
171                                             bool* p_restart_input,
172                                             bool* p_restart_output,
173                                             bool* p_config_updated) {
174   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
175       &a2dp_ldac_encoder_cb.ldac_encoder_params;
176   uint8_t codec_info[AVDT_CODEC_SIZE];
177 
178   *p_restart_input = false;
179   *p_restart_output = false;
180   *p_config_updated = false;
181 
182   if (!a2dp_ldac_encoder_cb.has_ldac_handle) {
183     a2dp_ldac_encoder_cb.ldac_handle = ldacBT_get_handle();
184     if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
185       log::error("Cannot get LDAC encoder handle");
186       return;  // TODO: Return an error?
187     }
188     a2dp_ldac_encoder_cb.has_ldac_handle = true;
189   }
190   log::assert_that(
191       a2dp_ldac_encoder_cb.ldac_handle != nullptr,
192       "assert failed: a2dp_ldac_encoder_cb.ldac_handle != nullptr");
193 
194   if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
195     log::error("Cannot update the codec encoder for {}: invalid codec config",
196                a2dp_codec_config->name());
197     return;
198   }
199   const uint8_t* p_codec_info = codec_info;
200   btav_a2dp_codec_config_t codec_config = a2dp_codec_config->getCodecConfig();
201 
202   // The feeding parameters
203   tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_ldac_encoder_cb.feeding_params;
204   p_feeding_params->sample_rate =
205       A2DP_VendorGetTrackSampleRateLdac(p_codec_info);
206   p_feeding_params->bits_per_sample =
207       a2dp_codec_config->getAudioBitsPerSample();
208   p_feeding_params->channel_count =
209       A2DP_VendorGetTrackChannelCountLdac(p_codec_info);
210   log::info("sample_rate={} bits_per_sample={} channel_count={}",
211             p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
212             p_feeding_params->channel_count);
213   a2dp_vendor_ldac_feeding_reset();
214 
215   // The codec parameters
216   p_encoder_params->sample_rate =
217       a2dp_ldac_encoder_cb.feeding_params.sample_rate;
218   p_encoder_params->channel_mode =
219       A2DP_VendorGetChannelModeCodeLdac(p_codec_info);
220 
221   // Set the quality mode index
222   int old_quality_mode_index = p_encoder_params->quality_mode_index;
223   if (codec_config.codec_specific_1 != 0) {
224     p_encoder_params->quality_mode_index = codec_config.codec_specific_1 % 10;
225     log::info("setting quality mode to {}",
226               quality_mode_index_to_name(p_encoder_params->quality_mode_index));
227   } else {
228     p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_ABR;
229     log::info("setting quality mode to default {}",
230               quality_mode_index_to_name(p_encoder_params->quality_mode_index));
231   }
232 
233   int ldac_eqmid = LDAC_ABR_MODE_EQMID;
234   if (p_encoder_params->quality_mode_index == A2DP_LDAC_QUALITY_ABR) {
235     if (!ldac_abr_loaded) {
236       p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
237       log::warn(
238           "LDAC ABR library is not loaded, resetting quality mode to {}",
239           quality_mode_index_to_name(p_encoder_params->quality_mode_index));
240     } else {
241       log::info(
242           "changing mode from {} to {}",
243           quality_mode_index_to_name(old_quality_mode_index),
244           quality_mode_index_to_name(p_encoder_params->quality_mode_index));
245       if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
246         log::info("already in LDAC ABR mode, do nothing.");
247       } else {
248         log::info("get and init LDAC ABR handle.");
249         a2dp_ldac_encoder_cb.ldac_abr_handle = ldac_ABR_get_handle();
250         if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
251           a2dp_ldac_encoder_cb.has_ldac_abr_handle = true;
252           a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
253           a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
254           ldac_ABR_Init(a2dp_ldac_encoder_cb.ldac_abr_handle,
255                         A2DP_LDAC_ENCODER_INTERVAL_MS);
256         } else {
257           p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
258           log::info(
259               "get LDAC ABR handle failed, resetting quality mode to {}.",
260               quality_mode_index_to_name(p_encoder_params->quality_mode_index));
261         }
262       }
263     }
264   } else {
265     ldac_eqmid = p_encoder_params->quality_mode_index;
266     log::info("in {} mode, free LDAC ABR handle.",
267               quality_mode_index_to_name(ldac_eqmid));
268     if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
269       ldac_ABR_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
270       a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
271       a2dp_ldac_encoder_cb.has_ldac_abr_handle = false;
272       a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1;
273       a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0;
274     }
275   }
276 
277   if (p_encoder_params->quality_mode_index != old_quality_mode_index)
278     *p_config_updated = true;
279 
280   p_encoder_params->pcm_wlength =
281       a2dp_ldac_encoder_cb.feeding_params.bits_per_sample >> 3;
282   // Set the Audio format from pcm_wlength
283   p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16;
284   if (p_encoder_params->pcm_wlength == 2)
285     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16;
286   else if (p_encoder_params->pcm_wlength == 3)
287     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S24;
288   else if (p_encoder_params->pcm_wlength == 4)
289     p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S32;
290 
291   const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params =
292       a2dp_ldac_encoder_cb.peer_params;
293   a2dp_ldac_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params);
294   log::info("MTU={}, peer_mtu={}", a2dp_ldac_encoder_cb.TxAaMtuSize,
295             peer_params.peer_mtu);
296   log::info(
297       "sample_rate: {} channel_mode: {} quality_mode_index: {} pcm_wlength: {} "
298       "pcm_fmt: {}",
299       p_encoder_params->sample_rate, p_encoder_params->channel_mode,
300       p_encoder_params->quality_mode_index, p_encoder_params->pcm_wlength,
301       p_encoder_params->pcm_fmt);
302 
303   // Initialize the encoder.
304   // NOTE: MTU in the initialization must include the AVDT media header size.
305   int result = ldacBT_init_handle_encode(
306       a2dp_ldac_encoder_cb.ldac_handle,
307       a2dp_ldac_encoder_cb.TxAaMtuSize + AVDT_MEDIA_HDR_SIZE, ldac_eqmid,
308       p_encoder_params->channel_mode, p_encoder_params->pcm_fmt,
309       p_encoder_params->sample_rate);
310   if (result != 0) {
311     int err_code = ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle);
312     log::error(
313         "error initializing the LDAC encoder: {} api_error = {} handle_error = "
314         "{} block_error = {} error_code = 0x{:x}",
315         result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code),
316         LDACBT_BLOCK_ERR(err_code), err_code);
317   }
318 }
319 
a2dp_vendor_ldac_encoder_cleanup(void)320 void a2dp_vendor_ldac_encoder_cleanup(void) {
321   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
322     ldac_ABR_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
323   }
324   if (a2dp_ldac_encoder_cb.has_ldac_handle) {
325     ldacBT_free_handle(a2dp_ldac_encoder_cb.ldac_handle);
326   }
327   memset(&a2dp_ldac_encoder_cb, 0, sizeof(a2dp_ldac_encoder_cb));
328 }
329 
a2dp_vendor_ldac_feeding_reset(void)330 void a2dp_vendor_ldac_feeding_reset(void) {
331   /* By default, just clear the entire state */
332   memset(&a2dp_ldac_encoder_cb.ldac_feeding_state, 0,
333          sizeof(a2dp_ldac_encoder_cb.ldac_feeding_state));
334 
335   a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick =
336       (a2dp_ldac_encoder_cb.feeding_params.sample_rate *
337        a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8 *
338        a2dp_ldac_encoder_cb.feeding_params.channel_count *
339        A2DP_LDAC_ENCODER_INTERVAL_MS) /
340       1000;
341 
342   log::info("PCM bytes per tick {}",
343             a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick);
344 }
345 
a2dp_vendor_ldac_feeding_flush(void)346 void a2dp_vendor_ldac_feeding_flush(void) {
347   a2dp_ldac_encoder_cb.ldac_feeding_state.counter = 0.0f;
348 }
349 
a2dp_vendor_ldac_get_encoder_interval_ms(void)350 uint64_t a2dp_vendor_ldac_get_encoder_interval_ms(void) {
351   return A2DP_LDAC_ENCODER_INTERVAL_MS;
352 }
353 
a2dp_vendor_ldac_get_effective_frame_size()354 int a2dp_vendor_ldac_get_effective_frame_size() {
355   return a2dp_ldac_encoder_cb.TxAaMtuSize;
356 }
357 
a2dp_vendor_ldac_send_frames(uint64_t timestamp_us)358 void a2dp_vendor_ldac_send_frames(uint64_t timestamp_us) {
359   uint8_t nb_frame = 0;
360   uint8_t nb_iterations = 0;
361 
362   a2dp_ldac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
363   log::verbose("Sending {} frames per iteration, {} iterations", nb_frame,
364                nb_iterations);
365   if (nb_frame == 0) return;
366 
367   for (uint8_t counter = 0; counter < nb_iterations; counter++) {
368     if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
369       int flag_enable = 1;
370       int prev_eqmid = a2dp_ldac_encoder_cb.last_ldac_abr_eqmid;
371       a2dp_ldac_encoder_cb.last_ldac_abr_eqmid =
372           ldac_ABR_Proc(a2dp_ldac_encoder_cb.ldac_handle,
373                         a2dp_ldac_encoder_cb.ldac_abr_handle,
374                         a2dp_ldac_encoder_cb.TxQueueLength, flag_enable);
375       if (prev_eqmid != a2dp_ldac_encoder_cb.last_ldac_abr_eqmid)
376         a2dp_ldac_encoder_cb.ldac_abr_adjustments++;
377 #ifdef __ANDROID__
378       ATRACE_INT("LDAC ABR level", a2dp_ldac_encoder_cb.last_ldac_abr_eqmid);
379 #endif
380     }
381     // Transcode frame and enqueue
382     a2dp_ldac_encode_frames(nb_frame);
383   }
384 }
385 
386 // Obtains the number of frames to send and number of iterations
387 // to be used. |num_of_iterations| and |num_of_frames| parameters
388 // 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)389 static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations,
390                                               uint8_t* num_of_frames,
391                                               uint64_t timestamp_us) {
392   uint32_t result = 0;
393   uint8_t nof = 0;
394   uint8_t noi = 1;
395 
396   uint32_t pcm_bytes_per_frame =
397       A2DP_LDAC_MEDIA_BYTES_PER_FRAME *
398       a2dp_ldac_encoder_cb.feeding_params.channel_count *
399       a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
400   log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame);
401 
402   uint32_t us_this_tick = A2DP_LDAC_ENCODER_INTERVAL_MS * 1000;
403   uint64_t now_us = timestamp_us;
404   if (a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us != 0)
405     us_this_tick =
406         (now_us - a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us);
407   a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us = now_us;
408 
409   a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
410       (float)a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick * us_this_tick /
411       (A2DP_LDAC_ENCODER_INTERVAL_MS * 1000);
412 
413   result =
414       a2dp_ldac_encoder_cb.ldac_feeding_state.counter / pcm_bytes_per_frame;
415   a2dp_ldac_encoder_cb.ldac_feeding_state.counter -=
416       result * pcm_bytes_per_frame;
417   nof = result;
418 
419   log::verbose("effective num of frames {}, iterations {}", nof, noi);
420 
421   *num_of_frames = nof;
422   *num_of_iterations = noi;
423 }
424 
a2dp_ldac_encode_frames(uint8_t nb_frame)425 static void a2dp_ldac_encode_frames(uint8_t nb_frame) {
426   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
427       &a2dp_ldac_encoder_cb.ldac_encoder_params;
428   uint8_t remain_nb_frame = nb_frame;
429   uint16_t ldac_frame_size;
430   uint8_t read_buffer[LDACBT_MAX_LSU * 4 /* byte/sample */ * 2 /* ch */];
431 
432   switch (p_encoder_params->sample_rate) {
433     case 176400:
434     case 192000:
435       ldac_frame_size = 512;  // sample/ch
436       break;
437     case 88200:
438     case 96000:
439       ldac_frame_size = 256;  // sample/ch
440       break;
441     case 44100:
442     case 48000:
443     default:
444       ldac_frame_size = 128;  // sample/ch
445       break;
446   }
447 
448   uint32_t count;
449   int32_t encode_count = 0;
450   int32_t out_frames = 0;
451   int written = 0;
452 
453   uint32_t bytes_read = 0;
454   while (nb_frame) {
455     BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
456     p_buf->offset = A2DP_LDAC_OFFSET;
457     p_buf->len = 0;
458     p_buf->layer_specific = 0;
459     a2dp_ldac_encoder_cb.stats.media_read_total_expected_packets++;
460 
461     count = 0;
462     do {
463       //
464       // Read the PCM data and encode it
465       //
466       uint32_t temp_bytes_read = 0;
467       if (a2dp_ldac_read_feeding(read_buffer, &temp_bytes_read)) {
468         bytes_read += temp_bytes_read;
469         uint8_t* packet = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
470         if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
471           log::error("invalid LDAC handle");
472           a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
473           osi_free(p_buf);
474           return;
475         }
476         int result = ldacBT_encode(
477             a2dp_ldac_encoder_cb.ldac_handle, read_buffer, (int*)&encode_count,
478             packet + count, (int*)&written, (int*)&out_frames);
479         if (result != 0) {
480           int err_code =
481               ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle);
482           log::error(
483               "LDAC encoding error: {} api_error = {} handle_error = {} "
484               "block_error = {} error_code = 0x{:x}",
485               result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code),
486               LDACBT_BLOCK_ERR(err_code), err_code);
487           a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
488           osi_free(p_buf);
489           return;
490         }
491         count += written;
492         p_buf->len += written;
493         nb_frame--;
494         p_buf->layer_specific += out_frames;  // added a frame to the buffer
495       } else {
496         log::warn("underflow {}", nb_frame);
497         a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
498             nb_frame * LDACBT_ENC_LSU *
499             a2dp_ldac_encoder_cb.feeding_params.channel_count *
500             a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
501 
502         // no more pcm to read
503         nb_frame = 0;
504       }
505     } while ((written == 0) && nb_frame);
506 
507     if (p_buf->len) {
508       /*
509        * Timestamp of the media packet header represent the TS of the
510        * first frame, i.e the timestamp before including this frame.
511        */
512       *((uint32_t*)(p_buf + 1)) = a2dp_ldac_encoder_cb.timestamp;
513 
514       // Timestamp will wrap over to 0 if stream continues on long enough
515       // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that
516       // no unsigned overflow is triggered as ubsan is always enabled.
517       a2dp_ldac_encoder_cb.timestamp =
518           ((uint64_t)a2dp_ldac_encoder_cb.timestamp +
519            (p_buf->layer_specific * ldac_frame_size)) & UINT32_MAX;
520 
521       uint8_t done_nb_frame = remain_nb_frame - nb_frame;
522       remain_nb_frame = nb_frame;
523       if (!a2dp_ldac_encoder_cb.enqueue_callback(p_buf, done_nb_frame,
524                                                  bytes_read))
525         return;
526     } else {
527       // NOTE: Unlike the execution path for other codecs, it is normal for
528       // LDAC to NOT write encoded data to the last buffer if there wasn't
529       // enough data to write to. That data is accumulated internally by
530       // the codec and included in the next iteration. Therefore, here we
531       // don't increment the "media_read_total_dropped_packets" counter.
532       osi_free(p_buf);
533     }
534   }
535 }
536 
a2dp_ldac_read_feeding(uint8_t * read_buffer,uint32_t * bytes_read)537 static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) {
538   uint32_t read_size = LDACBT_ENC_LSU *
539                        a2dp_ldac_encoder_cb.feeding_params.channel_count *
540                        a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
541 
542   a2dp_ldac_encoder_cb.stats.media_read_total_expected_reads_count++;
543   a2dp_ldac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
544 
545   /* Read Data from UIPC channel */
546   uint32_t nb_byte_read =
547       a2dp_ldac_encoder_cb.read_callback(read_buffer, read_size);
548   a2dp_ldac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
549 
550   if (nb_byte_read < read_size) {
551     if (nb_byte_read == 0) return false;
552 
553     /* Fill the unfilled part of the read buffer with silence (0) */
554     memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
555     nb_byte_read = read_size;
556   }
557   a2dp_ldac_encoder_cb.stats.media_read_total_actual_reads_count++;
558 
559   *bytes_read = nb_byte_read;
560   return true;
561 }
562 
adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS & peer_params)563 static uint16_t adjust_effective_mtu(
564     const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) {
565   uint16_t mtu_size =
566       BT_DEFAULT_BUFFER_SIZE - A2DP_LDAC_OFFSET - sizeof(BT_HDR);
567   if (mtu_size > peer_params.peer_mtu) {
568     mtu_size = peer_params.peer_mtu;
569   }
570   log::verbose("original AVDTP MTU size: {}", mtu_size);
571   return mtu_size;
572 }
573 
quality_mode_index_to_name(int quality_mode_index)574 static std::string quality_mode_index_to_name(int quality_mode_index) {
575   switch (quality_mode_index) {
576     case A2DP_LDAC_QUALITY_HIGH:
577       return "HIGH";
578     case A2DP_LDAC_QUALITY_MID:
579       return "MID";
580     case A2DP_LDAC_QUALITY_LOW:
581       return "LOW";
582     case A2DP_LDAC_QUALITY_ABR:
583       return "ABR";
584     default:
585       return "Unknown";
586   }
587 }
588 
a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length)589 void a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length) {
590   a2dp_ldac_encoder_cb.TxQueueLength = transmit_queue_length;
591 }
592 
debug_codec_dump(int fd)593 void A2dpCodecConfigLdacSource::debug_codec_dump(int fd) {
594   a2dp_ldac_encoder_stats_t* stats = &a2dp_ldac_encoder_cb.stats;
595   tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params =
596       &a2dp_ldac_encoder_cb.ldac_encoder_params;
597 
598   A2dpCodecConfig::debug_codec_dump(fd);
599 
600   dprintf(
601       fd, "  LDAC quality mode                                       : %s\n",
602       quality_mode_index_to_name(p_encoder_params->quality_mode_index).c_str());
603 
604   dprintf(fd,
605           "  LDAC transmission bitrate (Kbps)                        : %d\n",
606           ldacBT_get_bitrate(a2dp_ldac_encoder_cb.ldac_handle));
607 
608   dprintf(fd,
609           "  LDAC saved transmit queue length                        : %zu\n",
610           a2dp_ldac_encoder_cb.TxQueueLength);
611   if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
612     dprintf(fd,
613             "  LDAC adaptive bit rate encode quality mode index        : %d\n",
614             a2dp_ldac_encoder_cb.last_ldac_abr_eqmid);
615     dprintf(fd,
616             "  LDAC adaptive bit rate adjustments                      : %zu\n",
617             a2dp_ldac_encoder_cb.ldac_abr_adjustments);
618   }
619   dprintf(fd, "  Encoder interval (ms): %" PRIu64 "\n",
620           a2dp_vendor_ldac_get_encoder_interval_ms());
621   dprintf(fd, "  Effective MTU: %d\n",
622           a2dp_vendor_ldac_get_effective_frame_size());
623   dprintf(fd,
624           "  Packet counts (expected/dropped)                        : %zu / "
625           "%zu\n",
626           stats->media_read_total_expected_packets,
627           stats->media_read_total_dropped_packets);
628 
629   dprintf(fd,
630           "  PCM read counts (expected/actual)                       : %zu / "
631           "%zu\n",
632           stats->media_read_total_expected_reads_count,
633           stats->media_read_total_actual_reads_count);
634 
635   dprintf(fd,
636           "  PCM read bytes (expected/actual)                        : %zu / "
637           "%zu\n",
638           stats->media_read_total_expected_read_bytes,
639           stats->media_read_total_actual_read_bytes);
640 }
641