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