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 
19 #include "a2dp_vendor_aptx_encoder.h"
20 
21 #include <bluetooth/log.h>
22 #include <inttypes.h>
23 #include <stdio.h>
24 #include <string.h>
25 
26 #include <cstdint>
27 
28 #include "a2dp_codec_api.h"
29 #include "a2dp_vendor.h"
30 #include "a2dp_vendor_aptx.h"
31 #include "aptXbtenc.h"
32 #include "avdt_api.h"
33 #include "common/time_util.h"
34 #include "internal_include/bt_target.h"
35 #include "osi/include/allocator.h"
36 #include "stack/include/bt_hdr.h"
37 
38 using namespace bluetooth;
39 
40 //
41 // Encoder for aptX Source Codec
42 //
43 
44 static const tAPTX_API aptx_api = {
45         .init_func = aptxbtenc_init,
46         .encode_stereo_func = aptxbtenc_encodestereo,
47         .sizeof_params_func = SizeofAptxbtenc,
48 };
49 
50 // offset
51 // no RTP header for aptX classic
52 #define A2DP_APTX_OFFSET (AVDT_MEDIA_OFFSET - AVDT_MEDIA_HDR_SIZE)
53 
54 #define A2DP_APTX_MAX_PCM_BYTES_PER_READ 4096
55 
56 typedef struct {
57   uint64_t sleep_time_ns;
58   uint32_t pcm_reads;
59   uint32_t pcm_bytes_per_read;
60   uint32_t aptx_bytes;
61   uint32_t frame_size_counter;
62 } tAPTX_FRAMING_PARAMS;
63 
64 typedef struct {
65   uint64_t session_start_us;
66 
67   size_t media_read_total_expected_packets;
68   size_t media_read_total_expected_reads_count;
69   size_t media_read_total_expected_read_bytes;
70 
71   size_t media_read_total_dropped_packets;
72   size_t media_read_total_actual_reads_count;
73   size_t media_read_total_actual_read_bytes;
74 } a2dp_aptx_encoder_stats_t;
75 
76 typedef struct {
77   a2dp_source_read_callback_t read_callback;
78   a2dp_source_enqueue_callback_t enqueue_callback;
79 
80   bool use_SCMS_T;
81   tA2DP_ENCODER_INIT_PEER_PARAMS peer_params;
82   uint32_t timestamp;  // Timestamp for the A2DP frames
83 
84   tA2DP_FEEDING_PARAMS feeding_params;
85   tAPTX_FRAMING_PARAMS framing_params;
86   void* aptx_encoder_state;
87   a2dp_aptx_encoder_stats_t stats;
88 } tA2DP_APTX_ENCODER_CB;
89 
90 static tA2DP_APTX_ENCODER_CB a2dp_aptx_encoder_cb;
91 
92 static void a2dp_vendor_aptx_encoder_update(A2dpCodecConfig* a2dp_codec_config,
93                                             bool* p_restart_input, bool* p_restart_output,
94                                             bool* p_config_updated);
95 static void aptx_init_framing_params(tAPTX_FRAMING_PARAMS* framing_params);
96 static void aptx_update_framing_params(tAPTX_FRAMING_PARAMS* framing_params);
97 static size_t aptx_encode_16bit(tAPTX_FRAMING_PARAMS* framing_params, size_t* data_out_index,
98                                 uint16_t* data16_in, uint8_t* data_out);
99 
100 /*******************************************************************************
101  *
102  * Function         A2DP_VendorLoadEncoderAptx
103  *
104  * Description      This function will try to load the aptx encoder library.
105  *
106  * Returns          LOAD_SUCCESS on success
107  *                  LOAD_ERROR_MISSING_CODEC on missing library
108  *                  LOAD_ERROR_VERSION_MISMATCH on symbol loading error
109  *
110  ******************************************************************************/
A2DP_VendorLoadEncoderAptx(void)111 tLOADING_CODEC_STATUS A2DP_VendorLoadEncoderAptx(void) {
112   // Nothing to do - the library is statically linked
113   return LOAD_SUCCESS;
114 }
115 
A2DP_VendorCopyAptxApi(tAPTX_API & external_api)116 bool A2DP_VendorCopyAptxApi(tAPTX_API& external_api) {
117   external_api = aptx_api;
118   return true;
119 }
120 
A2DP_VendorUnloadEncoderAptx(void)121 void A2DP_VendorUnloadEncoderAptx(void) {
122   // nothing to do
123 }
124 
a2dp_vendor_aptx_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)125 void a2dp_vendor_aptx_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
126                                    A2dpCodecConfig* a2dp_codec_config,
127                                    a2dp_source_read_callback_t read_callback,
128                                    a2dp_source_enqueue_callback_t enqueue_callback) {
129   memset(&a2dp_aptx_encoder_cb, 0, sizeof(a2dp_aptx_encoder_cb));
130 
131   a2dp_aptx_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us();
132 
133   a2dp_aptx_encoder_cb.read_callback = read_callback;
134   a2dp_aptx_encoder_cb.enqueue_callback = enqueue_callback;
135   a2dp_aptx_encoder_cb.peer_params = *p_peer_params;
136   a2dp_aptx_encoder_cb.timestamp = 0;
137 
138   /* aptX encoder config */
139   a2dp_aptx_encoder_cb.use_SCMS_T = false;
140 
141   a2dp_aptx_encoder_cb.aptx_encoder_state = osi_malloc(aptx_api.sizeof_params_func());
142   if (a2dp_aptx_encoder_cb.aptx_encoder_state != NULL) {
143     aptx_api.init_func(a2dp_aptx_encoder_cb.aptx_encoder_state, 0);
144   } else {
145     log::error("Cannot allocate aptX encoder state");
146     // TODO: Return an error?
147   }
148 
149   // NOTE: Ignore the restart_input / restart_output flags - this initization
150   // happens when the audio session is (re)started.
151   bool restart_input = false;
152   bool restart_output = false;
153   bool config_updated = false;
154   a2dp_vendor_aptx_encoder_update(a2dp_codec_config, &restart_input, &restart_output,
155                                   &config_updated);
156 }
157 
158 // Update the A2DP aptX encoder.
159 // |a2dp_codec_config| is the A2DP codec to use for the update.
a2dp_vendor_aptx_encoder_update(A2dpCodecConfig * a2dp_codec_config,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)160 static void a2dp_vendor_aptx_encoder_update(A2dpCodecConfig* a2dp_codec_config,
161                                             bool* p_restart_input, bool* p_restart_output,
162                                             bool* p_config_updated) {
163   uint8_t codec_info[AVDT_CODEC_SIZE];
164 
165   *p_restart_input = false;
166   *p_restart_output = false;
167   *p_config_updated = false;
168   if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
169     log::error("Cannot update the codec encoder for {}: invalid codec config",
170                a2dp_codec_config->name());
171     return;
172   }
173   const uint8_t* p_codec_info = codec_info;
174 
175   // The feeding parameters
176   tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aptx_encoder_cb.feeding_params;
177   p_feeding_params->sample_rate = A2DP_VendorGetTrackSampleRateAptx(p_codec_info);
178   p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample();
179   p_feeding_params->channel_count = A2DP_VendorGetTrackChannelCountAptx(p_codec_info);
180   log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate,
181             p_feeding_params->bits_per_sample, p_feeding_params->channel_count);
182   a2dp_vendor_aptx_feeding_reset();
183 }
184 
a2dp_vendor_aptx_encoder_cleanup(void)185 void a2dp_vendor_aptx_encoder_cleanup(void) {
186   osi_free(a2dp_aptx_encoder_cb.aptx_encoder_state);
187   memset(&a2dp_aptx_encoder_cb, 0, sizeof(a2dp_aptx_encoder_cb));
188 }
189 
190 //
191 // Initialize the framing parameters, and set those that don't change
192 // while streaming (e.g., 'sleep_time_ns').
193 //
aptx_init_framing_params(tAPTX_FRAMING_PARAMS * framing_params)194 static void aptx_init_framing_params(tAPTX_FRAMING_PARAMS* framing_params) {
195   framing_params->sleep_time_ns = 0;
196   framing_params->pcm_reads = 0;
197   framing_params->pcm_bytes_per_read = 0;
198   framing_params->aptx_bytes = 0;
199   framing_params->frame_size_counter = 0;
200 
201   if (a2dp_aptx_encoder_cb.feeding_params.sample_rate == 48000) {
202     if (a2dp_aptx_encoder_cb.use_SCMS_T) {
203       framing_params->sleep_time_ns = 13000000;
204     } else {
205       framing_params->sleep_time_ns = 14000000;
206     }
207   } else {
208     // Assume the sample rate is 44100
209     if (a2dp_aptx_encoder_cb.use_SCMS_T) {
210       framing_params->sleep_time_ns = 14000000;
211     } else {
212       framing_params->sleep_time_ns = 15000000;
213     }
214   }
215 
216   log::info("sleep_time_ns={}", framing_params->sleep_time_ns);
217 }
218 
219 //
220 // Set frame size and transmission interval needed to stream the required
221 // sample rate using 2-DH5 packets for aptX and 2-DH3 packets for aptX-LL.
222 // With SCMS-T enabled we need to reserve room for extra headers added later.
223 // Packets are always sent at equals time intervals but to achieve the
224 // required sample rate, the frame size needs to change on occasion.
225 //
226 // Also need to specify how many of the required PCM samples are read at a
227 // time:
228 //     aptx_bytes = pcm_reads * pcm_bytes_per_read / 4
229 // and
230 //     number of aptX samples produced = pcm_bytes_per_read / 16
231 //
aptx_update_framing_params(tAPTX_FRAMING_PARAMS * framing_params)232 static void aptx_update_framing_params(tAPTX_FRAMING_PARAMS* framing_params) {
233   if (a2dp_aptx_encoder_cb.feeding_params.sample_rate == 48000) {
234     if (a2dp_aptx_encoder_cb.use_SCMS_T) {
235       framing_params->aptx_bytes = 624;
236       framing_params->pcm_bytes_per_read = 208;
237       framing_params->pcm_reads = 12;
238     } else {
239       framing_params->aptx_bytes = 672;
240       framing_params->pcm_bytes_per_read = 224;
241       framing_params->pcm_reads = 12;
242     }
243   } else {
244     // Assume the sample rate is 44100
245     if (a2dp_aptx_encoder_cb.use_SCMS_T) {
246       if (++framing_params->frame_size_counter < 20) {
247         framing_params->aptx_bytes = 616;
248         framing_params->pcm_bytes_per_read = 224;
249         framing_params->pcm_reads = 11;
250       } else {
251         framing_params->aptx_bytes = 644;
252         framing_params->pcm_bytes_per_read = 368;
253         framing_params->pcm_reads = 7;
254         framing_params->frame_size_counter = 0;
255       }
256     } else {
257       if (++framing_params->frame_size_counter < 8) {
258         framing_params->aptx_bytes = 660;
259         framing_params->pcm_bytes_per_read = 240;
260         framing_params->pcm_reads = 11;
261       } else {
262         framing_params->aptx_bytes = 672;
263         framing_params->pcm_bytes_per_read = 224;
264         framing_params->pcm_reads = 12;
265         framing_params->frame_size_counter = 0;
266       }
267     }
268   }
269 
270   log::verbose(
271           "sleep_time_ns={} aptx_bytes={} pcm_bytes_per_read={} pcm_reads={} "
272           "frame_size_counter={}",
273           framing_params->sleep_time_ns, framing_params->aptx_bytes,
274           framing_params->pcm_bytes_per_read, framing_params->pcm_reads,
275           framing_params->frame_size_counter);
276 }
277 
a2dp_vendor_aptx_feeding_reset(void)278 void a2dp_vendor_aptx_feeding_reset(void) {
279   aptx_init_framing_params(&a2dp_aptx_encoder_cb.framing_params);
280 }
281 
a2dp_vendor_aptx_feeding_flush(void)282 void a2dp_vendor_aptx_feeding_flush(void) {
283   aptx_init_framing_params(&a2dp_aptx_encoder_cb.framing_params);
284 }
285 
a2dp_vendor_aptx_get_encoder_interval_ms(void)286 uint64_t a2dp_vendor_aptx_get_encoder_interval_ms(void) {
287   return a2dp_aptx_encoder_cb.framing_params.sleep_time_ns / (1000 * 1000);
288 }
289 
a2dp_vendor_aptx_get_effective_frame_size()290 int a2dp_vendor_aptx_get_effective_frame_size() {
291   return a2dp_aptx_encoder_cb.peer_params.peer_mtu;
292 }
293 
a2dp_vendor_aptx_send_frames(uint64_t)294 void a2dp_vendor_aptx_send_frames(uint64_t /* timestamp_us */) {
295   tAPTX_FRAMING_PARAMS* framing_params = &a2dp_aptx_encoder_cb.framing_params;
296 
297   // Prepare the packet to send
298   BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
299   p_buf->offset = A2DP_APTX_OFFSET;
300   p_buf->len = 0;
301   p_buf->layer_specific = 0;
302 
303   uint8_t* encoded_ptr = (uint8_t*)(p_buf + 1);
304   encoded_ptr += p_buf->offset;
305 
306   aptx_update_framing_params(framing_params);
307 
308   //
309   // Read the PCM data and encode it
310   //
311   uint16_t read_buffer16[A2DP_APTX_MAX_PCM_BYTES_PER_READ / sizeof(uint16_t)];
312   uint32_t expected_read_bytes = framing_params->pcm_reads * framing_params->pcm_bytes_per_read;
313   size_t encoded_ptr_index = 0;
314   size_t pcm_bytes_encoded = 0;
315   uint32_t bytes_read = 0;
316 
317   a2dp_aptx_encoder_cb.stats.media_read_total_expected_packets++;
318   a2dp_aptx_encoder_cb.stats.media_read_total_expected_reads_count++;
319   a2dp_aptx_encoder_cb.stats.media_read_total_expected_read_bytes += expected_read_bytes;
320 
321   log::verbose("PCM read of size {}", expected_read_bytes);
322   bytes_read = a2dp_aptx_encoder_cb.read_callback((uint8_t*)read_buffer16, expected_read_bytes);
323   a2dp_aptx_encoder_cb.stats.media_read_total_actual_read_bytes += bytes_read;
324   if (bytes_read < expected_read_bytes) {
325     log::warn("underflow at PCM reading: read {} bytes instead of {}", bytes_read,
326               expected_read_bytes);
327     a2dp_aptx_encoder_cb.stats.media_read_total_dropped_packets++;
328     osi_free(p_buf);
329     return;
330   }
331   a2dp_aptx_encoder_cb.stats.media_read_total_actual_reads_count++;
332 
333   for (uint32_t reads = 0, offset = 0; reads < framing_params->pcm_reads;
334        reads++, offset += (framing_params->pcm_bytes_per_read / sizeof(uint16_t))) {
335     pcm_bytes_encoded += aptx_encode_16bit(framing_params, &encoded_ptr_index,
336                                            read_buffer16 + offset, encoded_ptr);
337   }
338 
339   // Compute the number of encoded bytes
340   const int COMPRESSION_RATIO = 4;
341   size_t encoded_bytes = pcm_bytes_encoded / COMPRESSION_RATIO;
342   p_buf->len += encoded_bytes;
343   log::verbose("encoded {} PCM bytes to {}", pcm_bytes_encoded, encoded_bytes);
344 
345   // Update the RTP timestamp
346   *((uint32_t*)(p_buf + 1)) = a2dp_aptx_encoder_cb.timestamp;
347 
348   const uint8_t BYTES_PER_FRAME = 2;
349   uint32_t rtp_timestamp =
350           (pcm_bytes_encoded / a2dp_aptx_encoder_cb.feeding_params.channel_count) / BYTES_PER_FRAME;
351 
352   // Timestamp will wrap over to 0 if stream continues on long enough
353   // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that
354   // no unsigned overflow is triggered as ubsan is always enabled.
355   a2dp_aptx_encoder_cb.timestamp =
356           ((uint64_t)a2dp_aptx_encoder_cb.timestamp + rtp_timestamp) & UINT32_MAX;
357 
358   if (p_buf->len > 0) {
359     a2dp_aptx_encoder_cb.enqueue_callback(p_buf, 1, bytes_read);
360   } else {
361     a2dp_aptx_encoder_cb.stats.media_read_total_dropped_packets++;
362     osi_free(p_buf);
363   }
364 }
365 
aptx_encode_16bit(tAPTX_FRAMING_PARAMS * framing_params,size_t * data_out_index,uint16_t * data16_in,uint8_t * data_out)366 static size_t aptx_encode_16bit(tAPTX_FRAMING_PARAMS* framing_params, size_t* data_out_index,
367                                 uint16_t* data16_in, uint8_t* data_out) {
368   size_t pcm_bytes_encoded = 0;
369   size_t frame = 0;
370 
371   for (size_t aptx_samples = 0; aptx_samples < framing_params->pcm_bytes_per_read / 16;
372        aptx_samples++) {
373     uint32_t pcmL[4];
374     uint32_t pcmR[4];
375     uint16_t encoded_sample[2];
376 
377     for (size_t i = 0, j = frame; i < 4; i++, j++) {
378       pcmL[i] = (uint16_t)*(data16_in + (2 * j));
379       pcmR[i] = (uint16_t)*(data16_in + ((2 * j) + 1));
380     }
381 
382     aptx_api.encode_stereo_func(a2dp_aptx_encoder_cb.aptx_encoder_state, &pcmL, &pcmR,
383                                 &encoded_sample);
384 
385     data_out[*data_out_index + 0] = (uint8_t)((encoded_sample[0] >> 8) & 0xff);
386     data_out[*data_out_index + 1] = (uint8_t)((encoded_sample[0] >> 0) & 0xff);
387     data_out[*data_out_index + 2] = (uint8_t)((encoded_sample[1] >> 8) & 0xff);
388     data_out[*data_out_index + 3] = (uint8_t)((encoded_sample[1] >> 0) & 0xff);
389 
390     frame += 4;
391     pcm_bytes_encoded += 16;
392     *data_out_index += 4;
393   }
394 
395   return pcm_bytes_encoded;
396 }
397 
debug_codec_dump(int fd)398 void A2dpCodecConfigAptx::debug_codec_dump(int fd) {
399   a2dp_aptx_encoder_stats_t* stats = &a2dp_aptx_encoder_cb.stats;
400 
401   A2dpCodecConfig::debug_codec_dump(fd);
402 
403   dprintf(fd, "  Encoder interval (ms): %" PRIu64 "\n", a2dp_vendor_aptx_get_encoder_interval_ms());
404   dprintf(fd, "  Effective MTU: %d\n", a2dp_vendor_aptx_get_effective_frame_size());
405   dprintf(fd,
406           "  Packet counts (expected/dropped)                        : %zu / "
407           "%zu\n",
408           stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets);
409 
410   dprintf(fd,
411           "  PCM read counts (expected/actual)                       : %zu / "
412           "%zu\n",
413           stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count);
414 
415   dprintf(fd,
416           "  PCM read bytes (expected/actual)                        : %zu / "
417           "%zu\n",
418           stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes);
419 }
420