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_aac_encoder"
18
19 #include "a2dp_aac_encoder.h"
20
21 #include <inttypes.h>
22 #include <stdio.h>
23 #include <string.h>
24
25 #include <aacenc_lib.h>
26 #include <base/logging.h>
27
28 #include "a2dp_aac.h"
29 #include "bt_common.h"
30 #include "common/time_util.h"
31 #include "osi/include/log.h"
32 #include "osi/include/osi.h"
33
34 //
35 // Encoder for AAC Source Codec
36 //
37
38 // A2DP AAC encoder interval in milliseconds
39 #define A2DP_AAC_ENCODER_INTERVAL_MS 20
40
41 // offset
42 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
43 #define A2DP_AAC_OFFSET (AVDT_MEDIA_OFFSET + 1)
44 #else
45 #define A2DP_AAC_OFFSET AVDT_MEDIA_OFFSET
46 #endif
47
48 typedef struct {
49 uint32_t sample_rate;
50 uint8_t channel_mode;
51 uint8_t bits_per_sample;
52 uint32_t frame_length; // Samples per channel in a frame
53 uint8_t input_channels_n; // Number of channels
54 int max_encoded_buffer_bytes; // Max encoded bytes per frame
55 } tA2DP_AAC_ENCODER_PARAMS;
56
57 typedef struct {
58 uint32_t counter;
59 uint32_t bytes_per_tick; /* pcm bytes read each media task tick */
60 uint64_t last_frame_us;
61 } tA2DP_AAC_FEEDING_STATE;
62
63 typedef struct {
64 uint64_t session_start_us;
65
66 size_t media_read_total_expected_packets;
67 size_t media_read_total_expected_reads_count;
68 size_t media_read_total_expected_read_bytes;
69
70 size_t media_read_total_dropped_packets;
71 size_t media_read_total_actual_reads_count;
72 size_t media_read_total_actual_read_bytes;
73 } a2dp_aac_encoder_stats_t;
74
75 typedef struct {
76 a2dp_source_read_callback_t read_callback;
77 a2dp_source_enqueue_callback_t enqueue_callback;
78 uint16_t TxAaMtuSize;
79
80 bool use_SCMS_T;
81 bool is_peer_edr; // True if the peer device supports EDR
82 bool peer_supports_3mbps; // True if the peer device supports 3Mbps EDR
83 uint16_t peer_mtu; // MTU of the A2DP peer
84 uint32_t timestamp; // Timestamp for the A2DP frames
85
86 HANDLE_AACENCODER aac_handle;
87 bool has_aac_handle; // True if aac_handle is valid
88
89 tA2DP_FEEDING_PARAMS feeding_params;
90 tA2DP_AAC_ENCODER_PARAMS aac_encoder_params;
91 tA2DP_AAC_FEEDING_STATE aac_feeding_state;
92
93 a2dp_aac_encoder_stats_t stats;
94 } tA2DP_AAC_ENCODER_CB;
95
96 static tA2DP_AAC_ENCODER_CB a2dp_aac_encoder_cb;
97
98 static void a2dp_aac_encoder_update(uint16_t peer_mtu,
99 A2dpCodecConfig* a2dp_codec_config,
100 bool* p_restart_input,
101 bool* p_restart_output,
102 bool* p_config_updated);
103 static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations,
104 uint8_t* num_of_frames,
105 uint64_t timestamp_us);
106 static void a2dp_aac_encode_frames(uint8_t nb_frame);
107 static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read);
108
A2DP_LoadEncoderAac(void)109 bool A2DP_LoadEncoderAac(void) {
110 // Nothing to do - the library is statically linked
111 return true;
112 }
113
A2DP_UnloadEncoderAac(void)114 void A2DP_UnloadEncoderAac(void) {
115 // Nothing to do - the library is statically linked
116 if (a2dp_aac_encoder_cb.has_aac_handle)
117 aacEncClose(&a2dp_aac_encoder_cb.aac_handle);
118 memset(&a2dp_aac_encoder_cb, 0, sizeof(a2dp_aac_encoder_cb));
119 }
120
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)121 void a2dp_aac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
122 A2dpCodecConfig* a2dp_codec_config,
123 a2dp_source_read_callback_t read_callback,
124 a2dp_source_enqueue_callback_t enqueue_callback) {
125 if (a2dp_aac_encoder_cb.has_aac_handle)
126 aacEncClose(&a2dp_aac_encoder_cb.aac_handle);
127 memset(&a2dp_aac_encoder_cb, 0, sizeof(a2dp_aac_encoder_cb));
128
129 a2dp_aac_encoder_cb.stats.session_start_us =
130 bluetooth::common::time_get_os_boottime_us();
131
132 a2dp_aac_encoder_cb.read_callback = read_callback;
133 a2dp_aac_encoder_cb.enqueue_callback = enqueue_callback;
134 a2dp_aac_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
135 a2dp_aac_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
136 a2dp_aac_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
137 a2dp_aac_encoder_cb.timestamp = 0;
138
139 a2dp_aac_encoder_cb.use_SCMS_T = false; // TODO: should be a parameter
140 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
141 a2dp_aac_encoder_cb.use_SCMS_T = true;
142 #endif
143
144 // NOTE: Ignore the restart_input / restart_output flags - this initization
145 // happens when the connection is (re)started.
146 bool restart_input = false;
147 bool restart_output = false;
148 bool config_updated = false;
149 a2dp_aac_encoder_update(a2dp_aac_encoder_cb.peer_mtu, a2dp_codec_config,
150 &restart_input, &restart_output, &config_updated);
151 }
152
updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS * p_peer_params,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)153 bool A2dpCodecConfigAacSource::updateEncoderUserConfig(
154 const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input,
155 bool* p_restart_output, bool* p_config_updated) {
156 a2dp_aac_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
157 a2dp_aac_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
158 a2dp_aac_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
159 a2dp_aac_encoder_cb.timestamp = 0;
160
161 if (a2dp_aac_encoder_cb.peer_mtu == 0) {
162 LOG_ERROR(LOG_TAG,
163 "%s: Cannot update the codec encoder for %s: "
164 "invalid peer MTU",
165 __func__, name().c_str());
166 return false;
167 }
168
169 a2dp_aac_encoder_update(a2dp_aac_encoder_cb.peer_mtu, this, p_restart_input,
170 p_restart_output, p_config_updated);
171 return true;
172 }
173
174 // Update the A2DP AAC encoder.
175 // |peer_mtu| is the peer MTU.
176 // |a2dp_codec_config| is the A2DP codec to use for the update.
a2dp_aac_encoder_update(uint16_t peer_mtu,A2dpCodecConfig * a2dp_codec_config,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)177 static void a2dp_aac_encoder_update(uint16_t peer_mtu,
178 A2dpCodecConfig* a2dp_codec_config,
179 bool* p_restart_input,
180 bool* p_restart_output,
181 bool* p_config_updated) {
182 tA2DP_AAC_ENCODER_PARAMS* p_encoder_params =
183 &a2dp_aac_encoder_cb.aac_encoder_params;
184 uint8_t codec_info[AVDT_CODEC_SIZE];
185 AACENC_ERROR aac_error;
186 int aac_param_value, aac_sampling_freq, aac_peak_bit_rate;
187
188 *p_restart_input = false;
189 *p_restart_output = false;
190 *p_config_updated = false;
191
192 if (!a2dp_aac_encoder_cb.has_aac_handle) {
193 AACENC_ERROR aac_error = aacEncOpen(&a2dp_aac_encoder_cb.aac_handle, 0,
194 2 /* max 2 channels: stereo */);
195 if (aac_error != AACENC_OK) {
196 LOG_ERROR(LOG_TAG, "%s: Cannot open AAC encoder handle: AAC error 0x%x",
197 __func__, aac_error);
198 return; // TODO: Return an error?
199 }
200 a2dp_aac_encoder_cb.has_aac_handle = true;
201 }
202
203 if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
204 LOG_ERROR(LOG_TAG,
205 "%s: Cannot update the codec encoder for %s: "
206 "invalid codec config",
207 __func__, a2dp_codec_config->name().c_str());
208 return;
209 }
210 const uint8_t* p_codec_info = codec_info;
211
212 // The feeding parameters
213 tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aac_encoder_cb.feeding_params;
214 p_feeding_params->sample_rate = A2DP_GetTrackSampleRateAac(p_codec_info);
215 p_feeding_params->bits_per_sample =
216 a2dp_codec_config->getAudioBitsPerSample();
217 p_feeding_params->channel_count = A2DP_GetTrackChannelCountAac(p_codec_info);
218 LOG_DEBUG(LOG_TAG, "%s: sample_rate=%u bits_per_sample=%u channel_count=%u",
219 __func__, p_feeding_params->sample_rate,
220 p_feeding_params->bits_per_sample, p_feeding_params->channel_count);
221 a2dp_aac_feeding_reset();
222
223 // The codec parameters
224 p_encoder_params->sample_rate =
225 a2dp_aac_encoder_cb.feeding_params.sample_rate;
226 p_encoder_params->channel_mode = A2DP_GetChannelModeCodeAac(p_codec_info);
227
228 LOG_VERBOSE(LOG_TAG, "%s: original AVDTP MTU size: %d", __func__,
229 a2dp_aac_encoder_cb.TxAaMtuSize);
230 if (a2dp_aac_encoder_cb.is_peer_edr &&
231 !a2dp_aac_encoder_cb.peer_supports_3mbps) {
232 // This condition would be satisfied only if the remote device is
233 // EDR and supports only 2 Mbps, but the effective AVDTP MTU size
234 // exceeds the 2DH5 packet size.
235 LOG_VERBOSE(LOG_TAG,
236 "%s: The remote device is EDR but does not support 3 Mbps",
237 __func__);
238 if (peer_mtu > MAX_2MBPS_AVDTP_MTU) {
239 LOG_WARN(LOG_TAG, "%s: Restricting AVDTP MTU size from %d to %d",
240 __func__, peer_mtu, MAX_2MBPS_AVDTP_MTU);
241 peer_mtu = MAX_2MBPS_AVDTP_MTU;
242 }
243 }
244 uint16_t mtu_size = BT_DEFAULT_BUFFER_SIZE - A2DP_AAC_OFFSET - sizeof(BT_HDR);
245 if (mtu_size < peer_mtu) {
246 a2dp_aac_encoder_cb.TxAaMtuSize = mtu_size;
247 } else {
248 a2dp_aac_encoder_cb.TxAaMtuSize = peer_mtu;
249 }
250
251 LOG_DEBUG(LOG_TAG, "%s: MTU=%d, peer_mtu=%d", __func__,
252 a2dp_aac_encoder_cb.TxAaMtuSize, peer_mtu);
253 LOG_DEBUG(LOG_TAG, "%s: sample_rate: %d channel_mode: %d ", __func__,
254 p_encoder_params->sample_rate, p_encoder_params->channel_mode);
255
256 // Set the encoder's parameters: Audio Object Type - MANDATORY
257 // A2DP_AAC_OBJECT_TYPE_MPEG2_LC -> AOT_AAC_LC
258 // A2DP_AAC_OBJECT_TYPE_MPEG4_LC -> AOT_AAC_LC
259 // A2DP_AAC_OBJECT_TYPE_MPEG4_LTP -> AOT_AAC_LTP
260 // A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE -> AOT_AAC_SCAL
261 aac_param_value = AOT_AAC_LC;
262 int object_type = A2DP_GetObjectTypeCodeAac(p_codec_info);
263 switch (object_type) {
264 case A2DP_AAC_OBJECT_TYPE_MPEG2_LC:
265 aac_param_value = AOT_AAC_LC;
266 break;
267 case A2DP_AAC_OBJECT_TYPE_MPEG4_LC:
268 aac_param_value = AOT_AAC_LC;
269 break;
270 case A2DP_AAC_OBJECT_TYPE_MPEG4_LTP:
271 aac_param_value = AOT_AAC_LTP;
272 break;
273 case A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE:
274 aac_param_value = AOT_AAC_SCAL;
275 break;
276 default:
277 LOG_ERROR(LOG_TAG,
278 "%s: Cannot set AAC parameter AACENC_AOT: "
279 "invalid object type %d",
280 __func__, object_type);
281 return; // TODO: Return an error?
282 }
283 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_AOT,
284 aac_param_value);
285 if (aac_error != AACENC_OK) {
286 LOG_ERROR(LOG_TAG,
287 "%s: Cannot set AAC parameter AACENC_AOT to %d: "
288 "AAC error 0x%x",
289 __func__, aac_param_value, aac_error);
290 return; // TODO: Return an error?
291 }
292
293 // Set the encoder's parameters: audioMuxVersion
294 aac_param_value = 2; // audioMuxVersion = "2"
295 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
296 AACENC_AUDIOMUXVER, aac_param_value);
297 if (aac_error != AACENC_OK) {
298 LOG_ERROR(LOG_TAG,
299 "%s: Cannot set AAC parameter AACENC_AUDIOMUXVER to %d: "
300 "AAC error 0x%x",
301 __func__, aac_param_value, aac_error);
302 return; // TODO: Return an error?
303 }
304
305 // Set the encoder's parameters: Signaling mode of the extension AOT
306 aac_param_value = 1; // Signaling mode of the extension AOT = 1
307 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
308 AACENC_SIGNALING_MODE, aac_param_value);
309 if (aac_error != AACENC_OK) {
310 LOG_ERROR(LOG_TAG,
311 "%s: Cannot set AAC parameter AACENC_SIGNALING_MODE to %d: "
312 "AAC error 0x%x",
313 __func__, aac_param_value, aac_error);
314 return; // TODO: Return an error?
315 }
316
317 // Set the encoder's parameters: Sample Rate - MANDATORY
318 aac_param_value = A2DP_GetTrackSampleRateAac(p_codec_info);
319 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
320 AACENC_SAMPLERATE, aac_param_value);
321 if (aac_error != AACENC_OK) {
322 LOG_ERROR(LOG_TAG,
323 "%s: Cannot set AAC parameter AACENC_SAMPLERATE to %d: "
324 "AAC error 0x%x",
325 __func__, aac_param_value, aac_error);
326 return; // TODO: Return an error?
327 }
328 aac_sampling_freq = aac_param_value; // Save for extra usage below
329
330 // Set the encoder's parameters: Bit Rate - MANDATORY
331 aac_param_value = A2DP_GetBitRateAac(p_codec_info);
332 // Calculate the bit rate from MTU and sampling frequency
333 aac_peak_bit_rate =
334 A2DP_ComputeMaxBitRateAac(p_codec_info, a2dp_aac_encoder_cb.TxAaMtuSize);
335 aac_param_value = std::min(aac_param_value, aac_peak_bit_rate);
336 LOG_DEBUG(LOG_TAG, "%s: MTU = %d Sampling Frequency = %d Bit Rate = %d",
337 __func__, a2dp_aac_encoder_cb.TxAaMtuSize, aac_sampling_freq,
338 aac_param_value);
339 if (aac_param_value == -1) {
340 LOG_ERROR(LOG_TAG,
341 "%s: Cannot set AAC parameter AACENC_BITRATE: "
342 "invalid codec bit rate",
343 __func__);
344 return; // TODO: Return an error?
345 }
346 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
347 AACENC_BITRATE, aac_param_value);
348 if (aac_error != AACENC_OK) {
349 LOG_ERROR(LOG_TAG,
350 "%s: Cannot set AAC parameter AACENC_BITRATE to %d: "
351 "AAC error 0x%x",
352 __func__, aac_param_value, aac_error);
353 return; // TODO: Return an error?
354 }
355
356 // Set the encoder's parameters: PEAK Bit Rate
357 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
358 AACENC_PEAK_BITRATE, aac_peak_bit_rate);
359 if (aac_error != AACENC_OK) {
360 LOG_ERROR(LOG_TAG,
361 "%s: Cannot set AAC parameter AACENC_PEAK_BITRATE to %d: "
362 "AAC error 0x%x",
363 __func__, aac_peak_bit_rate, aac_error);
364 return; // TODO: Return an error?
365 }
366
367 // Set the encoder's parameters: Channel Mode - MANDATORY
368 if (A2DP_GetTrackChannelCountAac(p_codec_info) == 1) {
369 aac_param_value = MODE_1; // Mono
370 } else {
371 aac_param_value = MODE_2; // Stereo
372 }
373 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
374 AACENC_CHANNELMODE, aac_param_value);
375 if (aac_error != AACENC_OK) {
376 LOG_ERROR(LOG_TAG,
377 "%s: Cannot set AAC parameter AACENC_CHANNELMODE to %d: "
378 "AAC error 0x%x",
379 __func__, aac_param_value, aac_error);
380 return; // TODO: Return an error?
381 }
382
383 // Set the encoder's parameters: Transport Type
384 aac_param_value = TT_MP4_LATM_MCP1; // muxConfigPresent = 1
385 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
386 AACENC_TRANSMUX, aac_param_value);
387 if (aac_error != AACENC_OK) {
388 LOG_ERROR(LOG_TAG,
389 "%s: Cannot set AAC parameter AACENC_TRANSMUX to %d: "
390 "AAC error 0x%x",
391 __func__, aac_param_value, aac_error);
392 return; // TODO: Return an error?
393 }
394
395 // Set the encoder's parameters: Header Period
396 aac_param_value = 1;
397 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
398 AACENC_HEADER_PERIOD, aac_param_value);
399 if (aac_error != AACENC_OK) {
400 LOG_ERROR(LOG_TAG,
401 "%s: Cannot set AAC parameter AACENC_HEADER_PERIOD to %d: "
402 "AAC error 0x%x",
403 __func__, aac_param_value, aac_error);
404 return; // TODO: Return an error?
405 }
406
407 // Set the encoder's parameters: Variable Bit Rate Support
408 aac_param_value = A2DP_GetVariableBitRateSupportAac(p_codec_info);
409 if (aac_param_value == -1) {
410 LOG_ERROR(LOG_TAG,
411 "%s: Cannot set AAC parameter AACENC_BITRATEMODE: "
412 "invalid codec bit rate mode",
413 __func__);
414 return; // TODO: Return an error?
415 }
416 aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
417 AACENC_BITRATEMODE, aac_param_value);
418 if (aac_error != AACENC_OK) {
419 LOG_ERROR(LOG_TAG,
420 "%s: Cannot set AAC parameter AACENC_BITRATEMODE to %d: "
421 "AAC error 0x%x",
422 __func__, aac_param_value, aac_error);
423 return; // TODO: Return an error?
424 }
425
426 // Mark the end of setting the encoder's parameters
427 aac_error =
428 aacEncEncode(a2dp_aac_encoder_cb.aac_handle, NULL, NULL, NULL, NULL);
429 if (aac_error != AACENC_OK) {
430 LOG_ERROR(LOG_TAG,
431 "%s: Cannot complete setting the AAC parameters: AAC error 0x%x",
432 __func__, aac_error);
433 return; // TODO: Return an error?
434 }
435
436 // Retrieve the encoder info so we can save the frame length
437 AACENC_InfoStruct aac_info;
438 aac_error = aacEncInfo(a2dp_aac_encoder_cb.aac_handle, &aac_info);
439 if (aac_error != AACENC_OK) {
440 LOG_ERROR(LOG_TAG,
441 "%s: Cannot retrieve the AAC encoder info: AAC error 0x%x",
442 __func__, aac_error);
443 return; // TODO: Return an error?
444 }
445 p_encoder_params->frame_length = aac_info.frameLength;
446 p_encoder_params->input_channels_n = aac_info.inputChannels;
447 p_encoder_params->max_encoded_buffer_bytes = aac_info.maxOutBufBytes;
448 LOG_DEBUG(LOG_TAG,
449 "%s: AAC frame_length = %u input_channels_n = %u "
450 "max_encoded_buffer_bytes = %d",
451 __func__, p_encoder_params->frame_length,
452 p_encoder_params->input_channels_n,
453 p_encoder_params->max_encoded_buffer_bytes);
454 }
455
a2dp_aac_encoder_cleanup(void)456 void a2dp_aac_encoder_cleanup(void) {
457 if (a2dp_aac_encoder_cb.has_aac_handle)
458 aacEncClose(&a2dp_aac_encoder_cb.aac_handle);
459 memset(&a2dp_aac_encoder_cb, 0, sizeof(a2dp_aac_encoder_cb));
460 }
461
a2dp_aac_feeding_reset(void)462 void a2dp_aac_feeding_reset(void) {
463 /* By default, just clear the entire state */
464 memset(&a2dp_aac_encoder_cb.aac_feeding_state, 0,
465 sizeof(a2dp_aac_encoder_cb.aac_feeding_state));
466
467 a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick =
468 (a2dp_aac_encoder_cb.feeding_params.sample_rate *
469 a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8 *
470 a2dp_aac_encoder_cb.feeding_params.channel_count *
471 A2DP_AAC_ENCODER_INTERVAL_MS) /
472 1000;
473
474 LOG_DEBUG(LOG_TAG, "%s: PCM bytes per tick %u", __func__,
475 a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick);
476 }
477
a2dp_aac_feeding_flush(void)478 void a2dp_aac_feeding_flush(void) {
479 a2dp_aac_encoder_cb.aac_feeding_state.counter = 0;
480 }
481
a2dp_aac_get_encoder_interval_ms(void)482 uint64_t a2dp_aac_get_encoder_interval_ms(void) {
483 return A2DP_AAC_ENCODER_INTERVAL_MS;
484 }
485
a2dp_aac_send_frames(uint64_t timestamp_us)486 void a2dp_aac_send_frames(uint64_t timestamp_us) {
487 uint8_t nb_frame = 0;
488 uint8_t nb_iterations = 0;
489
490 a2dp_aac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
491 LOG_VERBOSE(LOG_TAG, "%s: Sending %d frames per iteration, %d iterations",
492 __func__, nb_frame, nb_iterations);
493 if (nb_frame == 0) return;
494
495 for (uint8_t counter = 0; counter < nb_iterations; counter++) {
496 // Transcode frame and enqueue
497 a2dp_aac_encode_frames(nb_frame);
498 }
499 }
500
501 // Obtains the number of frames to send and number of iterations
502 // to be used. |num_of_iterations| and |num_of_frames| parameters
503 // 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)504 static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations,
505 uint8_t* num_of_frames,
506 uint64_t timestamp_us) {
507 uint32_t result = 0;
508 uint8_t nof = 0;
509 uint8_t noi = 1;
510
511 uint32_t pcm_bytes_per_frame =
512 a2dp_aac_encoder_cb.aac_encoder_params.frame_length *
513 a2dp_aac_encoder_cb.feeding_params.channel_count *
514 a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
515 LOG_VERBOSE(LOG_TAG, "%s: pcm_bytes_per_frame %u", __func__,
516 pcm_bytes_per_frame);
517
518 uint32_t us_this_tick = A2DP_AAC_ENCODER_INTERVAL_MS * 1000;
519 uint64_t now_us = timestamp_us;
520 if (a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us != 0)
521 us_this_tick =
522 (now_us - a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us);
523 a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us = now_us;
524
525 a2dp_aac_encoder_cb.aac_feeding_state.counter +=
526 a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick * us_this_tick /
527 (A2DP_AAC_ENCODER_INTERVAL_MS * 1000);
528
529 result = a2dp_aac_encoder_cb.aac_feeding_state.counter / pcm_bytes_per_frame;
530 a2dp_aac_encoder_cb.aac_feeding_state.counter -= result * pcm_bytes_per_frame;
531 nof = result;
532
533 LOG_VERBOSE(LOG_TAG, "%s: effective num of frames %u, iterations %u",
534 __func__, nof, noi);
535
536 *num_of_frames = nof;
537 *num_of_iterations = noi;
538 }
539
a2dp_aac_encode_frames(uint8_t nb_frame)540 static void a2dp_aac_encode_frames(uint8_t nb_frame) {
541 tA2DP_AAC_ENCODER_PARAMS* p_encoder_params =
542 &a2dp_aac_encoder_cb.aac_encoder_params;
543 tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aac_encoder_cb.feeding_params;
544 uint8_t remain_nb_frame = nb_frame;
545 uint8_t read_buffer[BT_DEFAULT_BUFFER_SIZE];
546 int pcm_bytes_per_frame = p_encoder_params->frame_length *
547 p_feeding_params->channel_count *
548 p_feeding_params->bits_per_sample / 8;
549 CHECK(pcm_bytes_per_frame <= static_cast<int>(sizeof(read_buffer)));
550
551 // Setup the input buffer
552 AACENC_BufDesc in_buf_desc;
553 void* in_buf_vector[1] = {nullptr};
554 int in_buf_identifiers[1] = {IN_AUDIO_DATA};
555 int in_buf_sizes[1] = {pcm_bytes_per_frame};
556 int in_buf_element_sizes[1] = {p_feeding_params->bits_per_sample / 8};
557 in_buf_desc.numBufs = 1;
558 in_buf_desc.bufs = in_buf_vector;
559 in_buf_desc.bufferIdentifiers = in_buf_identifiers;
560 in_buf_desc.bufSizes = in_buf_sizes;
561 in_buf_desc.bufElSizes = in_buf_element_sizes;
562
563 // Setup the output buffer (partially)
564 AACENC_BufDesc out_buf_desc;
565 void* out_buf_vector[1] = {nullptr};
566 int out_buf_identifiers[1] = {OUT_BITSTREAM_DATA};
567 int out_buf_sizes[1] = {p_encoder_params->max_encoded_buffer_bytes};
568 // NOTE: out_buf_element_sizes below is probably unused by the encoder
569 int out_buf_element_sizes[1] = {p_feeding_params->bits_per_sample / 8};
570 out_buf_desc.numBufs = 1;
571 out_buf_desc.bufs = out_buf_vector;
572 out_buf_desc.bufferIdentifiers = out_buf_identifiers;
573 out_buf_desc.bufSizes = out_buf_sizes;
574 out_buf_desc.bufElSizes = out_buf_element_sizes;
575 CHECK(p_encoder_params->max_encoded_buffer_bytes <=
576 static_cast<int>(BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR)));
577
578 AACENC_InArgs aac_in_args;
579 aac_in_args.numInSamples =
580 p_encoder_params->frame_length * p_feeding_params->channel_count;
581 aac_in_args.numAncBytes = 0;
582
583 AACENC_OutArgs aac_out_args = {
584 .numOutBytes = 0, .numInSamples = 0, .numAncBytes = 0};
585
586 uint32_t count;
587 uint32_t total_bytes_read = 0;
588 int written = 0;
589
590 while (nb_frame) {
591 BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
592 p_buf->offset = A2DP_AAC_OFFSET;
593 p_buf->len = 0;
594 p_buf->layer_specific = 0;
595 a2dp_aac_encoder_cb.stats.media_read_total_expected_packets++;
596
597 count = 0;
598 do {
599 //
600 // Read the PCM data and encode it
601 //
602 uint32_t bytes_read = 0;
603 if (a2dp_aac_read_feeding(read_buffer, &bytes_read)) {
604 uint8_t* packet = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
605 if (!a2dp_aac_encoder_cb.has_aac_handle) {
606 LOG_ERROR(LOG_TAG, "%s: invalid AAC handle", __func__);
607 a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
608 osi_free(p_buf);
609 return;
610 }
611 in_buf_vector[0] = read_buffer;
612 out_buf_vector[0] = packet + count;
613 AACENC_ERROR aac_error =
614 aacEncEncode(a2dp_aac_encoder_cb.aac_handle, &in_buf_desc,
615 &out_buf_desc, &aac_in_args, &aac_out_args);
616 if (aac_error != AACENC_OK) {
617 LOG_ERROR(LOG_TAG, "%s: AAC encoding error: 0x%x", __func__,
618 aac_error);
619 a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
620 osi_free(p_buf);
621 return;
622 }
623 written = aac_out_args.numOutBytes;
624 count += written;
625 p_buf->len += written;
626 nb_frame--;
627 p_buf->layer_specific++; // added a frame to the buffer
628 } else {
629 LOG_WARN(LOG_TAG, "%s: underflow %d", __func__, nb_frame);
630 a2dp_aac_encoder_cb.aac_feeding_state.counter +=
631 nb_frame * p_encoder_params->frame_length *
632 p_feeding_params->channel_count *
633 p_feeding_params->bits_per_sample / 8;
634
635 // no more pcm to read
636 nb_frame = 0;
637 }
638 total_bytes_read += bytes_read;
639 } while ((written == 0) && nb_frame);
640
641 // NOTE: We don't check whether the packet will fit in the MTU,
642 // because AAC doesn't give us control over the encoded frame size.
643 // If the packet is larger than the MTU, it will be fragmented before
644 // transmission.
645 if (p_buf->len) {
646 /*
647 * Timestamp of the media packet header represent the TS of the
648 * first frame, i.e the timestamp before including this frame.
649 */
650 *((uint32_t*)(p_buf + 1)) = a2dp_aac_encoder_cb.timestamp;
651
652 a2dp_aac_encoder_cb.timestamp +=
653 p_buf->layer_specific * p_encoder_params->frame_length;
654
655 uint8_t done_nb_frame = remain_nb_frame - nb_frame;
656 remain_nb_frame = nb_frame;
657 if (!a2dp_aac_encoder_cb.enqueue_callback(p_buf, done_nb_frame,
658 total_bytes_read))
659 return;
660 } else {
661 a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
662 osi_free(p_buf);
663 }
664 }
665 }
666
a2dp_aac_read_feeding(uint8_t * read_buffer,uint32_t * bytes_read)667 static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) {
668 uint32_t read_size = a2dp_aac_encoder_cb.aac_encoder_params.frame_length *
669 a2dp_aac_encoder_cb.feeding_params.channel_count *
670 a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
671
672 a2dp_aac_encoder_cb.stats.media_read_total_expected_reads_count++;
673 a2dp_aac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
674
675 /* Read Data from UIPC channel */
676 uint32_t nb_byte_read =
677 a2dp_aac_encoder_cb.read_callback(read_buffer, read_size);
678 a2dp_aac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
679 *bytes_read = nb_byte_read;
680
681 if (nb_byte_read < read_size) {
682 if (nb_byte_read == 0) return false;
683
684 /* Fill the unfilled part of the read buffer with silence (0) */
685 memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
686 nb_byte_read = read_size;
687 }
688 a2dp_aac_encoder_cb.stats.media_read_total_actual_reads_count++;
689
690 return true;
691 }
692
encoderIntervalMs() const693 uint64_t A2dpCodecConfigAacSource::encoderIntervalMs() const {
694 return a2dp_aac_get_encoder_interval_ms();
695 }
696
getEffectiveMtu() const697 int A2dpCodecConfigAacSource::getEffectiveMtu() const {
698 return a2dp_aac_encoder_cb.TxAaMtuSize;
699 }
700
debug_codec_dump(int fd)701 void A2dpCodecConfigAacSource::debug_codec_dump(int fd) {
702 a2dp_aac_encoder_stats_t* stats = &a2dp_aac_encoder_cb.stats;
703
704 A2dpCodecConfig::debug_codec_dump(fd);
705
706 dprintf(fd,
707 " Packet counts (expected/dropped) : %zu / "
708 "%zu\n",
709 stats->media_read_total_expected_packets,
710 stats->media_read_total_dropped_packets);
711
712 dprintf(fd,
713 " PCM read counts (expected/actual) : %zu / "
714 "%zu\n",
715 stats->media_read_total_expected_reads_count,
716 stats->media_read_total_actual_reads_count);
717
718 dprintf(fd,
719 " PCM read bytes (expected/actual) : %zu / "
720 "%zu\n",
721 stats->media_read_total_expected_read_bytes,
722 stats->media_read_total_actual_read_bytes);
723 }
724