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 /******************************************************************************
18  *
19  *  Utility functions to help build and parse the Opus Codec Information
20  *  Element and Media Payload.
21  *
22  ******************************************************************************/
23 
24 #define LOG_TAG "bluetooth-a2dp"
25 
26 #include "a2dp_vendor_opus.h"
27 
28 #include <bluetooth/log.h>
29 #include <string.h>
30 
31 #include "a2dp_vendor_opus_decoder.h"
32 #include "a2dp_vendor_opus_encoder.h"
33 #include "internal_include/bt_trace.h"
34 #include "os/log.h"
35 #include "osi/include/osi.h"
36 
37 using namespace bluetooth;
38 
39 // data type for the Opus Codec Information Element */
40 // NOTE: bits_per_sample and frameSize for Opus encoder initialization.
41 typedef struct {
42   uint32_t vendorId;
43   uint16_t codecId;    /* Codec ID for Opus */
44   uint8_t sampleRate;  /* Sampling Frequency */
45   uint8_t channelMode; /* STEREO/DUAL/MONO */
46   btav_a2dp_codec_bits_per_sample_t bits_per_sample;
47   uint8_t future1; /* codec_specific_1 framesize */
48   uint8_t future2; /* codec_specific_2 */
49   uint8_t future3; /* codec_specific_3 */
50   uint8_t future4; /* codec_specific_4 */
51 } tA2DP_OPUS_CIE;
52 
53 /* Opus Source codec capabilities */
54 static const tA2DP_OPUS_CIE a2dp_opus_source_caps = {
55     A2DP_OPUS_VENDOR_ID,  // vendorId
56     A2DP_OPUS_CODEC_ID,   // codecId
57     // sampleRate
58     (A2DP_OPUS_SAMPLING_FREQ_48000),
59     // channelMode
60     (A2DP_OPUS_CHANNEL_MODE_STEREO),
61     // bits_per_sample
62     (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16),
63     // future 1 frameSize
64     (A2DP_OPUS_20MS_FRAMESIZE),
65     // future 2
66     0x00,
67     // future 3
68     0x00,
69     // future 4
70     0x00};
71 
72 /* Opus Sink codec capabilities */
73 static const tA2DP_OPUS_CIE a2dp_opus_sink_caps = {
74     A2DP_OPUS_VENDOR_ID,  // vendorId
75     A2DP_OPUS_CODEC_ID,   // codecId
76     // sampleRate
77     (A2DP_OPUS_SAMPLING_FREQ_48000),
78     // channelMode
79     (A2DP_OPUS_CHANNEL_MODE_STEREO),
80     // bits_per_sample
81     (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16),
82     // future 1 frameSize
83     (A2DP_OPUS_20MS_FRAMESIZE),
84     // future 2
85     0x00,
86     // future 3
87     0x00,
88     // future 4
89     0x00};
90 
91 /* Default Opus codec configuration */
92 static const tA2DP_OPUS_CIE a2dp_opus_default_config = {
93     A2DP_OPUS_VENDOR_ID,                 // vendorId
94     A2DP_OPUS_CODEC_ID,                  // codecId
95     A2DP_OPUS_SAMPLING_FREQ_48000,       // sampleRate
96     A2DP_OPUS_CHANNEL_MODE_STEREO,       // channelMode
97     BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16,  // bits_per_sample
98     A2DP_OPUS_20MS_FRAMESIZE,            // frameSize
99     0x00,                                // future 2
100     0x00,                                // future 3
101     0x00                                 // future 4
102 };
103 
104 static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_opus = {
105     a2dp_vendor_opus_encoder_init,
106     a2dp_vendor_opus_encoder_cleanup,
107     a2dp_vendor_opus_feeding_reset,
108     a2dp_vendor_opus_feeding_flush,
109     a2dp_vendor_opus_get_encoder_interval_ms,
110     a2dp_vendor_opus_get_effective_frame_size,
111     a2dp_vendor_opus_send_frames,
112     a2dp_vendor_opus_set_transmit_queue_length};
113 
114 static const tA2DP_DECODER_INTERFACE a2dp_decoder_interface_opus = {
115     a2dp_vendor_opus_decoder_init,          a2dp_vendor_opus_decoder_cleanup,
116     a2dp_vendor_opus_decoder_decode_packet, a2dp_vendor_opus_decoder_start,
117     a2dp_vendor_opus_decoder_suspend,       a2dp_vendor_opus_decoder_configure,
118 };
119 
120 static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus(
121     const tA2DP_OPUS_CIE* p_cap, const uint8_t* p_codec_info,
122     bool is_peer_codec_info);
123 
124 // Builds the Opus Media Codec Capabilities byte sequence beginning from the
125 // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|.
126 // |p_ie| is a pointer to the Opus Codec Information Element information.
127 // The result is stored in |p_result|. Returns A2DP_SUCCESS on success,
128 // otherwise the corresponding A2DP error status code.
A2DP_BuildInfoOpus(uint8_t media_type,const tA2DP_OPUS_CIE * p_ie,uint8_t * p_result)129 static tA2DP_STATUS A2DP_BuildInfoOpus(uint8_t media_type,
130                                        const tA2DP_OPUS_CIE* p_ie,
131                                        uint8_t* p_result) {
132   if (p_ie == NULL || p_result == NULL) {
133     log::error("invalid information element");
134     return A2DP_INVALID_PARAMS;
135   }
136 
137   *p_result++ = A2DP_OPUS_CODEC_LEN;
138   *p_result++ = (media_type << 4);
139   *p_result++ = A2DP_MEDIA_CT_NON_A2DP;
140 
141   // Vendor ID and Codec ID
142   *p_result++ = (uint8_t)(p_ie->vendorId & 0x000000FF);
143   *p_result++ = (uint8_t)((p_ie->vendorId & 0x0000FF00) >> 8);
144   *p_result++ = (uint8_t)((p_ie->vendorId & 0x00FF0000) >> 16);
145   *p_result++ = (uint8_t)((p_ie->vendorId & 0xFF000000) >> 24);
146   *p_result++ = (uint8_t)(p_ie->codecId & 0x00FF);
147   *p_result++ = (uint8_t)((p_ie->codecId & 0xFF00) >> 8);
148 
149   *p_result = 0;
150   *p_result |= (uint8_t)(p_ie->channelMode) & A2DP_OPUS_CHANNEL_MODE_MASK;
151   if ((*p_result & A2DP_OPUS_CHANNEL_MODE_MASK) == 0) {
152     log::error("channelmode 0x{:X} setting failed", p_ie->channelMode);
153     return A2DP_INVALID_PARAMS;
154   }
155 
156   *p_result |= ((uint8_t)(p_ie->future1) & A2DP_OPUS_FRAMESIZE_MASK);
157   if ((*p_result & A2DP_OPUS_FRAMESIZE_MASK) == 0) {
158     log::error("frameSize 0x{:X} setting failed", p_ie->future1);
159     return A2DP_INVALID_PARAMS;
160   }
161 
162   *p_result |= ((uint8_t)(p_ie->sampleRate) & A2DP_OPUS_SAMPLING_FREQ_MASK);
163   if ((*p_result & A2DP_OPUS_SAMPLING_FREQ_MASK) == 0) {
164     log::error("samplerate 0x{:X} setting failed", p_ie->sampleRate);
165     return A2DP_INVALID_PARAMS;
166   }
167 
168   p_result++;
169 
170   return A2DP_SUCCESS;
171 }
172 
173 // Parses the Opus Media Codec Capabilities byte sequence beginning from the
174 // LOSC octet. The result is stored in |p_ie|. The byte sequence to parse is
175 // |p_codec_info|. If |is_capability| is true, the byte sequence is
176 // codec capabilities, otherwise is codec configuration.
177 // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error
178 // status code.
A2DP_ParseInfoOpus(tA2DP_OPUS_CIE * p_ie,const uint8_t * p_codec_info,bool is_capability)179 static tA2DP_STATUS A2DP_ParseInfoOpus(tA2DP_OPUS_CIE* p_ie,
180                                        const uint8_t* p_codec_info,
181                                        bool is_capability) {
182   uint8_t losc;
183   uint8_t media_type;
184   tA2DP_CODEC_TYPE codec_type;
185 
186   if (p_ie == NULL || p_codec_info == NULL) {
187     log::error("unable to parse information element");
188     return A2DP_INVALID_PARAMS;
189   }
190 
191   // Check the codec capability length
192   losc = *p_codec_info++;
193   if (losc != A2DP_OPUS_CODEC_LEN) {
194     log::error("invalid codec ie length {}", losc);
195     return A2DP_WRONG_CODEC;
196   }
197 
198   media_type = (*p_codec_info++) >> 4;
199   codec_type = *p_codec_info++;
200   /* Check the Media Type and Media Codec Type */
201   if (media_type != AVDT_MEDIA_TYPE_AUDIO ||
202       codec_type != A2DP_MEDIA_CT_NON_A2DP) {
203     log::error("invalid codec");
204     return A2DP_WRONG_CODEC;
205   }
206 
207   // Check the Vendor ID and Codec ID */
208   p_ie->vendorId = (*p_codec_info & 0x000000FF) |
209                    (*(p_codec_info + 1) << 8 & 0x0000FF00) |
210                    (*(p_codec_info + 2) << 16 & 0x00FF0000) |
211                    (*(p_codec_info + 3) << 24 & 0xFF000000);
212   p_codec_info += 4;
213   p_ie->codecId =
214       (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00);
215   p_codec_info += 2;
216   if (p_ie->vendorId != A2DP_OPUS_VENDOR_ID ||
217       p_ie->codecId != A2DP_OPUS_CODEC_ID) {
218     log::error("wrong vendor or codec id");
219     return A2DP_WRONG_CODEC;
220   }
221 
222   p_ie->channelMode = *p_codec_info & A2DP_OPUS_CHANNEL_MODE_MASK;
223   p_ie->future1 = *p_codec_info & A2DP_OPUS_FRAMESIZE_MASK;
224   p_ie->sampleRate = *p_codec_info & A2DP_OPUS_SAMPLING_FREQ_MASK;
225   p_ie->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
226 
227   if (is_capability) {
228     // NOTE: The checks here are very liberal. We should be using more
229     // pedantic checks specific to the SRC or SNK as specified in the spec.
230     if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) {
231       log::error("invalid sample rate 0x{:X}", p_ie->sampleRate);
232       return A2DP_BAD_SAMP_FREQ;
233     }
234     if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) {
235       log::error("invalid channel mode");
236       return A2DP_BAD_CH_MODE;
237     }
238 
239     return A2DP_SUCCESS;
240   }
241 
242   if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) {
243     log::error("invalid sampling frequency 0x{:X}", p_ie->sampleRate);
244     return A2DP_BAD_SAMP_FREQ;
245   }
246   if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) {
247     log::error("invalid channel mode.");
248     return A2DP_BAD_CH_MODE;
249   }
250 
251   return A2DP_SUCCESS;
252 }
253 
254 // Build the Opus Media Payload Header.
255 // |p_dst| points to the location where the header should be written to.
256 // If |frag| is true, the media payload frame is fragmented.
257 // |start| is true for the first packet of a fragmented frame.
258 // |last| is true for the last packet of a fragmented frame.
259 // If |frag| is false, |num| is the number of number of frames in the packet,
260 // otherwise is the number of remaining fragments (including this one).
A2DP_BuildMediaPayloadHeaderOpus(uint8_t * p_dst,bool frag,bool start,bool last,uint8_t num)261 static void A2DP_BuildMediaPayloadHeaderOpus(uint8_t* p_dst, bool frag,
262                                              bool start, bool last,
263                                              uint8_t num) {
264   if (p_dst == NULL) return;
265 
266   *p_dst = 0;
267   if (frag) *p_dst |= A2DP_OPUS_HDR_F_MSK;
268   if (start) *p_dst |= A2DP_OPUS_HDR_S_MSK;
269   if (last) *p_dst |= A2DP_OPUS_HDR_L_MSK;
270   *p_dst |= (A2DP_OPUS_HDR_NUM_MSK & num);
271 }
272 
A2DP_IsVendorSourceCodecValidOpus(const uint8_t * p_codec_info)273 bool A2DP_IsVendorSourceCodecValidOpus(const uint8_t* p_codec_info) {
274   tA2DP_OPUS_CIE cfg_cie;
275 
276   /* Use a liberal check when parsing the codec info */
277   return (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, false) == A2DP_SUCCESS) ||
278          (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) == A2DP_SUCCESS);
279 }
280 
A2DP_IsVendorSinkCodecValidOpus(const uint8_t * p_codec_info)281 bool A2DP_IsVendorSinkCodecValidOpus(const uint8_t* p_codec_info) {
282   tA2DP_OPUS_CIE cfg_cie;
283 
284   /* Use a liberal check when parsing the codec info */
285   return (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, false) == A2DP_SUCCESS) ||
286          (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) == A2DP_SUCCESS);
287 }
288 
A2DP_IsVendorPeerSourceCodecValidOpus(const uint8_t * p_codec_info)289 bool A2DP_IsVendorPeerSourceCodecValidOpus(const uint8_t* p_codec_info) {
290   tA2DP_OPUS_CIE cfg_cie;
291 
292   /* Use a liberal check when parsing the codec info */
293   return (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, false) == A2DP_SUCCESS) ||
294          (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) == A2DP_SUCCESS);
295 }
296 
A2DP_IsVendorPeerSinkCodecValidOpus(const uint8_t * p_codec_info)297 bool A2DP_IsVendorPeerSinkCodecValidOpus(const uint8_t* p_codec_info) {
298   tA2DP_OPUS_CIE cfg_cie;
299 
300   /* Use a liberal check when parsing the codec info */
301   return (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, false) == A2DP_SUCCESS) ||
302          (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) == A2DP_SUCCESS);
303 }
304 
A2DP_IsVendorSinkCodecSupportedOpus(const uint8_t * p_codec_info)305 bool A2DP_IsVendorSinkCodecSupportedOpus(const uint8_t* p_codec_info) {
306   return A2DP_CodecInfoMatchesCapabilityOpus(&a2dp_opus_sink_caps, p_codec_info,
307                                              false) == A2DP_SUCCESS;
308 }
A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t * p_codec_info)309 bool A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t* p_codec_info) {
310   return A2DP_CodecInfoMatchesCapabilityOpus(&a2dp_opus_sink_caps, p_codec_info,
311                                              true) == A2DP_SUCCESS;
312 }
313 
314 // Checks whether A2DP Opus codec configuration matches with a device's codec
315 // capabilities. |p_cap| is the Opus codec configuration. |p_codec_info| is
316 // the device's codec capabilities.
317 // If |is_capability| is true, the byte sequence is codec capabilities,
318 // otherwise is codec configuration.
319 // |p_codec_info| contains the codec capabilities for a peer device that
320 // is acting as an A2DP source.
321 // Returns A2DP_SUCCESS if the codec configuration matches with capabilities,
322 // otherwise the corresponding A2DP error status code.
A2DP_CodecInfoMatchesCapabilityOpus(const tA2DP_OPUS_CIE * p_cap,const uint8_t * p_codec_info,bool is_capability)323 static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus(
324     const tA2DP_OPUS_CIE* p_cap, const uint8_t* p_codec_info,
325     bool is_capability) {
326   tA2DP_STATUS status;
327   tA2DP_OPUS_CIE cfg_cie;
328 
329   /* parse configuration */
330   status = A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, is_capability);
331   if (status != A2DP_SUCCESS) {
332     log::error("parsing failed {}", status);
333     return status;
334   }
335 
336   /* verify that each parameter is in range */
337 
338   log::verbose("SAMPLING FREQ peer: 0x{:x}, capability 0x{:x}",
339                cfg_cie.sampleRate, p_cap->sampleRate);
340   log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode,
341                p_cap->channelMode);
342   log::verbose("FRAMESIZE peer: 0x{:x}, capability 0x{:x}", cfg_cie.future1,
343                p_cap->future1);
344 
345   /* sampling frequency */
346   if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ;
347 
348   /* channel mode */
349   if ((cfg_cie.channelMode & p_cap->channelMode) == 0) return A2DP_NS_CH_MODE;
350 
351   /* frameSize */
352   if ((cfg_cie.future1 & p_cap->future1) == 0) return A2DP_NS_FRAMESIZE;
353 
354   return A2DP_SUCCESS;
355 }
356 
A2DP_VendorUsesRtpHeaderOpus(bool,const uint8_t *)357 bool A2DP_VendorUsesRtpHeaderOpus(bool /* content_protection_enabled */,
358                                   const uint8_t* /* p_codec_info */) {
359   return true;
360 }
361 
A2DP_VendorCodecNameOpus(const uint8_t *)362 const char* A2DP_VendorCodecNameOpus(const uint8_t* /* p_codec_info */) {
363   return "Opus";
364 }
365 
A2DP_VendorCodecTypeEqualsOpus(const uint8_t * p_codec_info_a,const uint8_t * p_codec_info_b)366 bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a,
367                                     const uint8_t* p_codec_info_b) {
368   tA2DP_OPUS_CIE Opus_cie_a;
369   tA2DP_OPUS_CIE Opus_cie_b;
370 
371   // Check whether the codec info contains valid data
372   tA2DP_STATUS a2dp_status =
373       A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true);
374   if (a2dp_status != A2DP_SUCCESS) {
375     log::error("cannot decode codec information: {}", a2dp_status);
376     return false;
377   }
378   a2dp_status = A2DP_ParseInfoOpus(&Opus_cie_b, p_codec_info_b, true);
379   if (a2dp_status != A2DP_SUCCESS) {
380     log::error("cannot decode codec information: {}", a2dp_status);
381     return false;
382   }
383 
384   return true;
385 }
386 
A2DP_VendorCodecEqualsOpus(const uint8_t * p_codec_info_a,const uint8_t * p_codec_info_b)387 bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a,
388                                 const uint8_t* p_codec_info_b) {
389   tA2DP_OPUS_CIE Opus_cie_a;
390   tA2DP_OPUS_CIE Opus_cie_b;
391 
392   // Check whether the codec info contains valid data
393   tA2DP_STATUS a2dp_status =
394       A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true);
395   if (a2dp_status != A2DP_SUCCESS) {
396     log::error("cannot decode codec information: {}", a2dp_status);
397     return false;
398   }
399   a2dp_status = A2DP_ParseInfoOpus(&Opus_cie_b, p_codec_info_b, true);
400   if (a2dp_status != A2DP_SUCCESS) {
401     log::error("cannot decode codec information: {}", a2dp_status);
402     return false;
403   }
404 
405   return (Opus_cie_a.sampleRate == Opus_cie_b.sampleRate) &&
406          (Opus_cie_a.channelMode == Opus_cie_b.channelMode) &&
407          (Opus_cie_a.future1 == Opus_cie_b.future1);
408 }
409 
A2DP_VendorGetBitRateOpus(const uint8_t * p_codec_info)410 int A2DP_VendorGetBitRateOpus(const uint8_t* p_codec_info) {
411   int channel_count = A2DP_VendorGetTrackChannelCountOpus(p_codec_info);
412   int framesize = A2DP_VendorGetFrameSizeOpus(p_codec_info);
413   int samplerate = A2DP_VendorGetTrackSampleRateOpus(p_codec_info);
414 
415   // in milliseconds
416   switch ((framesize * 1000) / samplerate) {
417     case 20:
418       if (channel_count == 2) {
419         return 256000;
420       } else if (channel_count == 1) {
421         return 128000;
422       } else
423         return -1;
424     default:
425       return -1;
426   }
427 }
428 
A2DP_VendorGetTrackSampleRateOpus(const uint8_t * p_codec_info)429 int A2DP_VendorGetTrackSampleRateOpus(const uint8_t* p_codec_info) {
430   tA2DP_OPUS_CIE Opus_cie;
431 
432   // Check whether the codec info contains valid data
433   tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
434   if (a2dp_status != A2DP_SUCCESS) {
435     log::error("cannot decode codec information: {}", a2dp_status);
436     return -1;
437   }
438 
439   switch (Opus_cie.sampleRate) {
440     case A2DP_OPUS_SAMPLING_FREQ_48000:
441       return 48000;
442   }
443 
444   return -1;
445 }
446 
A2DP_VendorGetTrackBitsPerSampleOpus(const uint8_t * p_codec_info)447 int A2DP_VendorGetTrackBitsPerSampleOpus(const uint8_t* p_codec_info) {
448   tA2DP_OPUS_CIE Opus_cie;
449 
450   // Check whether the codec info contains valid data
451   tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
452   if (a2dp_status != A2DP_SUCCESS) {
453     log::error("cannot decode codec information: {}", a2dp_status);
454     return -1;
455   }
456 
457   switch (Opus_cie.bits_per_sample) {
458     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
459       return 16;
460     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
461       return 24;
462     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
463       return 32;
464     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE:
465     default:
466       log::error("Invalid bit depth setting");
467       return -1;
468   }
469 }
470 
A2DP_VendorGetTrackChannelCountOpus(const uint8_t * p_codec_info)471 int A2DP_VendorGetTrackChannelCountOpus(const uint8_t* p_codec_info) {
472   tA2DP_OPUS_CIE Opus_cie;
473 
474   // Check whether the codec info contains valid data
475   tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
476   if (a2dp_status != A2DP_SUCCESS) {
477     log::error("cannot decode codec information: {}", a2dp_status);
478     return -1;
479   }
480 
481   switch (Opus_cie.channelMode) {
482     case A2DP_OPUS_CHANNEL_MODE_MONO:
483       return 1;
484     case A2DP_OPUS_CHANNEL_MODE_STEREO:
485     case A2DP_OPUS_CHANNEL_MODE_DUAL_MONO:
486       return 2;
487     default:
488       log::error("Invalid channel setting");
489   }
490 
491   return -1;
492 }
493 
A2DP_VendorGetSinkTrackChannelTypeOpus(const uint8_t * p_codec_info)494 int A2DP_VendorGetSinkTrackChannelTypeOpus(const uint8_t* p_codec_info) {
495   tA2DP_OPUS_CIE Opus_cie;
496 
497   // Check whether the codec info contains valid data
498   tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
499   if (a2dp_status != A2DP_SUCCESS) {
500     log::error("cannot decode codec information: {}", a2dp_status);
501     return -1;
502   }
503 
504   switch (Opus_cie.channelMode) {
505     case A2DP_OPUS_CHANNEL_MODE_MONO:
506       return 1;
507     case A2DP_OPUS_CHANNEL_MODE_STEREO:
508       return 2;
509   }
510 
511   return -1;
512 }
513 
A2DP_VendorGetChannelModeCodeOpus(const uint8_t * p_codec_info)514 int A2DP_VendorGetChannelModeCodeOpus(const uint8_t* p_codec_info) {
515   tA2DP_OPUS_CIE Opus_cie;
516 
517   // Check whether the codec info contains valid data
518   tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
519   if (a2dp_status != A2DP_SUCCESS) {
520     log::error("cannot decode codec information: {}", a2dp_status);
521     return -1;
522   }
523 
524   switch (Opus_cie.channelMode) {
525     case A2DP_OPUS_CHANNEL_MODE_MONO:
526     case A2DP_OPUS_CHANNEL_MODE_STEREO:
527       return Opus_cie.channelMode;
528     default:
529       break;
530   }
531 
532   return -1;
533 }
534 
A2DP_VendorGetFrameSizeOpus(const uint8_t * p_codec_info)535 int A2DP_VendorGetFrameSizeOpus(const uint8_t* p_codec_info) {
536   tA2DP_OPUS_CIE Opus_cie;
537 
538   // Check whether the codec info contains valid data
539   tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
540   if (a2dp_status != A2DP_SUCCESS) {
541     log::error("cannot decode codec information: {}", a2dp_status);
542     return -1;
543   }
544   int samplerate = A2DP_VendorGetTrackSampleRateOpus(p_codec_info);
545 
546   switch (Opus_cie.future1) {
547     case A2DP_OPUS_20MS_FRAMESIZE:
548       if (samplerate == 48000) {
549         return 960;
550       }
551   }
552 
553   return -1;
554 }
555 
A2DP_VendorGetPacketTimestampOpus(const uint8_t *,const uint8_t * p_data,uint32_t * p_timestamp)556 bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* /* p_codec_info */,
557                                        const uint8_t* p_data,
558                                        uint32_t* p_timestamp) {
559   *p_timestamp = *(const uint32_t*)p_data;
560   return true;
561 }
562 
A2DP_VendorBuildCodecHeaderOpus(const uint8_t *,BT_HDR * p_buf,uint16_t frames_per_packet)563 bool A2DP_VendorBuildCodecHeaderOpus(const uint8_t* /* p_codec_info */,
564                                      BT_HDR* p_buf,
565                                      uint16_t frames_per_packet) {
566   uint8_t* p;
567 
568   if (p_buf->offset < 4 + A2DP_OPUS_MPL_HDR_LEN) {
569     return false;
570   }
571 
572   p_buf->offset -= A2DP_OPUS_MPL_HDR_LEN;
573   p = (uint8_t*)(p_buf + 1) + p_buf->offset;
574   p_buf->len += A2DP_OPUS_MPL_HDR_LEN;
575 
576   A2DP_BuildMediaPayloadHeaderOpus(p, false, false, false,
577                                    (uint8_t)frames_per_packet);
578 
579   return true;
580 }
581 
A2DP_VendorCodecInfoStringOpus(const uint8_t * p_codec_info)582 std::string A2DP_VendorCodecInfoStringOpus(const uint8_t* p_codec_info) {
583   std::stringstream res;
584   std::string field;
585   tA2DP_STATUS a2dp_status;
586   tA2DP_OPUS_CIE Opus_cie;
587 
588   a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, true);
589   if (a2dp_status != A2DP_SUCCESS) {
590     res << "A2DP_ParseInfoOpus fail: "
591         << loghex(static_cast<uint8_t>(a2dp_status));
592     return res.str();
593   }
594 
595   res << "\tname: Opus\n";
596 
597   // Sample frequency
598   field.clear();
599   AppendField(&field, (Opus_cie.sampleRate == 0), "NONE");
600   AppendField(&field, (Opus_cie.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000),
601               "48000");
602   res << "\tsamp_freq: " << field << " (" << loghex(Opus_cie.sampleRate)
603       << ")\n";
604 
605   // Channel mode
606   field.clear();
607   AppendField(&field, (Opus_cie.channelMode == 0), "NONE");
608   AppendField(&field, (Opus_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO),
609               "Mono");
610   AppendField(&field, (Opus_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO),
611               "Stereo");
612   res << "\tch_mode: " << field << " (" << loghex(Opus_cie.channelMode)
613       << ")\n";
614 
615   // Framesize
616   field.clear();
617   AppendField(&field, (Opus_cie.future1 == 0), "NONE");
618   AppendField(&field, (Opus_cie.future1 & A2DP_OPUS_20MS_FRAMESIZE), "20ms");
619   AppendField(&field, (Opus_cie.future1 & A2DP_OPUS_10MS_FRAMESIZE), "10ms");
620   res << "\tframesize: " << field << " (" << loghex(Opus_cie.future1) << ")\n";
621 
622   return res.str();
623 }
624 
A2DP_VendorGetEncoderInterfaceOpus(const uint8_t * p_codec_info)625 const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus(
626     const uint8_t* p_codec_info) {
627   if (!A2DP_IsVendorSourceCodecValidOpus(p_codec_info)) return NULL;
628 
629   return &a2dp_encoder_interface_opus;
630 }
631 
A2DP_VendorGetDecoderInterfaceOpus(const uint8_t * p_codec_info)632 const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus(
633     const uint8_t* p_codec_info) {
634   if (!A2DP_IsVendorSinkCodecValidOpus(p_codec_info)) return NULL;
635 
636   return &a2dp_decoder_interface_opus;
637 }
638 
A2DP_VendorAdjustCodecOpus(uint8_t * p_codec_info)639 bool A2DP_VendorAdjustCodecOpus(uint8_t* p_codec_info) {
640   tA2DP_OPUS_CIE cfg_cie;
641 
642   // Nothing to do: just verify the codec info is valid
643   if (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS)
644     return false;
645 
646   return true;
647 }
648 
A2DP_VendorSourceCodecIndexOpus(const uint8_t *)649 btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus(
650     const uint8_t* /* p_codec_info */) {
651   return BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS;
652 }
653 
A2DP_VendorSinkCodecIndexOpus(const uint8_t *)654 btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus(
655     const uint8_t* /* p_codec_info */) {
656   return BTAV_A2DP_CODEC_INDEX_SINK_OPUS;
657 }
658 
A2DP_VendorCodecIndexStrOpus(void)659 const char* A2DP_VendorCodecIndexStrOpus(void) { return "Opus"; }
660 
A2DP_VendorCodecIndexStrOpusSink(void)661 const char* A2DP_VendorCodecIndexStrOpusSink(void) { return "Opus SINK"; }
662 
A2DP_VendorInitCodecConfigOpus(AvdtpSepConfig * p_cfg)663 bool A2DP_VendorInitCodecConfigOpus(AvdtpSepConfig* p_cfg) {
664   if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &a2dp_opus_source_caps,
665                          p_cfg->codec_info) != A2DP_SUCCESS) {
666     return false;
667   }
668 
669   return true;
670 }
671 
A2DP_VendorInitCodecConfigOpusSink(AvdtpSepConfig * p_cfg)672 bool A2DP_VendorInitCodecConfigOpusSink(AvdtpSepConfig* p_cfg) {
673   return A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &a2dp_opus_sink_caps,
674                             p_cfg->codec_info) == A2DP_SUCCESS;
675 }
676 
build_codec_config(const tA2DP_OPUS_CIE & config_cie,btav_a2dp_codec_config_t * result)677 UNUSED_ATTR static void build_codec_config(const tA2DP_OPUS_CIE& config_cie,
678                                            btav_a2dp_codec_config_t* result) {
679   if (config_cie.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000)
680     result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
681 
682   result->bits_per_sample = config_cie.bits_per_sample;
683 
684   if (config_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO)
685     result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
686   if (config_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
687     result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
688   }
689 
690   if (config_cie.future1 & A2DP_OPUS_20MS_FRAMESIZE)
691     result->codec_specific_1 |= BTAV_A2DP_CODEC_FRAME_SIZE_20MS;
692   if (config_cie.future1 & A2DP_OPUS_10MS_FRAMESIZE)
693     result->codec_specific_1 |= BTAV_A2DP_CODEC_FRAME_SIZE_10MS;
694 }
695 
A2dpCodecConfigOpusSource(btav_a2dp_codec_priority_t codec_priority)696 A2dpCodecConfigOpusSource::A2dpCodecConfigOpusSource(
697     btav_a2dp_codec_priority_t codec_priority)
698     : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS,
699                               A2DP_VendorCodecIndexStrOpus(), codec_priority,
700                               true) {
701   // Compute the local capability
702   if (a2dp_opus_source_caps.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) {
703     codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
704   }
705   codec_local_capability_.bits_per_sample =
706       a2dp_opus_source_caps.bits_per_sample;
707   if (a2dp_opus_source_caps.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) {
708     codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
709   }
710   if (a2dp_opus_source_caps.channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
711     codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
712   }
713 }
714 
~A2dpCodecConfigOpusSource()715 A2dpCodecConfigOpusSource::~A2dpCodecConfigOpusSource() {}
716 
init()717 bool A2dpCodecConfigOpusSource::init() {
718   if (!isValid()) return false;
719 
720   return true;
721 }
722 
useRtpHeaderMarkerBit() const723 bool A2dpCodecConfigOpusSource::useRtpHeaderMarkerBit() const { return false; }
724 
725 //
726 // Selects the best sample rate from |sampleRate|.
727 // The result is stored in |p_result| and |p_codec_config|.
728 // Returns true if a selection was made, otherwise false.
729 //
select_best_sample_rate(uint8_t sampleRate,tA2DP_OPUS_CIE * p_result,btav_a2dp_codec_config_t * p_codec_config)730 static bool select_best_sample_rate(uint8_t sampleRate,
731                                     tA2DP_OPUS_CIE* p_result,
732                                     btav_a2dp_codec_config_t* p_codec_config) {
733   if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) {
734     p_result->sampleRate = A2DP_OPUS_SAMPLING_FREQ_48000;
735     p_codec_config->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
736     return true;
737   }
738   return false;
739 }
740 
741 //
742 // Selects the audio sample rate from |p_codec_audio_config|.
743 // |sampleRate| contains the capability.
744 // The result is stored in |p_result| and |p_codec_config|.
745 // Returns true if a selection was made, otherwise false.
746 //
select_audio_sample_rate(const btav_a2dp_codec_config_t * p_codec_audio_config,uint8_t sampleRate,tA2DP_OPUS_CIE * p_result,btav_a2dp_codec_config_t * p_codec_config)747 static bool select_audio_sample_rate(
748     const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t sampleRate,
749     tA2DP_OPUS_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) {
750   switch (p_codec_audio_config->sample_rate) {
751     case BTAV_A2DP_CODEC_SAMPLE_RATE_48000:
752       if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) {
753         p_result->sampleRate = A2DP_OPUS_SAMPLING_FREQ_48000;
754         p_codec_config->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
755         return true;
756       }
757       break;
758     case BTAV_A2DP_CODEC_SAMPLE_RATE_16000:
759     case BTAV_A2DP_CODEC_SAMPLE_RATE_24000:
760     case BTAV_A2DP_CODEC_SAMPLE_RATE_44100:
761     case BTAV_A2DP_CODEC_SAMPLE_RATE_88200:
762     case BTAV_A2DP_CODEC_SAMPLE_RATE_96000:
763     case BTAV_A2DP_CODEC_SAMPLE_RATE_176400:
764     case BTAV_A2DP_CODEC_SAMPLE_RATE_192000:
765     case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE:
766       break;
767   }
768 
769   return false;
770 }
771 
772 //
773 // Selects the best bits per sample from |bits_per_sample|.
774 // |bits_per_sample| contains the capability.
775 // The result is stored in |p_result| and |p_codec_config|.
776 // Returns true if a selection was made, otherwise false.
777 //
select_best_bits_per_sample(btav_a2dp_codec_bits_per_sample_t bits_per_sample,tA2DP_OPUS_CIE * p_result,btav_a2dp_codec_config_t * p_codec_config)778 static bool select_best_bits_per_sample(
779     btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_OPUS_CIE* p_result,
780     btav_a2dp_codec_config_t* p_codec_config) {
781   if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) {
782     p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
783     p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
784     return true;
785   }
786   if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) {
787     p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
788     p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
789     return true;
790   }
791   if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) {
792     p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
793     p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
794     return true;
795   }
796   return false;
797 }
798 
799 //
800 // Selects the audio bits per sample from |p_codec_audio_config|.
801 // |bits_per_sample| contains the capability.
802 // The result is stored in |p_result| and |p_codec_config|.
803 // Returns true if a selection was made, otherwise false.
804 //
select_audio_bits_per_sample(const btav_a2dp_codec_config_t * p_codec_audio_config,btav_a2dp_codec_bits_per_sample_t bits_per_sample,tA2DP_OPUS_CIE * p_result,btav_a2dp_codec_config_t * p_codec_config)805 static bool select_audio_bits_per_sample(
806     const btav_a2dp_codec_config_t* p_codec_audio_config,
807     btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_OPUS_CIE* p_result,
808     btav_a2dp_codec_config_t* p_codec_config) {
809   switch (p_codec_audio_config->bits_per_sample) {
810     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
811       if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) {
812         p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
813         p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
814         return true;
815       }
816       break;
817     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
818       if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) {
819         p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
820         p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
821         return true;
822       }
823       break;
824     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
825       if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) {
826         p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
827         p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
828         return true;
829       }
830       break;
831     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE:
832       break;
833   }
834   return false;
835 }
836 
837 //
838 // Selects the best channel mode from |channelMode|.
839 // The result is stored in |p_result| and |p_codec_config|.
840 // Returns true if a selection was made, otherwise false.
841 //
select_best_channel_mode(uint8_t channelMode,tA2DP_OPUS_CIE * p_result,btav_a2dp_codec_config_t * p_codec_config)842 static bool select_best_channel_mode(uint8_t channelMode,
843                                      tA2DP_OPUS_CIE* p_result,
844                                      btav_a2dp_codec_config_t* p_codec_config) {
845   if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
846     p_result->channelMode = A2DP_OPUS_CHANNEL_MODE_STEREO;
847     p_codec_config->channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
848     return true;
849   }
850   if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) {
851     p_result->channelMode = A2DP_OPUS_CHANNEL_MODE_MONO;
852     p_codec_config->channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
853     return true;
854   }
855   return false;
856 }
857 
858 //
859 // Selects the audio channel mode from |p_codec_audio_config|.
860 // |channelMode| contains the capability.
861 // The result is stored in |p_result| and |p_codec_config|.
862 // Returns true if a selection was made, otherwise false.
863 //
select_audio_channel_mode(const btav_a2dp_codec_config_t * p_codec_audio_config,uint8_t channelMode,tA2DP_OPUS_CIE * p_result,btav_a2dp_codec_config_t * p_codec_config)864 static bool select_audio_channel_mode(
865     const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t channelMode,
866     tA2DP_OPUS_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) {
867   switch (p_codec_audio_config->channel_mode) {
868     case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO:
869       if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) {
870         p_result->channelMode = A2DP_OPUS_CHANNEL_MODE_MONO;
871         p_codec_config->channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
872         return true;
873       }
874       break;
875     case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO:
876       if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
877         p_result->channelMode = A2DP_OPUS_CHANNEL_MODE_STEREO;
878         p_codec_config->channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
879         return true;
880       }
881       break;
882     case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE:
883       break;
884   }
885 
886   return false;
887 }
888 
setCodecConfig(const uint8_t * p_peer_codec_info,bool is_capability,uint8_t * p_result_codec_config)889 bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info,
890                                              bool is_capability,
891                                              uint8_t* p_result_codec_config) {
892   std::lock_guard<std::recursive_mutex> lock(codec_mutex_);
893   tA2DP_OPUS_CIE peer_info_cie;
894   tA2DP_OPUS_CIE result_config_cie;
895   uint8_t channelMode;
896   uint8_t sampleRate;
897   uint8_t frameSize;
898   btav_a2dp_codec_bits_per_sample_t bits_per_sample;
899   const tA2DP_OPUS_CIE* p_a2dp_opus_caps =
900       (is_source_) ? &a2dp_opus_source_caps : &a2dp_opus_sink_caps;
901 
902   btav_a2dp_codec_config_t device_codec_config_ = getCodecConfig();
903 
904   log::info(
905       "AudioManager stream config {} sample rate {} bit depth {} channel mode",
906       device_codec_config_.sample_rate, device_codec_config_.bits_per_sample,
907       device_codec_config_.channel_mode);
908 
909   // Save the internal state
910   btav_a2dp_codec_config_t saved_codec_config = codec_config_;
911   btav_a2dp_codec_config_t saved_codec_capability = codec_capability_;
912   btav_a2dp_codec_config_t saved_codec_selectable_capability =
913       codec_selectable_capability_;
914   btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_;
915   btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_;
916   uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE];
917   uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE];
918   uint8_t saved_ota_codec_peer_config[AVDT_CODEC_SIZE];
919   memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_));
920   memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_,
921          sizeof(ota_codec_peer_capability_));
922   memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_,
923          sizeof(ota_codec_peer_config_));
924 
925   tA2DP_STATUS status =
926       A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_info, is_capability);
927   if (status != A2DP_SUCCESS) {
928     log::error("can't parse peer's capabilities: error = {}", status);
929     goto fail;
930   }
931 
932   //
933   // Build the preferred configuration
934   //
935   memset(&result_config_cie, 0, sizeof(result_config_cie));
936   result_config_cie.vendorId = p_a2dp_opus_caps->vendorId;
937   result_config_cie.codecId = p_a2dp_opus_caps->codecId;
938 
939   //
940   // Select the sample frequency
941   //
942   sampleRate = p_a2dp_opus_caps->sampleRate & peer_info_cie.sampleRate;
943   codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
944 
945   switch (codec_user_config_.sample_rate) {
946     case BTAV_A2DP_CODEC_SAMPLE_RATE_48000:
947       if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) {
948         result_config_cie.sampleRate = A2DP_OPUS_SAMPLING_FREQ_48000;
949         codec_capability_.sample_rate = codec_user_config_.sample_rate;
950         codec_config_.sample_rate = codec_user_config_.sample_rate;
951       }
952       break;
953     case BTAV_A2DP_CODEC_SAMPLE_RATE_44100:
954     case BTAV_A2DP_CODEC_SAMPLE_RATE_88200:
955     case BTAV_A2DP_CODEC_SAMPLE_RATE_96000:
956     case BTAV_A2DP_CODEC_SAMPLE_RATE_176400:
957     case BTAV_A2DP_CODEC_SAMPLE_RATE_192000:
958     case BTAV_A2DP_CODEC_SAMPLE_RATE_16000:
959     case BTAV_A2DP_CODEC_SAMPLE_RATE_24000:
960     case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE:
961       codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
962       codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
963       break;
964   }
965 
966   // Select the sample frequency if there is no user preference
967   do {
968     // Compute the selectable capability
969     if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) {
970       codec_selectable_capability_.sample_rate |=
971           BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
972     }
973 
974     if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break;
975 
976     // Compute the common capability
977     if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000)
978       codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
979 
980     // No user preference - try the codec audio config
981     if (select_audio_sample_rate(&codec_audio_config_, sampleRate,
982                                  &result_config_cie, &codec_config_)) {
983       break;
984     }
985 
986     // No user preference - try the default config
987     if (select_best_sample_rate(
988             a2dp_opus_default_config.sampleRate & peer_info_cie.sampleRate,
989             &result_config_cie, &codec_config_)) {
990       break;
991     }
992 
993     // No user preference - use the best match
994     if (select_best_sample_rate(sampleRate, &result_config_cie,
995                                 &codec_config_)) {
996       break;
997     }
998   } while (false);
999   if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
1000     log::error(
1001         "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}",
1002         p_a2dp_opus_caps->sampleRate, peer_info_cie.sampleRate);
1003     goto fail;
1004   }
1005 
1006   //
1007   // Select the bits per sample
1008   //
1009   // NOTE: this information is NOT included in the Opus A2DP codec description
1010   // that is sent OTA.
1011   bits_per_sample = p_a2dp_opus_caps->bits_per_sample;
1012   codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
1013   switch (codec_user_config_.bits_per_sample) {
1014     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
1015       if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) {
1016         result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample;
1017         codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample;
1018         codec_config_.bits_per_sample = codec_user_config_.bits_per_sample;
1019       }
1020       break;
1021     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
1022       if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) {
1023         result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample;
1024         codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample;
1025         codec_config_.bits_per_sample = codec_user_config_.bits_per_sample;
1026       }
1027       break;
1028     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
1029       if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) {
1030         result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample;
1031         codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample;
1032         codec_config_.bits_per_sample = codec_user_config_.bits_per_sample;
1033       }
1034       break;
1035     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE:
1036       result_config_cie.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
1037       codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
1038       codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
1039       break;
1040   }
1041 
1042   // Select the bits per sample if there is no user preference
1043   do {
1044     // Compute the selectable capability
1045     codec_selectable_capability_.bits_per_sample =
1046         p_a2dp_opus_caps->bits_per_sample;
1047 
1048     if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE)
1049       break;
1050 
1051     // Compute the common capability
1052     codec_capability_.bits_per_sample = bits_per_sample;
1053 
1054     // No user preference - try yhe codec audio config
1055     if (select_audio_bits_per_sample(&codec_audio_config_,
1056                                      p_a2dp_opus_caps->bits_per_sample,
1057                                      &result_config_cie, &codec_config_)) {
1058       break;
1059     }
1060 
1061     // No user preference - try the default config
1062     if (select_best_bits_per_sample(a2dp_opus_default_config.bits_per_sample,
1063                                     &result_config_cie, &codec_config_)) {
1064       break;
1065     }
1066 
1067     // No user preference - use the best match
1068     if (select_best_bits_per_sample(p_a2dp_opus_caps->bits_per_sample,
1069                                     &result_config_cie, &codec_config_)) {
1070       break;
1071     }
1072   } while (false);
1073   if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
1074     log::error(
1075         "cannot match bits per sample: default = 0x{:x} user preference = "
1076         "0x{:x}",
1077         a2dp_opus_default_config.bits_per_sample,
1078         codec_user_config_.bits_per_sample);
1079     goto fail;
1080   }
1081 
1082   //
1083   // Select the channel mode
1084   //
1085   channelMode = p_a2dp_opus_caps->channelMode & peer_info_cie.channelMode;
1086   codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
1087   switch (codec_user_config_.channel_mode) {
1088     case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO:
1089       if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) {
1090         result_config_cie.channelMode = A2DP_OPUS_CHANNEL_MODE_MONO;
1091         codec_capability_.channel_mode = codec_user_config_.channel_mode;
1092         codec_config_.channel_mode = codec_user_config_.channel_mode;
1093       }
1094       break;
1095     case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO:
1096       if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
1097         result_config_cie.channelMode = A2DP_OPUS_CHANNEL_MODE_STEREO;
1098         codec_capability_.channel_mode = codec_user_config_.channel_mode;
1099         codec_config_.channel_mode = codec_user_config_.channel_mode;
1100       }
1101       break;
1102     case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE:
1103       codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
1104       codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
1105       break;
1106   }
1107 
1108   // Select the channel mode if there is no user preference
1109   do {
1110     // Compute the selectable capability
1111     if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) {
1112       codec_selectable_capability_.channel_mode |=
1113           BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
1114     }
1115     if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
1116       codec_selectable_capability_.channel_mode |=
1117           BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
1118     }
1119 
1120     if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break;
1121 
1122     // Compute the common capability
1123     if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO)
1124       codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
1125     if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
1126       codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
1127     }
1128 
1129     // No user preference - try the codec audio config
1130     if (select_audio_channel_mode(&codec_audio_config_, channelMode,
1131                                   &result_config_cie, &codec_config_)) {
1132       break;
1133     }
1134 
1135     // No user preference - try the default config
1136     if (select_best_channel_mode(
1137             a2dp_opus_default_config.channelMode & peer_info_cie.channelMode,
1138             &result_config_cie, &codec_config_)) {
1139       break;
1140     }
1141 
1142     // No user preference - use the best match
1143     if (select_best_channel_mode(channelMode, &result_config_cie,
1144                                  &codec_config_)) {
1145       break;
1146     }
1147   } while (false);
1148   if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
1149     log::error(
1150         "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}",
1151         p_a2dp_opus_caps->channelMode, peer_info_cie.channelMode);
1152     goto fail;
1153   }
1154 
1155   //
1156   // Select the frame size
1157   //
1158   frameSize = p_a2dp_opus_caps->future1 & peer_info_cie.future1;
1159   codec_config_.codec_specific_1 = BTAV_A2DP_CODEC_FRAME_SIZE_NONE;
1160   switch (codec_user_config_.codec_specific_1) {
1161     case BTAV_A2DP_CODEC_FRAME_SIZE_20MS:
1162       if (frameSize & A2DP_OPUS_20MS_FRAMESIZE) {
1163         result_config_cie.future1 = A2DP_OPUS_20MS_FRAMESIZE;
1164         codec_capability_.codec_specific_1 =
1165             codec_user_config_.codec_specific_1;
1166         codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1;
1167       }
1168       break;
1169     case BTAV_A2DP_CODEC_FRAME_SIZE_10MS:
1170       if (frameSize & A2DP_OPUS_10MS_FRAMESIZE) {
1171         result_config_cie.future1 = A2DP_OPUS_10MS_FRAMESIZE;
1172         codec_capability_.codec_specific_1 =
1173             codec_user_config_.codec_specific_1;
1174         codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1;
1175       }
1176       break;
1177     case BTAV_A2DP_CODEC_FRAME_SIZE_NONE:
1178       codec_capability_.codec_specific_1 = BTAV_A2DP_CODEC_FRAME_SIZE_NONE;
1179       codec_config_.codec_specific_1 = BTAV_A2DP_CODEC_FRAME_SIZE_NONE;
1180       break;
1181   }
1182 
1183   // No user preference - set default value
1184   codec_config_.codec_specific_1 = BTAV_A2DP_CODEC_FRAME_SIZE_20MS;
1185   result_config_cie.future1 = A2DP_OPUS_20MS_FRAMESIZE;
1186   result_config_cie.future3 = 0x00;
1187 
1188   if (codec_config_.codec_specific_1 == BTAV_A2DP_CODEC_FRAME_SIZE_NONE) {
1189     log::error(
1190         "cannot match frame size: local caps = 0x{:x} peer info = 0x{:x}",
1191         p_a2dp_opus_caps->future1, peer_info_cie.future1);
1192     goto fail;
1193   }
1194 
1195   if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie,
1196                          p_result_codec_config) != A2DP_SUCCESS) {
1197     log::error("failed to BuildInfoOpus for result_config_cie");
1198     goto fail;
1199   }
1200 
1201   //
1202   // Copy the codec-specific fields if they are not zero
1203   //
1204   if (codec_user_config_.codec_specific_1 != 0)
1205     codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1;
1206   if (codec_user_config_.codec_specific_2 != 0)
1207     codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2;
1208   if (codec_user_config_.codec_specific_3 != 0)
1209     codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3;
1210   if (codec_user_config_.codec_specific_4 != 0)
1211     codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4;
1212 
1213   // Create a local copy of the peer codec capability, and the
1214   // result codec config.
1215   if (is_capability) {
1216     status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie,
1217                                 ota_codec_peer_capability_);
1218   } else {
1219     status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie,
1220                                 ota_codec_peer_config_);
1221   }
1222   log::assert_that(status == A2DP_SUCCESS,
1223                    "assert failed: status == A2DP_SUCCESS");
1224 
1225   status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie,
1226                               ota_codec_config_);
1227   log::assert_that(status == A2DP_SUCCESS,
1228                    "assert failed: status == A2DP_SUCCESS");
1229   return true;
1230 
1231 fail:
1232   // Restore the internal state
1233   codec_config_ = saved_codec_config;
1234   codec_capability_ = saved_codec_capability;
1235   codec_selectable_capability_ = saved_codec_selectable_capability;
1236   codec_user_config_ = saved_codec_user_config;
1237   codec_audio_config_ = saved_codec_audio_config;
1238   memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_));
1239   memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability,
1240          sizeof(ota_codec_peer_capability_));
1241   memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config,
1242          sizeof(ota_codec_peer_config_));
1243   return false;
1244 }
1245 
setPeerCodecCapabilities(const uint8_t * p_peer_codec_capabilities)1246 bool A2dpCodecConfigOpusBase::setPeerCodecCapabilities(
1247     const uint8_t* p_peer_codec_capabilities) {
1248   std::lock_guard<std::recursive_mutex> lock(codec_mutex_);
1249   tA2DP_OPUS_CIE peer_info_cie;
1250   uint8_t channelMode;
1251   uint8_t sampleRate;
1252   const tA2DP_OPUS_CIE* p_a2dp_opus_caps =
1253       (is_source_) ? &a2dp_opus_source_caps : &a2dp_opus_sink_caps;
1254 
1255   // Save the internal state
1256   btav_a2dp_codec_config_t saved_codec_selectable_capability =
1257       codec_selectable_capability_;
1258   uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE];
1259   memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_,
1260          sizeof(ota_codec_peer_capability_));
1261 
1262   tA2DP_STATUS status =
1263       A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_capabilities, true);
1264   if (status != A2DP_SUCCESS) {
1265     log::error("can't parse peer's capabilities: error = {}", status);
1266     goto fail;
1267   }
1268 
1269   // Compute the selectable capability - sample rate
1270   sampleRate = p_a2dp_opus_caps->sampleRate & peer_info_cie.sampleRate;
1271   if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) {
1272     codec_selectable_capability_.sample_rate |=
1273         BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
1274   }
1275 
1276   // Compute the selectable capability - bits per sample
1277   codec_selectable_capability_.bits_per_sample =
1278       p_a2dp_opus_caps->bits_per_sample;
1279 
1280   // Compute the selectable capability - channel mode
1281   channelMode = p_a2dp_opus_caps->channelMode & peer_info_cie.channelMode;
1282   if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) {
1283     codec_selectable_capability_.channel_mode |=
1284         BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
1285   }
1286   if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) {
1287     codec_selectable_capability_.channel_mode |=
1288         BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
1289   }
1290 
1291   log::info("BuildInfoOpus for peer info cie for ota caps");
1292   status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie,
1293                               ota_codec_peer_capability_);
1294   log::assert_that(status == A2DP_SUCCESS,
1295                    "assert failed: status == A2DP_SUCCESS");
1296   return true;
1297 
1298 fail:
1299   // Restore the internal state
1300   codec_selectable_capability_ = saved_codec_selectable_capability;
1301   memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability,
1302          sizeof(ota_codec_peer_capability_));
1303   return false;
1304 }
1305 
A2dpCodecConfigOpusSink(btav_a2dp_codec_priority_t codec_priority)1306 A2dpCodecConfigOpusSink::A2dpCodecConfigOpusSink(
1307     btav_a2dp_codec_priority_t codec_priority)
1308     : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SINK_OPUS,
1309                               A2DP_VendorCodecIndexStrOpusSink(),
1310                               codec_priority, false) {}
1311 
~A2dpCodecConfigOpusSink()1312 A2dpCodecConfigOpusSink::~A2dpCodecConfigOpusSink() {}
1313 
init()1314 bool A2dpCodecConfigOpusSink::init() {
1315   if (!isValid()) return false;
1316 
1317   return true;
1318 }
1319 
useRtpHeaderMarkerBit() const1320 bool A2dpCodecConfigOpusSink::useRtpHeaderMarkerBit() const { return false; }
1321 
updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS *,bool *,bool *,bool *)1322 bool A2dpCodecConfigOpusSink::updateEncoderUserConfig(
1323     const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */,
1324     bool* /* p_restart_input */, bool* /* p_restart_output */,
1325     bool* /* p_config_updated */) {
1326   return false;
1327 }
1328