1 /*
2  * Copyright 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //
18 // A2DP Codecs API
19 //
20 
21 #ifndef A2DP_CODEC_API_H
22 #define A2DP_CODEC_API_H
23 
24 #include <hardware/bt_av.h>
25 #include <stddef.h>
26 #include <stdint.h>
27 #include <string.h>
28 
29 #include <list>
30 #include <map>
31 #include <mutex>
32 #include <string>
33 #include <vector>
34 
35 #include "a2dp_api.h"
36 #include "audio_a2dp_hw/include/audio_a2dp_hw.h"
37 #include "avdt_api.h"
38 #include "stack/include/bt_hdr.h"
39 #include "types/raw_address.h"
40 
41 class tBT_A2DP_OFFLOAD;
42 
43 /**
44  * Structure used to initialize the A2DP encoder with A2DP peer information
45  */
46 typedef struct {
47   bool is_peer_edr;          // True if the A2DP peer supports EDR
48   bool peer_supports_3mbps;  // True if the A2DP peer supports 3 Mbps EDR
49   uint16_t peer_mtu;         // MTU of the A2DP peer
50 } tA2DP_ENCODER_INIT_PEER_PARAMS;
51 
52 class A2dpCodecConfig {
53   friend class A2dpCodecs;
54 
55  public:
56   // Creates a codec entry. The selected codec is defined by |codec_index|,
57   // Returns the codec entry on success, otherwise nullptr.
58   static A2dpCodecConfig* createCodec(
59       btav_a2dp_codec_index_t codec_index,
60       btav_a2dp_codec_priority_t codec_priority =
61           BTAV_A2DP_CODEC_PRIORITY_DEFAULT);
62 
63   virtual ~A2dpCodecConfig() = 0;
64 
65   // Gets the pre-defined codec index.
codecIndex()66   btav_a2dp_codec_index_t codecIndex() const { return codec_index_; }
67 
68   // Gets the standardized codec identifier.
69   // The codec identifier is 40 bits,
70   //  - Bits 0-7: Audio Codec ID, as defined by [ID 6.5.1]
71   //      0x00: SBC
72   //      0x02: AAC
73   //      0xFF: Vendor
74   //  - Bits 8-23: Company ID,
75   //      set to 0, if octet 0 is not 0xFF.
76   //  - Bits 24-39: Vendor-defined codec ID,
77   //      set to 0, if octet 0 is not 0xFF.
codecId()78   uint64_t codecId() const { return codec_id_; }
79 
80   // Gets the codec name.
name()81   const std::string& name() const { return name_; }
82 
83   // Gets the current priority of the codec.
codecPriority()84   btav_a2dp_codec_priority_t codecPriority() const { return codec_priority_; }
85 
86   // gets current OTA codec specific config to |p_a2dp_offload->codec_info|.
87   // Returns true if the current codec config is valid and copied,
88   // otherwise false.
89   bool getCodecSpecificConfig(tBT_A2DP_OFFLOAD* p_a2dp_offload);
90 
91   // Gets the bitRate for the A2DP codec.
92   // Returns the bitrate of current codec configuration, or 0 if not configured
93   int getTrackBitRate() const;
94 
95   // Copies out the current OTA codec config to |p_codec_info|.
96   // Returns true if the current codec config is valid and copied,
97   // otherwise false.
98   bool copyOutOtaCodecConfig(uint8_t* p_codec_info);
99 
100   // Gets the current codec configuration.
101   // Returns a copy of the current codec configuration.
102   btav_a2dp_codec_config_t getCodecConfig();
103 
104   // Gets the current codec capability.
105   // The capability is computed by intersecting the local codec's capability
106   // and the peer's codec capability. However, if there is an explicit user
107   // configuration for some of the parameters, the result codec configuration
108   // and capability is restricted to the user's configuration choice.
109   // Returns a copy of the current codec capability.
110   btav_a2dp_codec_config_t getCodecCapability();
111 
112   // Gets the codec local capability.
113   // Returns a copy of the codec local capability.
114   btav_a2dp_codec_config_t getCodecLocalCapability();
115 
116   // Gets the codec selectable capability.
117   // The capability is computed by intersecting the local codec's capability
118   // and the peer's codec capability. Any explicit user configuration is
119   // not included in the result.
120   // Returns a copy of the codec selectable capability.
121   btav_a2dp_codec_config_t getCodecSelectableCapability();
122 
123   // Gets the current codec user configuration.
124   // Returns a copy of the current codec user configuration.
125   btav_a2dp_codec_config_t getCodecUserConfig();
126 
127   // Gets the current codec audio configuration.
128   // Returns a copy of the current codec audio configuration.
129   btav_a2dp_codec_config_t getCodecAudioConfig();
130 
131   // Gets the number of bits per sample of the current codec configuration,
132   // or 0 if not configured.
133   uint8_t getAudioBitsPerSample();
134 
135   // Checks whether the codec uses the RTP Header Marker bit (see RFC 6416).
136   // NOTE: Even if the encoded data uses RTP headers, some codecs do not use
137   // the Marker bit - that bit is expected to be set to 0.
138   // Returns true if the encoded data packets have RTP headers, and
139   // the Marker bit in the header is set according to RFC 6416.
140   virtual bool useRtpHeaderMarkerBit() const = 0;
141 
142   // Checks whether |codec_config| is empty and contains no configuration.
143   // Returns true if |codec_config| is empty, otherwise false.
144   static bool isCodecConfigEmpty(const btav_a2dp_codec_config_t& codec_config);
145 
146  protected:
147   // Sets the current priority of the codec to |codec_priority|.
148   // If |codec_priority| is BTAV_A2DP_CODEC_PRIORITY_DEFAULT, the priority is
149   // reset to its default value.
150   void setCodecPriority(btav_a2dp_codec_priority_t codec_priority);
151 
152   // Sets the current priority of the codec to its default value.
153   void setDefaultCodecPriority();
154 
155   // Sets the A2DP Source-to-Sink codec configuration to be used
156   // with a peer Sink device.
157   // |p_peer_codec_info| is the peer's A2DP Sink codec information
158   // to use. If |is_capability| is true, then |p_peer_codec_info| contains the
159   // peer's A2DP Sink codec capability, otherwise it contains the peer's
160   // preferred A2DP codec configuration to use.
161   // The result codec configuration is stored in |p_result_codec_config|.
162   // See |A2dpCodecs.setCodecConfig| for detailed description of
163   // the actual mechanism used to compute the configuration.
164   // Returns true on success, othewise false.
165   virtual bool setCodecConfig(const uint8_t* p_peer_codec_info,
166                               bool is_capability,
167                               uint8_t* p_result_codec_config) = 0;
168 
169   // Sets the user prefered codec configuration.
170   // |codec_user_config| contains the preferred codec user configuration.
171   // |codec_audio_config| contains the selected audio feeding configuration.
172   // |p_peer_params| contains the A2DP peer information.
173   // |p_peer_codec_info| is the peer's A2DP Sink codec information
174   // to use. If |is_capability| is true, then |p_peer_codec_info| contains the
175   // peer's A2DP Sink codec capability, otherwise it contains the peer's
176   // preferred A2DP codec configuration to use.
177   // If there is a change in the codec configuration that requires restarting
178   // if the audio input stream, flag |p_restart_input| is set to true.
179   // If there is a change in the encoder configuration that requires restarting
180   // of the A2DP connection, the new codec configuration is stored in
181   // |p_result_codec_config|, and flag |p_restart_output| is set to true.
182   // If there is any change in the codec configuration, flag |p_config_updated|
183   // is set to true.
184   // Returns true on success, otherwise false.
185   bool setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config,
186                           const btav_a2dp_codec_config_t& codec_audio_config,
187                           const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
188                           const uint8_t* p_peer_codec_info, bool is_capability,
189                           uint8_t* p_result_codec_config, bool* p_restart_input,
190                           bool* p_restart_output, bool* p_config_updated);
191 
192   // Sets the codec capabilities for a peer.
193   // |p_peer_codec_capabiltities| is the peer codec capabilities to set.
194   // Returns true on success, otherwise false.
195   virtual bool setPeerCodecCapabilities(
196       const uint8_t* p_peer_codec_capabilities) = 0;
197 
198   // Constructor where |codec_index| is the unique index that identifies the
199   // codec. The user-friendly name is |name|.
200   // The default codec priority is |codec_priority|. If the value is
201   // |BTAV_A2DP_CODEC_PRIORITY_DEFAULT|, the codec priority is computed
202   // internally.
203   A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, uint64_t codec_id,
204                   const std::string& name,
205                   btav_a2dp_codec_priority_t codec_priority);
206 
207   // Initializes the codec entry.
208   // Returns true on success, otherwise false.
209   virtual bool init() = 0;
210 
211   // Checks whether the internal state is valid
212   virtual bool isValid() const;
213 
214   // Checks whether the A2DP Codec Configuration is valid.
215   // Returns true if A2DP Codec Configuration stored in |codec_config|
216   // is valid, otherwise false.
217   static bool codecConfigIsValid(const btav_a2dp_codec_config_t& codec_config);
218 
219   // Gets the string representation of A2DP Codec Configuration.
220   // Returns the string representation of A2DP Codec Configuration stored
221   // in |codec_config|. The format is:
222   // "Rate=44100|48000 Bits=16|24 Mode=MONO|STEREO"
223   static std::string codecConfig2Str(
224       const btav_a2dp_codec_config_t& codec_config);
225 
226   // Gets the string representation of A2DP Codec Sample Rate.
227   // Returns the string representation of A2DP Codec Sample Rate stored
228   // in |codec_sample_rate|. If there are multiple values stored in
229   // |codec_sample_rate|, the return string format is "rate1|rate2|rate3".
230   static std::string codecSampleRate2Str(
231       btav_a2dp_codec_sample_rate_t codec_sample_rate);
232 
233   // Gets the string representation of A2DP Codec Bits Per Sample.
234   // Returns the string representation of A2DP Codec Bits Per Sample stored
235   // in |codec_bits_per_sample|. If there are multiple values stored in
236   // |codec_bits_per_sample|, the return string format is "bits1|bits2|bits3".
237   static std::string codecBitsPerSample2Str(
238       btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample);
239 
240   // Gets the string representation of A2DP Codec Channel Mode.
241   // Returns the string representation of A2DP Channel Mode stored
242   // in |codec_channel_mode|. If there are multiple values stored in
243   // |codec_channel_mode|, the return string format is "mode1|mode2|mode3".
244   static std::string codecChannelMode2Str(
245       btav_a2dp_codec_channel_mode_t codec_channel_mode);
246 
247   // Dumps codec-related information.
248   // The information is written in user-friendly form to file descriptor |fd|.
249   virtual void debug_codec_dump(int fd);
250 
251   std::recursive_mutex codec_mutex_;
252   const btav_a2dp_codec_index_t codec_index_;  // The unique codec index
253   const uint64_t codec_id_;                    // The standardized codec id
254   const std::string name_;                     // The codec name
255   btav_a2dp_codec_priority_t codec_priority_;  // Codec priority: must be unique
256   btav_a2dp_codec_priority_t default_codec_priority_;
257 
258   btav_a2dp_codec_config_t codec_config_;
259   btav_a2dp_codec_config_t codec_capability_;
260   btav_a2dp_codec_config_t codec_local_capability_;
261   btav_a2dp_codec_config_t codec_selectable_capability_;
262 
263   // The optional user configuration. The values (if set) are used
264   // as a preference when there is a choice. If a particular value
265   // is not supported by the local or remote device, it is ignored.
266   btav_a2dp_codec_config_t codec_user_config_;
267 
268   // The selected audio feeding configuration.
269   btav_a2dp_codec_config_t codec_audio_config_;
270 
271   uint8_t ota_codec_config_[AVDT_CODEC_SIZE];
272   uint8_t ota_codec_peer_capability_[AVDT_CODEC_SIZE];
273   uint8_t ota_codec_peer_config_[AVDT_CODEC_SIZE];
274 };
275 
276 class A2dpCodecs {
277  public:
278   // Constructor for class |A2dpCodecs|.
279   // |codec_priorities| contains the codec priorities to use.
280   A2dpCodecs(const std::vector<btav_a2dp_codec_config_t>& codec_priorities);
281   ~A2dpCodecs();
282 
283   // Initializes all supported codecs.
284   // Returns true if at least one Source codec and one Sink codec were
285   // initialized, otherwise false.
286   bool init();
287 
288   // Finds the Source codec that corresponds to the A2DP over-the-air
289   // |p_codec_info| information.
290   // Returns the Source codec if found, otherwise nullptr.
291   A2dpCodecConfig* findSourceCodecConfig(const uint8_t* p_codec_info);
292 
293   // Finds the Source codec that corresponds to the A2DP codec index.
294   // Returns the Source codec if found, otherwise nullptr.
295   A2dpCodecConfig* findSourceCodecConfig(btav_a2dp_codec_index_t codec_index);
296 
297   // Finds the Sink codec that corresponds to the A2DP over-the-air
298   // |p_codec_info| information.
299   // Returns the Sink codec if found, otherwise nullptr.
300   A2dpCodecConfig* findSinkCodecConfig(const uint8_t* p_codec_info);
301 
302   // Checks whether the codec for |codec_index| is supported.
303   // Returns true if the codec is supported, otherwise false.
304   bool isSupportedCodec(btav_a2dp_codec_index_t codec_index);
305 
306   // Gets the codec config that is currently selected.
307   // Returns the codec config that is currently selected, or nullptr if
308   // no codec is selected.
getCurrentCodecConfig()309   A2dpCodecConfig* getCurrentCodecConfig() const {
310     return current_codec_config_;
311   }
312 
313   // Selects the codec config.
314   // /!\ Must only be used with offloaded codecs.
setCurrentCodecConfig(A2dpCodecConfig * codec_config)315   void setCurrentCodecConfig(A2dpCodecConfig* codec_config) {
316     std::lock_guard<std::recursive_mutex> lock(codec_mutex_);
317     current_codec_config_ = codec_config;
318   }
319 
320   // Gets the list of Source codecs ordered by priority: higher priority first.
orderedSourceCodecs()321   const std::list<A2dpCodecConfig*> orderedSourceCodecs() const {
322     return ordered_source_codecs_;
323   }
324 
325   // Gets the list of Sink codecs ordered by priority: higher priority first.
orderedSinkCodecs()326   const std::list<A2dpCodecConfig*> orderedSinkCodecs() const {
327     return ordered_sink_codecs_;
328   }
329 
330   // Sets the A2DP Source-to-Sink codec configuration to be used
331   // with a peer Sink device.
332   // |p_peer_codec_info| is the peer's A2DP Sink codec information
333   // to use. If |is_capability| is true, then |p_peer_codec_info| contains the
334   // peer's A2DP Sink codec capability, otherwise it contains the peer's
335   // preferred A2DP codec configuration to use.
336   // If the codec can be used and |select_current_codec| is true, then
337   // this codec is selected as the current one.
338   //
339   // The codec configuration is built by considering the optional user
340   // configuration, the local codec capabilities, the peer's codec
341   // capabilities, and the codec's locally-defined default values.
342   // For each codec parameter:
343   //
344   // 1. If it is user-configurable parameter (sample rate, bits per sample,
345   //    channel mode, and some codec-specific parameters),
346   //    if the user has an explicit preference, and that preference
347   //    is supported by both the local and remote device, this is the
348   //    parameter value that is used.
349   // 2. Otherwise, if the explicit internal default value is supported
350   //    by both the local and remote device, this is the parameter value
351   //    that is used.
352   // 3. Otherwise, the best match is chosen among all values supported by
353   //    the local and remote device.
354   //
355   // In addition, the codec's internal state is updated to reflect
356   // the capabilities that are advertised to the upstream audio source
357   // (Media Framework) to make run-time audio parameter choices:
358   // 4. If the user-configurable parameter was selected, this is the
359   //    only parameter value that is advertised to the Media Framework.
360   // 5. Otherwise, all values supported by both the local and remote
361   //    devices are advertised to the Media Framework.
362   //
363   // The result codec configuration is stored in |p_result_codec_config|.
364   // Returns true on success, othewise false.
365   bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability,
366                       uint8_t* p_result_codec_config,
367                       bool select_current_codec);
368 
369   // Sets the A2DP Sink codec configuration to be used with a peer Source
370   // device.
371   // [See setCodecConfig() for description]
372   bool setSinkCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability,
373                           uint8_t* p_result_codec_config,
374                           bool select_current_codec);
375 
376   // Sets the user prefered codec configuration.
377   // |codec_user_config| contains the preferred codec configuration.
378   // |p_peer_params| contains the A2DP peer information.
379   // |p_peer_sink_capabilities| is the peer's A2DP Sink codec capabilities
380   // to use.
381   // If there is a change in the encoder configuration that requires restarting
382   // the audio input stream, flag |p_restart_input| is set to true.
383   // If there is a change in the encoder configuration that requires restarting
384   // of the A2DP connection, flag |p_restart_output| is set to true, and the
385   // new codec is stored in |p_result_codec_config|.
386   // If there is any change in the codec configuration, flag |p_config_updated|
387   // is set to true.
388   // Returns true on success, otherwise false.
389   bool setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config,
390                           const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
391                           const uint8_t* p_peer_sink_capabilities,
392                           uint8_t* p_result_codec_config, bool* p_restart_input,
393                           bool* p_restart_output, bool* p_config_updated);
394 
395   // Sets the Audio HAL selected audio feeding parameters.
396   // Those parameters are applied only to the currently selected codec.
397   // |codec_audio_config| contains the selected audio feeding configuration.
398   // |p_peer_params| contains the A2DP peer information.
399   // |p_peer_sink_capabilities| is the peer's A2DP Sink codec capabilities
400   // to use.
401   // If there is a change in the encoder configuration that requires restarting
402   // of the A2DP connection, flag |p_restart_output| is set to true, and the
403   // new codec is stored in |p_result_codec_config|.
404   // If there is any change in the codec configuration, flag |p_config_updated|
405   // is set to true.
406   // Returns true on success, otherwise false.
407   bool setCodecAudioConfig(const btav_a2dp_codec_config_t& codec_audio_config,
408                            const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
409                            const uint8_t* p_peer_sink_capabilities,
410                            uint8_t* p_result_codec_config,
411                            bool* p_restart_output, bool* p_config_updated);
412 
413   // Sets the Over-The-Air preferred codec configuration.
414   // The OTA prefered codec configuration is ignored if the current
415   // codec configuration contains explicit user configuration, or if the
416   // codec configuration for the same codec contains explicit user
417   // configuration.
418   // |p_ota_codec_config| contains the received OTA A2DP codec configuration
419   // from the remote peer. Note: this is not the peer codec capability,
420   // but the codec configuration that the peer would like to use.
421   // |p_peer_params| contains the A2DP peer information.
422   // If there is a change in the encoder configuration that requires restarting
423   // the audio input stream, flag |p_restart_input| is set to true.
424   // If there is a change in the encoder configuration that requires restarting
425   // of the A2DP connection, flag |p_restart_output| is set to true, and the
426   // new codec is stored in |p_result_codec_config|.
427   // If there is any change in the codec configuration, flag |p_config_updated|
428   // is set to true.
429   // Returns true on success, otherwise false.
430   bool setCodecOtaConfig(const uint8_t* p_ota_codec_config,
431                          const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
432                          uint8_t* p_result_codec_config, bool* p_restart_input,
433                          bool* p_restart_output, bool* p_config_updated);
434 
435   // Sets the codec capabilities for a Sink peer.
436   // |p_peer_codec_capabiltities| is the peer codec capabilities to set.
437   // Returns true on success, otherwise false.
438   bool setPeerSinkCodecCapabilities(const uint8_t* p_peer_codec_capabilities);
439 
440   // Sets the codec capabilities for a Source peer.
441   // |p_peer_codec_capabiltities| is the peer codec capabilities to set.
442   // Returns true on success, otherwise false.
443   bool setPeerSourceCodecCapabilities(const uint8_t* p_peer_codec_capabilities);
444 
445   // Gets the current codec configuration and the capabilities of
446   // all configured codecs.
447   // The current codec configuration is stored in |p_codec_config|.
448   // Local device's codecs capabilities are stored in
449   // |p_codecs_local_capabilities|.
450   // The codecs capabilities that can be used between the local device
451   // and the remote device are stored in |p_codecs_selectable_capabilities|.
452   // Returns true on success, otherwise false.
453   bool getCodecConfigAndCapabilities(
454       btav_a2dp_codec_config_t* p_codec_config,
455       std::vector<btav_a2dp_codec_config_t>* p_codecs_local_capabilities,
456       std::vector<btav_a2dp_codec_config_t>* p_codecs_selectable_capabilities);
457 
458   // Dumps codec-related information.
459   // The information is written in user-friendly form to file descriptor |fd|.
460   void debug_codec_dump(int fd);
461 
462  private:
463   struct CompareBtBdaddr {
operatorCompareBtBdaddr464     bool operator()(const RawAddress& lhs, const RawAddress& rhs) const {
465       return (memcmp(&lhs, &rhs, sizeof(lhs)) < 0);
466     }
467   };
468   typedef std::map<btav_a2dp_codec_index_t, A2dpCodecConfig*> IndexedCodecs;
469 
470   std::recursive_mutex codec_mutex_;
471   A2dpCodecConfig* current_codec_config_;  // Currently selected codec
472   std::map<btav_a2dp_codec_index_t, btav_a2dp_codec_priority_t>
473       codec_priorities_;
474 
475   IndexedCodecs indexed_codecs_;           // The codecs indexed by codec index
476   IndexedCodecs disabled_codecs_;          // The disabled codecs
477 
478   // A2DP Source codecs ordered by priority
479   std::list<A2dpCodecConfig*> ordered_source_codecs_;
480 
481   // A2DP Sink codecs ordered by priority
482   std::list<A2dpCodecConfig*> ordered_sink_codecs_;
483 
484   std::map<RawAddress, IndexedCodecs*, CompareBtBdaddr> peer_codecs_;
485 };
486 
487 /**
488  * Structure used to configure the A2DP feeding.
489  */
490 typedef struct {
491   tA2DP_SAMPLE_RATE sample_rate;          // 44100, 48000, etc
492   tA2DP_BITS_PER_SAMPLE bits_per_sample;  // 8, 16, 24, 32
493   tA2DP_CHANNEL_COUNT channel_count;      // 1 for mono or 2 for stereo
494 } tA2DP_FEEDING_PARAMS;
495 
496 // Prototype for a callback to read audio data for encoding.
497 // |p_buf| is the buffer to store the data. |len| is the number of octets to
498 // read.
499 // Returns the number of octets read.
500 typedef uint32_t (*a2dp_source_read_callback_t)(uint8_t* p_buf, uint32_t len);
501 
502 // Prototype for a callback to enqueue A2DP Source packets for transmission.
503 // |p_buf| is the buffer with the audio data to enqueue. The callback is
504 // responsible for freeing |p_buf|.
505 // |frames_n| is the number of audio frames in |p_buf| - it is used for
506 // statistics purpose.
507 // |num_bytes| is the number of audio bytes in |p_buf| - it is used for
508 // delay reporting.
509 // Returns true if the packet was enqueued, otherwise false.
510 typedef bool (*a2dp_source_enqueue_callback_t)(BT_HDR* p_buf, size_t frames_n,
511                                                uint32_t num_bytes);
512 
513 //
514 // A2DP encoder callbacks interface.
515 //
516 typedef struct {
517   // Initialize the A2DP encoder.
518   // |p_peer_params| contains the A2DP peer information
519   // The current A2DP codec config is in |a2dp_codec_config|.
520   // |read_callback| is the callback for reading the input audio data.
521   // |enqueue_callback| is the callback for enqueueing the encoded audio data.
522   void (*encoder_init)(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params,
523                        A2dpCodecConfig* a2dp_codec_config,
524                        a2dp_source_read_callback_t read_callback,
525                        a2dp_source_enqueue_callback_t enqueue_callback);
526 
527   // Cleanup the A2DP encoder.
528   void (*encoder_cleanup)(void);
529 
530   // Reset the feeding for the A2DP encoder.
531   void (*feeding_reset)(void);
532 
533   // Flush the feeding for the A2DP encoder.
534   void (*feeding_flush)(void);
535 
536   // Get the A2DP encoder interval (in milliseconds).
537   uint64_t (*get_encoder_interval_ms)(void);
538 
539   // Get the A2DP encoded maximum frame size (similar to MTU).
540   int (*get_effective_frame_size)(void);
541 
542   // Prepare and send A2DP encoded frames.
543   // |timestamp_us| is the current timestamp (in microseconds).
544   void (*send_frames)(uint64_t timestamp_us);
545 
546   // Set transmit queue length for the A2DP encoder.
547   void (*set_transmit_queue_length)(size_t transmit_queue_length);
548 } tA2DP_ENCODER_INTERFACE;
549 
550 // Prototype for a callback to receive decoded audio data from a
551 // tA2DP_DECODER_INTERFACE|.
552 // |buf| is a pointer to the data.
553 // |len| is the number of octets pointed to by |buf|.
554 typedef void (*decoded_data_callback_t)(uint8_t* buf, uint32_t len);
555 
556 //
557 // A2DP decoder callbacks interface.
558 //
559 typedef struct {
560   // Initialize the decoder. Can be called multiple times, will reinitalize.
561   bool (*decoder_init)(decoded_data_callback_t decode_callback);
562 
563   // Cleanup the A2DP decoder.
564   void (*decoder_cleanup)();
565 
566   // Decodes |p_buf| and calls |decode_callback| passed into init for the
567   // decoded data.
568   bool (*decode_packet)(BT_HDR* p_buf);
569 
570   // Start the A2DP decoder.
571   void (*decoder_start)();
572 
573   // Suspend the A2DP decoder.
574   void (*decoder_suspend)();
575 
576   // A2DP decoder configuration.
577   void (*decoder_configure)(const uint8_t* p_codec_info);
578 } tA2DP_DECODER_INTERFACE;
579 
580 // Gets the A2DP codec type.
581 // |p_codec_info| contains information about the codec capabilities.
582 tA2DP_CODEC_TYPE A2DP_GetCodecType(const uint8_t* p_codec_info);
583 
584 // Checks whether the codec capabilities contain a valid A2DP Source codec.
585 // NOTE: only codecs that are implemented are considered valid.
586 // Returns true if |p_codec_info| contains information about a valid codec,
587 // otherwise false.
588 bool A2DP_IsSourceCodecValid(const uint8_t* p_codec_info);
589 
590 // Checks whether the codec capabilities contain a valid A2DP Sink codec.
591 // NOTE: only codecs that are implemented are considered valid.
592 // Returns true if |p_codec_info| contains information about a valid codec,
593 // otherwise false.
594 bool A2DP_IsSinkCodecValid(const uint8_t* p_codec_info);
595 
596 // Checks whether the codec capabilities contain a valid peer A2DP Source
597 // codec.
598 // NOTE: only codecs that are implemented are considered valid.
599 // Returns true if |p_codec_info| contains information about a valid codec,
600 // otherwise false.
601 bool A2DP_IsPeerSourceCodecValid(const uint8_t* p_codec_info);
602 
603 // Checks whether the codec capabilities contain a valid peer A2DP Sink codec.
604 // NOTE: only codecs that are implemented are considered valid.
605 // Returns true if |p_codec_info| contains information about a valid codec,
606 // otherwise false.
607 bool A2DP_IsPeerSinkCodecValid(const uint8_t* p_codec_info);
608 
609 // Checks whether an A2DP Sink codec is supported.
610 // |p_codec_info| contains information about the codec capabilities.
611 // Returns true if the A2DP Sink codec is supported, otherwise false.
612 bool A2DP_IsSinkCodecSupported(const uint8_t* p_codec_info);
613 
614 // Gets peer sink endpoint codec type.
615 // |p_codec_info| contains information about the codec capabilities.
616 int A2DP_IotGetPeerSinkCodecType(const uint8_t* p_codec_info);
617 
618 // Checks whether an A2DP Source codec for a peer Source device is supported.
619 // |p_codec_info| contains information about the codec capabilities of the
620 // peer device.
621 // Returns true if the A2DP Source codec for a peer Source device is supported,
622 // otherwise false.
623 bool A2DP_IsPeerSourceCodecSupported(const uint8_t* p_codec_info);
624 
625 // Initialize state with the default A2DP codec.
626 // The initialized state with the codec capabilities is stored in
627 // |p_codec_info|.
628 void A2DP_InitDefaultCodec(uint8_t* p_codec_info);
629 
630 // Checks whether the A2DP data packets should contain RTP header.
631 // |content_protection_enabled| is true if Content Protection is
632 // enabled. |p_codec_info| contains information about the codec capabilities.
633 // Returns true if the A2DP data packets should contain RTP header, otherwise
634 // false.
635 bool A2DP_UsesRtpHeader(bool content_protection_enabled,
636                         const uint8_t* p_codec_info);
637 
638 // Gets the |AVDT_MEDIA_TYPE_*| media type from the codec capability
639 // in |p_codec_info|.
640 uint8_t A2DP_GetMediaType(const uint8_t* p_codec_info);
641 
642 // Gets the A2DP codec name for a given |p_codec_info|.
643 const char* A2DP_CodecName(const uint8_t* p_codec_info);
644 
645 // Checks whether two A2DP codecs |p_codec_info_a| and |p_codec_info_b| have
646 // the same type.
647 // Returns true if the two codecs have the same type, otherwise false.
648 // If the codec type is not recognized, the return value is false.
649 bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a,
650                           const uint8_t* p_codec_info_b);
651 
652 // Checks whether two A2DP codecs p_codec_info_a| and |p_codec_info_b| are
653 // exactly the same.
654 // Returns true if the two codecs are exactly the same, otherwise false.
655 // If the codec type is not recognized, the return value is false.
656 bool A2DP_CodecEquals(const uint8_t* p_codec_info_a,
657                       const uint8_t* p_codec_info_b);
658 
659 // Gets the track sample rate value for the A2DP codec.
660 // |p_codec_info| is a pointer to the codec_info to decode.
661 // Returns the track sample rate on success, or -1 if |p_codec_info|
662 // contains invalid codec information.
663 int A2DP_GetTrackSampleRate(const uint8_t* p_codec_info);
664 
665 // Gets the track bits per sample value for the A2DP codec.
666 // |p_codec_info| is a pointer to the codec_info to decode.
667 // Returns the track bits per sample on success, or -1 if |p_codec_info|
668 // contains invalid codec information.
669 int A2DP_GetTrackBitsPerSample(const uint8_t* p_codec_info);
670 
671 // Gets the channel count for the A2DP codec.
672 // |p_codec_info| is a pointer to the codec_info to decode.
673 // Returns the channel count on success, or -1 if |p_codec_info|
674 // contains invalid codec information.
675 int A2DP_GetTrackChannelCount(const uint8_t* p_codec_info);
676 
677 // Gets the channel type for the A2DP Sink codec:
678 // 1 for mono, or 3 for dual/stereo/joint.
679 // |p_codec_info| is a pointer to the codec_info to decode.
680 // Returns the channel type on success, or -1 if |p_codec_info|
681 // contains invalid codec information.
682 int A2DP_GetSinkTrackChannelType(const uint8_t* p_codec_info);
683 
684 // Gets the A2DP audio data timestamp from an audio packet.
685 // |p_codec_info| contains the codec information.
686 // |p_data| contains the audio data.
687 // The timestamp is stored in |p_timestamp|.
688 // Returns true on success, otherwise false.
689 bool A2DP_GetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data,
690                              uint32_t* p_timestamp);
691 
692 // Builds A2DP codec header for audio data.
693 // |p_codec_info| contains the codec information.
694 // |p_buf| contains the audio data.
695 // |frames_per_packet| is the number of frames in this packet.
696 // Returns true on success, otherwise false.
697 bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf,
698                            uint16_t frames_per_packet);
699 
700 // Gets the A2DP encoder interface that can be used to encode and prepare
701 // A2DP packets for transmission - see |tA2DP_ENCODER_INTERFACE|.
702 // |p_codec_info| contains the codec information.
703 // Returns the A2DP encoder interface if the |p_codec_info| is valid and
704 // supported, otherwise NULL.
705 const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface(
706     const uint8_t* p_codec_info);
707 
708 // Gets the A2DP decoder interface that can be used to decode received A2DP
709 // packets - see |tA2DP_DECODER_INTERFACE|.
710 // |p_codec_info| contains the codec information.
711 // Returns the A2DP decoder interface if the |p_codec_info| is valid and
712 // supported, otherwise NULL.
713 const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface(
714     const uint8_t* p_codec_info);
715 
716 // Adjusts the A2DP codec, based on local support and Bluetooth specification.
717 // |p_codec_info| contains the codec information to adjust.
718 // Returns true if |p_codec_info| is valid and supported, otherwise false.
719 bool A2DP_AdjustCodec(uint8_t* p_codec_info);
720 
721 // Gets the A2DP Source codec index for a given |p_codec_info|.
722 // Returns the corresponding |btav_a2dp_codec_index_t| on success,
723 // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|.
724 btav_a2dp_codec_index_t A2DP_SourceCodecIndex(const uint8_t* p_codec_info);
725 
726 // Gets the A2DP Sink codec index for a given |p_codec_info|.
727 // Returns the corresponding |btav_a2dp_codec_index_t| on success,
728 // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|.
729 btav_a2dp_codec_index_t A2DP_SinkCodecIndex(const uint8_t* p_codec_info);
730 
731 // Gets the A2DP codec name for a given |codec_index|.
732 const char* A2DP_CodecIndexStr(btav_a2dp_codec_index_t codec_index);
733 
734 // Initializes A2DP codec-specific information into |AvdtpSepConfig|
735 // configuration entry pointed by |p_cfg|. The selected codec is defined
736 // by |codec_index|.
737 // Returns true on success, otherwise false.
738 bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index,
739                           AvdtpSepConfig* p_cfg);
740 
741 // Gets the A2DP effective frame size that each encoded media frame should not
742 // exceed this value.
743 // |p_codec_info| contains the codec information.
744 // Returns the effective frame size if the encoder is configured with this
745 // |p_codec_info|, otherwise 0.
746 int A2DP_GetEecoderEffectiveFrameSize(const uint8_t* p_codec_info);
747 
748 // Decodes A2DP codec info into a human readable string.
749 // |p_codec_info| is a pointer to the codec_info to decode.
750 // Returns a string describing the codec information.
751 std::string A2DP_CodecInfoString(const uint8_t* p_codec_info);
752 
753 // Add enum-based flag operators to the btav_a2dp_codec_config_t fields
754 #ifndef DEFINE_ENUM_FLAG_OPERATORS
755 // Use NOLINT to suppress missing parentheses warnings around bitmask.
756 #define DEFINE_ENUM_FLAG_OPERATORS(bitmask)                                 \
757   extern "C++" {                                                            \
758   inline constexpr bitmask operator&(bitmask X, bitmask Y) {  /* NOLINT */  \
759     return static_cast<bitmask>(static_cast<int>(X) & static_cast<int>(Y)); \
760   }                                                                         \
761   inline constexpr bitmask operator|(bitmask X, bitmask Y) {  /* NOLINT */  \
762     return static_cast<bitmask>(static_cast<int>(X) | static_cast<int>(Y)); \
763   }                                                                         \
764   inline constexpr bitmask operator^(bitmask X, bitmask Y) {  /* NOLINT */  \
765     return static_cast<bitmask>(static_cast<int>(X) ^ static_cast<int>(Y)); \
766   }                                                                         \
767   inline constexpr bitmask operator~(bitmask X) {             /* NOLINT */  \
768     return static_cast<bitmask>(~static_cast<int>(X));                      \
769   }                                                                         \
770   inline bitmask& operator&=(bitmask& X, bitmask Y) {         /* NOLINT */  \
771     X = X & Y;                                                              \
772     return X;                                                               \
773   }                                                                         \
774   inline bitmask& operator|=(bitmask& X, bitmask Y) {         /* NOLINT */  \
775     X = X | Y;                                                              \
776     return X;                                                               \
777   }                                                                         \
778   inline bitmask& operator^=(bitmask& X, bitmask Y) {         /* NOLINT */  \
779     X = X ^ Y;                                                              \
780     return X;                                                               \
781   }                                                                         \
782   }
783 #endif  // DEFINE_ENUM_FLAG_OPERATORS
784 DEFINE_ENUM_FLAG_OPERATORS(btav_a2dp_codec_sample_rate_t);
785 DEFINE_ENUM_FLAG_OPERATORS(btav_a2dp_codec_bits_per_sample_t);
786 DEFINE_ENUM_FLAG_OPERATORS(btav_a2dp_codec_channel_mode_t);
787 
788 #endif  // A2DP_CODEC_API_H
789