1 /*
2 * Copyright 2021 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_vendor_opus_encoder"
18
19 #include "a2dp_vendor_opus_encoder.h"
20
21 #include <dlfcn.h>
22 #include <inttypes.h>
23 #include <opus.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "a2dp_vendor.h"
28 #include "a2dp_vendor_opus.h"
29 #include "common/time_util.h"
30 #include "osi/include/allocator.h"
31 #include "osi/include/log.h"
32 #include "osi/include/osi.h"
33 #include "stack/include/bt_hdr.h"
34
35 typedef struct {
36 uint32_t sample_rate;
37 uint16_t bitrate;
38 uint16_t framesize;
39 uint8_t channel_mode;
40 uint8_t bits_per_sample;
41 uint8_t quality_mode_index;
42 int pcm_wlength;
43 uint8_t pcm_fmt;
44 } tA2DP_OPUS_ENCODER_PARAMS;
45
46 typedef struct {
47 float counter;
48 uint32_t bytes_per_tick;
49 uint64_t last_frame_us;
50 } tA2DP_OPUS_FEEDING_STATE;
51
52 typedef struct {
53 uint64_t session_start_us;
54
55 size_t media_read_total_expected_packets;
56 size_t media_read_total_expected_reads_count;
57 size_t media_read_total_expected_read_bytes;
58
59 size_t media_read_total_dropped_packets;
60 size_t media_read_total_actual_reads_count;
61 size_t media_read_total_actual_read_bytes;
62 } a2dp_opus_encoder_stats_t;
63
64 typedef struct {
65 a2dp_source_read_callback_t read_callback;
66 a2dp_source_enqueue_callback_t enqueue_callback;
67 uint16_t TxAaMtuSize;
68 size_t TxQueueLength;
69
70 bool use_SCMS_T;
71 bool is_peer_edr; // True if the peer device supports EDR
72 bool peer_supports_3mbps; // True if the peer device supports 3Mbps EDR
73 uint16_t peer_mtu; // MTU of the A2DP peer
74 uint32_t timestamp; // Timestamp for the A2DP frames
75
76 OpusEncoder* opus_handle;
77 bool has_opus_handle; // True if opus_handle is valid
78
79 tA2DP_FEEDING_PARAMS feeding_params;
80 tA2DP_OPUS_ENCODER_PARAMS opus_encoder_params;
81 tA2DP_OPUS_FEEDING_STATE opus_feeding_state;
82
83 a2dp_opus_encoder_stats_t stats;
84 } tA2DP_OPUS_ENCODER_CB;
85
86 static tA2DP_OPUS_ENCODER_CB a2dp_opus_encoder_cb;
87
88 static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu,
89 A2dpCodecConfig* a2dp_codec_config,
90 bool* p_restart_input,
91 bool* p_restart_output,
92 bool* p_config_updated);
93 static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations,
94 uint8_t* num_of_frames,
95 uint64_t timestamp_us);
96 static void a2dp_opus_encode_frames(uint8_t nb_frame);
97 static bool a2dp_opus_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read);
98
a2dp_vendor_opus_encoder_cleanup(void)99 void a2dp_vendor_opus_encoder_cleanup(void) {
100 if (a2dp_opus_encoder_cb.has_opus_handle) {
101 osi_free(a2dp_opus_encoder_cb.opus_handle);
102 a2dp_opus_encoder_cb.has_opus_handle = false;
103 a2dp_opus_encoder_cb.opus_handle = nullptr;
104 }
105 memset(&a2dp_opus_encoder_cb, 0, sizeof(a2dp_opus_encoder_cb));
106
107 a2dp_opus_encoder_cb.stats.session_start_us =
108 bluetooth::common::time_get_os_boottime_us();
109
110 a2dp_opus_encoder_cb.timestamp = 0;
111
112 #if (BTA_AV_CO_CP_SCMS_T == TRUE)
113 a2dp_opus_encoder_cb.use_SCMS_T = true;
114 #else
115 a2dp_opus_encoder_cb.use_SCMS_T = false;
116 #endif
117 return;
118 }
119
a2dp_vendor_opus_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)120 void a2dp_vendor_opus_encoder_init(
121 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 uint32_t error_val;
126
127 a2dp_vendor_opus_encoder_cleanup();
128
129 a2dp_opus_encoder_cb.read_callback = read_callback;
130 a2dp_opus_encoder_cb.enqueue_callback = enqueue_callback;
131 a2dp_opus_encoder_cb.is_peer_edr = p_peer_params->is_peer_edr;
132 a2dp_opus_encoder_cb.peer_supports_3mbps = p_peer_params->peer_supports_3mbps;
133 a2dp_opus_encoder_cb.peer_mtu = p_peer_params->peer_mtu;
134
135 // NOTE: Ignore the restart_input / restart_output flags - this initization
136 // happens when the connection is (re)started.
137 bool restart_input = false;
138 bool restart_output = false;
139 bool config_updated = false;
140
141 uint32_t size = opus_encoder_get_size(A2DP_OPUS_CODEC_OUTPUT_CHS);
142 a2dp_opus_encoder_cb.opus_handle =
143 static_cast<OpusEncoder*>(osi_malloc(size));
144 if (a2dp_opus_encoder_cb.opus_handle == nullptr) {
145 LOG_ERROR("failed to allocate opus encoder handle");
146 return;
147 }
148
149 error_val = opus_encoder_init(
150 a2dp_opus_encoder_cb.opus_handle, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE,
151 A2DP_OPUS_CODEC_OUTPUT_CHS, OPUS_APPLICATION_AUDIO);
152
153 if (error_val != OPUS_OK) {
154 LOG_ERROR(
155 "failed to init opus encoder (handle size %d, sampling rate %d, "
156 "output chs %d, error %d)",
157 size, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, A2DP_OPUS_CODEC_OUTPUT_CHS,
158 error_val);
159 osi_free(a2dp_opus_encoder_cb.opus_handle);
160 return;
161 } else {
162 a2dp_opus_encoder_cb.has_opus_handle = true;
163 }
164
165 a2dp_vendor_opus_encoder_update(a2dp_opus_encoder_cb.peer_mtu,
166 a2dp_codec_config, &restart_input,
167 &restart_output, &config_updated);
168
169 return;
170 }
171
updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS * p_peer_params,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)172 bool A2dpCodecConfigOpusSource::updateEncoderUserConfig(
173 const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input,
174 bool* p_restart_output, bool* p_config_updated) {
175 if (a2dp_opus_encoder_cb.peer_mtu == 0) {
176 LOG_ERROR(
177 "Cannot update the codec encoder for %s: "
178 "invalid peer MTU",
179 name().c_str());
180 return false;
181 }
182
183 return a2dp_vendor_opus_encoder_update(a2dp_opus_encoder_cb.peer_mtu, this,
184 p_restart_input, p_restart_output,
185 p_config_updated);
186 }
187
a2dp_vendor_opus_encoder_update(uint16_t peer_mtu,A2dpCodecConfig * a2dp_codec_config,bool * p_restart_input,bool * p_restart_output,bool * p_config_updated)188 static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu,
189 A2dpCodecConfig* a2dp_codec_config,
190 bool* p_restart_input,
191 bool* p_restart_output,
192 bool* p_config_updated) {
193 tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params =
194 &a2dp_opus_encoder_cb.opus_encoder_params;
195 uint8_t codec_info[AVDT_CODEC_SIZE];
196 uint32_t error = 0;
197
198 *p_restart_input = false;
199 *p_restart_output = false;
200 *p_config_updated = false;
201
202 if (!a2dp_opus_encoder_cb.has_opus_handle ||
203 a2dp_opus_encoder_cb.opus_handle == NULL) {
204 LOG_ERROR("Cannot get Opus encoder handle");
205 return false;
206 }
207 CHECK(a2dp_opus_encoder_cb.opus_handle != nullptr);
208
209 if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
210 LOG_ERROR(
211 "Cannot update the codec encoder for %s: "
212 "invalid codec config",
213 a2dp_codec_config->name().c_str());
214 return false;
215 }
216 const uint8_t* p_codec_info = codec_info;
217 btav_a2dp_codec_config_t codec_config = a2dp_codec_config->getCodecConfig();
218
219 // The feeding parameters
220 tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_opus_encoder_cb.feeding_params;
221 p_feeding_params->sample_rate =
222 A2DP_VendorGetTrackSampleRateOpus(p_codec_info);
223 p_feeding_params->bits_per_sample =
224 a2dp_codec_config->getAudioBitsPerSample();
225 p_feeding_params->channel_count =
226 A2DP_VendorGetTrackChannelCountOpus(p_codec_info);
227 LOG_INFO("sample_rate=%u bits_per_sample=%u channel_count=%u",
228 p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
229 p_feeding_params->channel_count);
230
231 // The codec parameters
232 p_encoder_params->sample_rate =
233 a2dp_opus_encoder_cb.feeding_params.sample_rate;
234 p_encoder_params->channel_mode =
235 A2DP_VendorGetChannelModeCodeOpus(p_codec_info);
236 p_encoder_params->framesize = A2DP_VendorGetFrameSizeOpus(p_codec_info);
237 p_encoder_params->bitrate = A2DP_VendorGetBitRateOpus(p_codec_info);
238
239 a2dp_vendor_opus_feeding_reset();
240
241 uint16_t mtu_size =
242 BT_DEFAULT_BUFFER_SIZE - A2DP_OPUS_OFFSET - sizeof(BT_HDR);
243 if (mtu_size < peer_mtu) {
244 a2dp_opus_encoder_cb.TxAaMtuSize = mtu_size;
245 } else {
246 a2dp_opus_encoder_cb.TxAaMtuSize = peer_mtu;
247 }
248
249 // Set the bitrate quality mode index
250 if (codec_config.codec_specific_3 != 0) {
251 p_encoder_params->quality_mode_index = codec_config.codec_specific_3 % 10;
252 LOG_INFO("setting bitrate quality mode to %d",
253 p_encoder_params->quality_mode_index);
254 } else {
255 p_encoder_params->quality_mode_index = 5;
256 LOG_INFO("setting bitrate quality mode to default %d",
257 p_encoder_params->quality_mode_index);
258 }
259
260 error = opus_encoder_ctl(
261 a2dp_opus_encoder_cb.opus_handle,
262 OPUS_SET_COMPLEXITY(p_encoder_params->quality_mode_index));
263
264 if (error != OPUS_OK) {
265 LOG_ERROR("failed to set encoder bitrate quality setting");
266 return false;
267 }
268
269 p_encoder_params->pcm_wlength =
270 a2dp_opus_encoder_cb.feeding_params.bits_per_sample >> 3;
271
272 LOG_INFO("setting bitrate to %d", p_encoder_params->bitrate);
273 error = opus_encoder_ctl(a2dp_opus_encoder_cb.opus_handle,
274 OPUS_SET_BITRATE(p_encoder_params->bitrate));
275
276 if (error != OPUS_OK) {
277 LOG_ERROR("failed to set encoder bitrate");
278 return false;
279 }
280
281 // Set the Audio format from pcm_wlength
282 if (p_encoder_params->pcm_wlength == 2)
283 p_encoder_params->pcm_fmt = 16;
284 else if (p_encoder_params->pcm_wlength == 3)
285 p_encoder_params->pcm_fmt = 24;
286 else if (p_encoder_params->pcm_wlength == 4)
287 p_encoder_params->pcm_fmt = 32;
288
289 return true;
290 }
291
a2dp_vendor_opus_feeding_reset(void)292 void a2dp_vendor_opus_feeding_reset(void) {
293 memset(&a2dp_opus_encoder_cb.opus_feeding_state, 0,
294 sizeof(a2dp_opus_encoder_cb.opus_feeding_state));
295
296 a2dp_opus_encoder_cb.opus_feeding_state.bytes_per_tick =
297 (a2dp_opus_encoder_cb.feeding_params.sample_rate *
298 a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8 *
299 a2dp_opus_encoder_cb.feeding_params.channel_count *
300 a2dp_vendor_opus_get_encoder_interval_ms()) /
301 1000;
302
303 return;
304 }
305
a2dp_vendor_opus_feeding_flush(void)306 void a2dp_vendor_opus_feeding_flush(void) {
307 a2dp_opus_encoder_cb.opus_feeding_state.counter = 0.0f;
308
309 return;
310 }
311
a2dp_vendor_opus_get_encoder_interval_ms(void)312 uint64_t a2dp_vendor_opus_get_encoder_interval_ms(void) {
313 return ((a2dp_opus_encoder_cb.opus_encoder_params.framesize * 1000) /
314 a2dp_opus_encoder_cb.opus_encoder_params.sample_rate);
315 }
316
a2dp_vendor_opus_send_frames(uint64_t timestamp_us)317 void a2dp_vendor_opus_send_frames(uint64_t timestamp_us) {
318 uint8_t nb_frame = 0;
319 uint8_t nb_iterations = 0;
320
321 a2dp_opus_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
322 if (nb_frame == 0) return;
323
324 for (uint8_t counter = 0; counter < nb_iterations; counter++) {
325 // Transcode frame and enqueue
326 a2dp_opus_encode_frames(nb_frame);
327 }
328
329 return;
330 }
331
332 // Obtains the number of frames to send and number of iterations
333 // to be used. |num_of_iterations| and |num_of_frames| parameters
334 // are used as output param for returning the respective values.
a2dp_opus_get_num_frame_iteration(uint8_t * num_of_iterations,uint8_t * num_of_frames,uint64_t timestamp_us)335 static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations,
336 uint8_t* num_of_frames,
337 uint64_t timestamp_us) {
338 uint32_t result = 0;
339 uint8_t nof = 0;
340 uint8_t noi = 1;
341
342 uint32_t pcm_bytes_per_frame =
343 a2dp_opus_encoder_cb.opus_encoder_params.framesize *
344 a2dp_opus_encoder_cb.feeding_params.channel_count *
345 a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8;
346
347 uint32_t us_this_tick = a2dp_vendor_opus_get_encoder_interval_ms() * 1000;
348 uint64_t now_us = timestamp_us;
349 if (a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us != 0)
350 us_this_tick =
351 (now_us - a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us);
352 a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us = now_us;
353
354 a2dp_opus_encoder_cb.opus_feeding_state.counter +=
355 (float)a2dp_opus_encoder_cb.opus_feeding_state.bytes_per_tick *
356 us_this_tick / (a2dp_vendor_opus_get_encoder_interval_ms() * 1000);
357
358 result =
359 a2dp_opus_encoder_cb.opus_feeding_state.counter / pcm_bytes_per_frame;
360 a2dp_opus_encoder_cb.opus_feeding_state.counter -=
361 result * pcm_bytes_per_frame;
362 nof = result;
363
364 *num_of_frames = nof;
365 *num_of_iterations = noi;
366 }
367
a2dp_opus_encode_frames(uint8_t nb_frame)368 static void a2dp_opus_encode_frames(uint8_t nb_frame) {
369 tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params =
370 &a2dp_opus_encoder_cb.opus_encoder_params;
371 unsigned char* packet;
372 uint8_t remain_nb_frame = nb_frame;
373 uint16_t opus_frame_size = p_encoder_params->framesize;
374 uint8_t read_buffer[p_encoder_params->framesize *
375 p_encoder_params->pcm_wlength *
376 p_encoder_params->channel_mode];
377
378 int32_t out_frames = 0;
379 int32_t written = 0;
380
381 uint32_t bytes_read = 0;
382 while (nb_frame) {
383 BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
384 p_buf->offset = A2DP_OPUS_OFFSET;
385 p_buf->len = 0;
386 p_buf->layer_specific = 0;
387 a2dp_opus_encoder_cb.stats.media_read_total_expected_packets++;
388
389 do {
390 //
391 // Read the PCM data and encode it
392 //
393 uint32_t temp_bytes_read = 0;
394 if (a2dp_opus_read_feeding(read_buffer, &temp_bytes_read)) {
395 bytes_read += temp_bytes_read;
396 packet = (unsigned char*)(p_buf + 1) + p_buf->offset + p_buf->len;
397
398 if (a2dp_opus_encoder_cb.opus_handle == NULL) {
399 LOG_ERROR("invalid OPUS handle");
400 a2dp_opus_encoder_cb.stats.media_read_total_dropped_packets++;
401 osi_free(p_buf);
402 return;
403 }
404
405 written =
406 opus_encode(a2dp_opus_encoder_cb.opus_handle,
407 (const opus_int16*)&read_buffer[0], opus_frame_size,
408 packet, (BT_DEFAULT_BUFFER_SIZE - p_buf->offset));
409
410 if (written <= 0) {
411 LOG_ERROR("OPUS encoding error");
412 a2dp_opus_encoder_cb.stats.media_read_total_dropped_packets++;
413 osi_free(p_buf);
414 return;
415 } else {
416 out_frames++;
417 }
418 p_buf->len += written;
419 nb_frame--;
420 p_buf->layer_specific += out_frames; // added a frame to the buffer
421 } else {
422 LOG_WARN("Opus src buffer underflow %d", nb_frame);
423 a2dp_opus_encoder_cb.opus_feeding_state.counter +=
424 nb_frame * opus_frame_size *
425 a2dp_opus_encoder_cb.feeding_params.channel_count *
426 a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8;
427
428 // no more pcm to read
429 nb_frame = 0;
430 }
431 } while ((written == 0) && nb_frame);
432
433 if (p_buf->len) {
434 /*
435 * Timestamp of the media packet header represent the TS of the
436 * first frame, i.e. the timestamp before including this frame.
437 */
438 *((uint32_t*)(p_buf + 1)) = a2dp_opus_encoder_cb.timestamp;
439
440 a2dp_opus_encoder_cb.timestamp += p_buf->layer_specific * opus_frame_size;
441
442 uint8_t done_nb_frame = remain_nb_frame - nb_frame;
443 remain_nb_frame = nb_frame;
444
445 if (!a2dp_opus_encoder_cb.enqueue_callback(p_buf, done_nb_frame,
446 bytes_read))
447 return;
448 } else {
449 a2dp_opus_encoder_cb.stats.media_read_total_dropped_packets++;
450 osi_free(p_buf);
451 }
452 }
453 }
454
a2dp_opus_read_feeding(uint8_t * read_buffer,uint32_t * bytes_read)455 static bool a2dp_opus_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) {
456 uint32_t read_size = a2dp_opus_encoder_cb.opus_encoder_params.framesize *
457 a2dp_opus_encoder_cb.feeding_params.channel_count *
458 a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8;
459
460 a2dp_opus_encoder_cb.stats.media_read_total_expected_reads_count++;
461 a2dp_opus_encoder_cb.stats.media_read_total_expected_read_bytes += read_size;
462
463 /* Read Data from UIPC channel */
464 uint32_t nb_byte_read =
465 a2dp_opus_encoder_cb.read_callback(read_buffer, read_size);
466 a2dp_opus_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read;
467
468 if (nb_byte_read < read_size) {
469 if (nb_byte_read == 0) return false;
470
471 /* Fill the unfilled part of the read buffer with silence (0) */
472 memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read);
473 nb_byte_read = read_size;
474 }
475 a2dp_opus_encoder_cb.stats.media_read_total_actual_reads_count++;
476
477 *bytes_read = nb_byte_read;
478 return true;
479 }
480
a2dp_vendor_opus_set_transmit_queue_length(size_t transmit_queue_length)481 void a2dp_vendor_opus_set_transmit_queue_length(size_t transmit_queue_length) {
482 a2dp_opus_encoder_cb.TxQueueLength = transmit_queue_length;
483
484 return;
485 }
486
encoderIntervalMs() const487 uint64_t A2dpCodecConfigOpusSource::encoderIntervalMs() const {
488 return a2dp_vendor_opus_get_encoder_interval_ms();
489 }
490
a2dp_vendor_opus_get_effective_frame_size()491 int a2dp_vendor_opus_get_effective_frame_size() {
492 return a2dp_opus_encoder_cb.TxAaMtuSize;
493 }
494
debug_codec_dump(int fd)495 void A2dpCodecConfigOpusSource::debug_codec_dump(int fd) {
496 a2dp_opus_encoder_stats_t* stats = &a2dp_opus_encoder_cb.stats;
497 tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params =
498 &a2dp_opus_encoder_cb.opus_encoder_params;
499
500 A2dpCodecConfig::debug_codec_dump(fd);
501
502 dprintf(fd,
503 " Packet counts (expected/dropped) : %zu / "
504 "%zu\n",
505 stats->media_read_total_expected_packets,
506 stats->media_read_total_dropped_packets);
507
508 dprintf(fd,
509 " PCM read counts (expected/actual) : %zu / "
510 "%zu\n",
511 stats->media_read_total_expected_reads_count,
512 stats->media_read_total_actual_reads_count);
513
514 dprintf(fd,
515 " PCM read bytes (expected/actual) : %zu / "
516 "%zu\n",
517 stats->media_read_total_expected_read_bytes,
518 stats->media_read_total_actual_read_bytes);
519
520 dprintf(fd,
521 " OPUS transmission bitrate (Kbps) : %d\n",
522 p_encoder_params->bitrate);
523
524 dprintf(fd,
525 " OPUS saved transmit queue length : %zu\n",
526 a2dp_opus_encoder_cb.TxQueueLength);
527
528 return;
529 }
530