1 /*
2 * Copyright 2023 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 <bluetooth/log.h>
20 #include <inttypes.h>
21 #include <string.h>
22
23 #include <string>
24
25 #include "a2dp_aac.h"
26 #include "a2dp_aac_encoder.h"
27 #include "common/time_util.h"
28 #include "internal_include/bt_target.h"
29 #include "mmc/codec_client/codec_client.h"
30 #include "mmc/proto/mmc_config.pb.h"
31 #include "os/rand.h"
32 #include "osi/include/allocator.h"
33 #include "stack/include/bt_hdr.h"
34
35 const int A2DP_AAC_HEADER_LEN = 9;
36 const int A2DP_AAC_MAX_LEN_REPR = 4;
37 const int A2DP_AAC_MAX_PREFIX_SIZE =
38 AVDT_MEDIA_HDR_SIZE + A2DP_AAC_HEADER_LEN + A2DP_AAC_MAX_LEN_REPR;
39
40 using namespace bluetooth;
41
42 class FFmpegInterface {
43 public:
44 // Updates the context and configures codec parameters.
45 //
46 // Returns:
47 // The (fixed) input pcm frame size that the encoder accepts.
48 // Otherwise a negative errno on error.
prepare_context(int sample_rate,int channel_count,int bit_rate,int bit_depth,int effective_frame_size)49 int prepare_context(int sample_rate, int channel_count, int bit_rate,
50 int bit_depth, int effective_frame_size) {
51 clear_context();
52 client = new mmc::CodecClient;
53
54 mmc::AacEncoderParam param;
55 param.set_sample_rate(sample_rate);
56 param.set_channel_count(channel_count);
57 param.set_bit_rate(bit_rate);
58 param.set_bit_depth(bit_depth);
59 param.set_effective_frame_size(effective_frame_size);
60
61 mmc::ConfigParam config;
62 *config.mutable_a2dp_aac_encoder_param() = param;
63
64 int rc = client->init(config);
65 if (rc < 0) {
66 log::error("Init failed with error message, {}", strerror(-rc));
67 }
68 return rc;
69 }
70
clear_context()71 void clear_context() {
72 if (client) {
73 client->cleanup();
74 delete client;
75 client = nullptr;
76 }
77 }
78
79 // Returns a negative errno if the encoded frame was not produced.
80 // Otherwise returns the length of the encoded frame stored in `o_buf`.
encode_pcm(uint8_t * i_buf,int i_len,uint8_t * o_buf,int o_len)81 int encode_pcm(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) {
82 if (i_buf == nullptr || o_buf == nullptr) {
83 log::error("Buffer is null");
84 return -EINVAL;
85 }
86
87 if (!client) {
88 log::error("CodecClient does not init");
89 return -ENOENT;
90 }
91
92 int rc = client->transcode(i_buf, i_len, o_buf, o_len);
93
94 if (rc < 0) {
95 log::error("Encode failed with error message, {}", strerror(-rc));
96 }
97 return rc;
98 }
99
100 private:
101 mmc::CodecClient* client = nullptr;
102 };
103
104 typedef struct {
105 float counter;
106 uint32_t bytes_per_tick; /* pcm bytes read for each media task tick */
107 uint64_t last_frame_us;
108 } tA2DP_AAC_FEEDING_STATE;
109
110 typedef struct {
111 uint64_t session_start_us;
112 size_t media_read_total_expected_packets;
113 size_t media_read_total_expected_reads_count;
114 size_t media_read_total_expected_read_bytes;
115 size_t media_read_total_dropped_packets;
116 size_t media_read_total_actual_reads_count;
117 size_t media_read_total_actual_read_bytes;
118 } a2dp_aac_encoder_stats_t;
119
120 typedef struct {
121 a2dp_source_read_callback_t read_callback;
122 a2dp_source_enqueue_callback_t enqueue_callback;
123 tA2DP_ENCODER_INIT_PEER_PARAMS peer_params;
124 tA2DP_FEEDING_PARAMS feeding_params;
125 tA2DP_AAC_FEEDING_STATE aac_feeding_state;
126 uint16_t TxAaMtuSize;
127 uint32_t timestamp; // Timestamp embedded into the BT frames
128 uint32_t pcm_samples_per_frame;
129 uint32_t encoder_interval_ms;
130 a2dp_aac_encoder_stats_t stats;
131 } tA2DP_AAC_ENCODER_CB;
132
133 static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations,
134 uint8_t* num_of_frames,
135 uint64_t timestamp_us);
136 static void a2dp_aac_encode_frames(uint8_t nb_frame);
137 static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read);
138 static uint16_t adjust_effective_mtu(
139 const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params);
140
141 namespace {
142 tA2DP_AAC_ENCODER_CB a2dp_aac_encoder_cb;
143 FFmpegInterface codec_intf;
144 } // namespace
145
A2DP_LoadEncoderAac()146 bool A2DP_LoadEncoderAac() { return true; }
147
A2DP_UnloadEncoderAac(void)148 void A2DP_UnloadEncoderAac(void) {
149 codec_intf.clear_context();
150 a2dp_aac_encoder_cb = tA2DP_AAC_ENCODER_CB{};
151 }
152
a2dp_aac_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)153 void a2dp_aac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
154 A2dpCodecConfig* a2dp_codec_config,
155 a2dp_source_read_callback_t read_callback,
156 a2dp_source_enqueue_callback_t enqueue_callback) {
157 uint8_t codec_info[AVDT_CODEC_SIZE];
158 if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
159 log::error("Cannot update the codec encoder for {}: invalid codec config",
160 a2dp_codec_config->name());
161 return;
162 }
163
164 uint16_t mtu = adjust_effective_mtu(*p_peer_params);
165
166 int max_bit_rate =
167 A2DP_ComputeMaxBitRateAac(codec_info, mtu - A2DP_AAC_MAX_PREFIX_SIZE) /
168 8 * 8;
169 int bit_rate = std::min(A2DP_GetBitRateAac(codec_info) / 8 * 8, max_bit_rate);
170
171 tA2DP_SAMPLE_RATE sample_rate = A2DP_GetTrackSampleRateAac(codec_info);
172 tA2DP_CHANNEL_COUNT channel_count = A2DP_GetTrackChannelCountAac(codec_info);
173 tA2DP_BITS_PER_SAMPLE bits_per_sample =
174 a2dp_codec_config->getAudioBitsPerSample();
175
176 int pcm_samples_per_frame = codec_intf.prepare_context(
177 sample_rate, channel_count, bit_rate, bits_per_sample, mtu);
178
179 if (pcm_samples_per_frame < 0) {
180 log::error("Failed to prepare context: {}", pcm_samples_per_frame);
181 codec_intf.clear_context();
182 return; // TODO(b/294165759): need to return an error
183 }
184
185 uint32_t encoder_interval_ms = pcm_samples_per_frame * 1000 / sample_rate;
186
187 a2dp_aac_encoder_cb = tA2DP_AAC_ENCODER_CB{
188 .read_callback = read_callback,
189 .enqueue_callback = enqueue_callback,
190 .TxAaMtuSize = mtu,
191 .peer_params = *p_peer_params,
192 .timestamp = bluetooth::os::GenerateRandom(), // (RFC 6416)
193 .feeding_params =
194 {
195 .sample_rate = sample_rate,
196 .bits_per_sample = bits_per_sample,
197 .channel_count = channel_count,
198 },
199 .aac_feeding_state =
200 tA2DP_AAC_FEEDING_STATE{
201 .bytes_per_tick = (sample_rate * bits_per_sample / 8 *
202 channel_count * encoder_interval_ms) /
203 1000,
204 },
205 .pcm_samples_per_frame = static_cast<uint32_t>(pcm_samples_per_frame),
206 .encoder_interval_ms = encoder_interval_ms,
207 .stats =
208 a2dp_aac_encoder_stats_t{
209 .session_start_us = bluetooth::common::time_get_os_boottime_us(),
210 },
211 };
212 }
213
a2dp_aac_encoder_cleanup()214 void a2dp_aac_encoder_cleanup() {
215 codec_intf.clear_context();
216 a2dp_aac_encoder_cb = tA2DP_AAC_ENCODER_CB{};
217 }
218
a2dp_aac_feeding_reset()219 void a2dp_aac_feeding_reset() {
220 auto frame_length = a2dp_aac_encoder_cb.pcm_samples_per_frame;
221 auto sample_rate = a2dp_aac_encoder_cb.feeding_params.sample_rate;
222 if (sample_rate == 0) {
223 log::warn("Sample rate is not configured");
224 return;
225 }
226
227 a2dp_aac_encoder_cb.encoder_interval_ms = frame_length * 1000 / sample_rate;
228
229 a2dp_aac_encoder_cb.aac_feeding_state = tA2DP_AAC_FEEDING_STATE{
230 .bytes_per_tick = (a2dp_aac_encoder_cb.feeding_params.sample_rate *
231 a2dp_aac_encoder_cb.feeding_params.bits_per_sample /
232 8 * a2dp_aac_encoder_cb.feeding_params.channel_count *
233 a2dp_aac_encoder_cb.encoder_interval_ms) /
234 1000,
235 };
236
237 log::warn("PCM bytes {} per tick ({}ms)",
238 a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick,
239 a2dp_aac_encoder_cb.encoder_interval_ms);
240 }
241
a2dp_aac_feeding_flush()242 void a2dp_aac_feeding_flush() {
243 a2dp_aac_encoder_cb.aac_feeding_state.counter = 0.0f;
244 }
245
a2dp_aac_get_encoder_interval_ms()246 uint64_t a2dp_aac_get_encoder_interval_ms() {
247 return a2dp_aac_encoder_cb.encoder_interval_ms;
248 }
249
a2dp_aac_get_effective_frame_size()250 int a2dp_aac_get_effective_frame_size() {
251 return a2dp_aac_encoder_cb.TxAaMtuSize;
252 }
253
a2dp_aac_send_frames(uint64_t timestamp_us)254 void a2dp_aac_send_frames(uint64_t timestamp_us) {
255 uint8_t nb_frame = 0;
256 uint8_t nb_iterations = 0;
257
258 a2dp_aac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
259 if (nb_frame == 0) return;
260
261 for (uint8_t counter = 0; counter < nb_iterations; counter++) {
262 a2dp_aac_encode_frames(nb_frame);
263 }
264 }
265
266 // Obtains the number of frames to send and number of iterations
267 // to be used. |num_of_iterations| and |num_of_frames| parameters
268 // are used as output param for returning the respective values.
a2dp_aac_get_num_frame_iteration(uint8_t * num_of_iterations,uint8_t * num_of_frames,uint64_t timestamp_us)269 static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations,
270 uint8_t* num_of_frames,
271 uint64_t timestamp_us) {
272 uint32_t result = 0;
273 uint8_t nof = 0;
274 uint8_t noi = 1;
275
276 uint32_t pcm_bytes_per_frame =
277 a2dp_aac_encoder_cb.pcm_samples_per_frame *
278 a2dp_aac_encoder_cb.feeding_params.channel_count *
279 a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
280 log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame);
281
282 uint32_t us_this_tick = a2dp_aac_encoder_cb.encoder_interval_ms * 1000;
283 uint64_t now_us = timestamp_us;
284 if (a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us != 0)
285 us_this_tick =
286 (now_us - a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us);
287 a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us = now_us;
288
289 a2dp_aac_encoder_cb.aac_feeding_state.counter +=
290 (float)a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick *
291 us_this_tick / (a2dp_aac_encoder_cb.encoder_interval_ms * 1000);
292
293 result = a2dp_aac_encoder_cb.aac_feeding_state.counter / pcm_bytes_per_frame;
294 a2dp_aac_encoder_cb.aac_feeding_state.counter -= result * pcm_bytes_per_frame;
295 nof = result;
296
297 log::verbose("effective num of frames {}, iterations {}", nof, noi);
298
299 *num_of_frames = nof;
300 *num_of_iterations = noi;
301 }
302
a2dp_aac_encode_frames(uint8_t nb_frame)303 static void a2dp_aac_encode_frames(uint8_t nb_frame) {
304 uint8_t read_buffer[BT_DEFAULT_BUFFER_SIZE];
305 int pcm_bytes_per_frame = a2dp_aac_encoder_cb.pcm_samples_per_frame *
306 a2dp_aac_encoder_cb.feeding_params.channel_count *
307 a2dp_aac_encoder_cb.feeding_params.bits_per_sample /
308 8;
309 log::assert_that(pcm_bytes_per_frame <= static_cast<int>(sizeof(read_buffer)),
310 "assert failed: pcm_bytes_per_frame <= "
311 "static_cast<int>(sizeof(read_buffer))");
312
313 while (nb_frame) {
314 a2dp_aac_encoder_cb.stats.media_read_total_expected_packets++;
315
316 uint32_t bytes_read = 0;
317 if (!a2dp_aac_read_feeding(read_buffer, &bytes_read)) {
318 log::warn("Underflow {}", nb_frame);
319 a2dp_aac_encoder_cb.aac_feeding_state.counter +=
320 nb_frame * a2dp_aac_encoder_cb.pcm_samples_per_frame *
321 a2dp_aac_encoder_cb.feeding_params.channel_count *
322 a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
323 return;
324 }
325
326 BT_HDR* p_buf = (BT_HDR*)osi_calloc(BT_DEFAULT_BUFFER_SIZE);
327 p_buf->offset = AVDT_MEDIA_OFFSET;
328 p_buf->len = 0;
329 p_buf->layer_specific = 0;
330
331 int written = codec_intf.encode_pcm(
332 read_buffer, bytes_read, (uint8_t*)(p_buf + 1) + p_buf->offset,
333 BT_DEFAULT_BUFFER_SIZE - 1 - p_buf->offset);
334
335 if (written < 0) {
336 a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
337 osi_free(p_buf);
338 return;
339 }
340
341 if (written == 0) {
342 log::info("Dropped a frame, likely due to buffering");
343 a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
344 osi_free(p_buf);
345 continue;
346 }
347
348 p_buf->layer_specific++;
349 p_buf->len += written;
350 --nb_frame;
351
352 *((uint32_t*)(p_buf + 1)) = a2dp_aac_encoder_cb.timestamp;
353
354 a2dp_aac_encoder_cb.timestamp +=
355 p_buf->layer_specific * a2dp_aac_encoder_cb.pcm_samples_per_frame;
356
357 if (!a2dp_aac_encoder_cb.enqueue_callback(p_buf, 1, bytes_read)) return;
358 }
359 }
360
a2dp_aac_read_feeding(uint8_t * read_buffer,uint32_t * bytes_read)361 static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) {
362 uint32_t read_size = a2dp_aac_encoder_cb.pcm_samples_per_frame *
363 a2dp_aac_encoder_cb.feeding_params.channel_count *
364 a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
365
366 a2dp_aac_encoder_cb.stats.media_read_total_expected_reads_count++;
367 a2dp_aac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
368
369 /* Read Data from UIPC channel */
370 uint32_t nb_byte_read =
371 a2dp_aac_encoder_cb.read_callback(read_buffer, read_size);
372 a2dp_aac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
373 *bytes_read = nb_byte_read;
374
375 if (nb_byte_read < read_size) {
376 if (nb_byte_read == 0) return false;
377
378 /* Fill the unfilled part of the read buffer with silence (0) */
379 std::fill_n((uint8_t*)read_buffer + nb_byte_read, read_size - nb_byte_read,
380 0x00);
381 nb_byte_read = read_size;
382 }
383 a2dp_aac_encoder_cb.stats.media_read_total_actual_reads_count++;
384
385 return true;
386 }
387
adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS & peer_params)388 static uint16_t adjust_effective_mtu(
389 const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) {
390 uint16_t mtu_size =
391 BT_DEFAULT_BUFFER_SIZE - AVDT_MEDIA_OFFSET - sizeof(BT_HDR);
392 if (mtu_size > peer_params.peer_mtu) {
393 mtu_size = peer_params.peer_mtu;
394 }
395 log::verbose("original AVDTP MTU size: {}", mtu_size);
396 if (peer_params.is_peer_edr && !peer_params.peer_supports_3mbps) {
397 // This condition would be satisfied only if the remote device is
398 // EDR and supports only 2 Mbps, but the effective AVDTP MTU size
399 // exceeds the 2DH5 packet size.
400 log::verbose("The remote device is EDR but does not support 3 Mbps");
401 if (mtu_size > MAX_2MBPS_AVDTP_MTU) {
402 log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size,
403 MAX_2MBPS_AVDTP_MTU);
404 mtu_size = MAX_2MBPS_AVDTP_MTU;
405 }
406 }
407 return mtu_size;
408 }
409
debug_codec_dump(int fd)410 void A2dpCodecConfigAacSource::debug_codec_dump(int fd) {
411 a2dp_aac_encoder_stats_t* stats = &a2dp_aac_encoder_cb.stats;
412
413 A2dpCodecConfig::debug_codec_dump(fd);
414
415 auto codec_specific_1 = getCodecConfig().codec_specific_1;
416 dprintf(
417 fd,
418 " AAC bitrate mode : %s "
419 "(0x%" PRIx64 ")\n",
420 ((codec_specific_1 & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK) == 0 ? "Constant"
421 : "Variable"),
422 codec_specific_1);
423 dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n",
424 a2dp_aac_get_encoder_interval_ms());
425 dprintf(fd, " Effective MTU: %d\n", a2dp_aac_get_effective_frame_size());
426 dprintf(fd,
427 " Packet counts (expected/dropped) : %zu / "
428 "%zu\n",
429 stats->media_read_total_expected_packets,
430 stats->media_read_total_dropped_packets);
431
432 dprintf(fd,
433 " PCM read counts (expected/actual) : %zu / "
434 "%zu\n",
435 stats->media_read_total_expected_reads_count,
436 stats->media_read_total_actual_reads_count);
437
438 dprintf(fd,
439 " PCM read bytes (expected/actual) : %zu / "
440 "%zu\n",
441 stats->media_read_total_expected_read_bytes,
442 stats->media_read_total_actual_read_bytes);
443 }
444