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