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