• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2009-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /*****************************************************************************
20  *
21  *  Filename:      audio_a2dp_hw.c
22  *
23  *  Description:   Implements hal for bluedroid a2dp audio device
24  *
25  *****************************************************************************/
26 
27 #define LOG_TAG "bt_a2dp_hw"
28 
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <inttypes.h>
32 #include <log/log.h>
33 #include <stdint.h>
34 #include <sys/errno.h>
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/un.h>
39 #include <unistd.h>
40 
41 #include <mutex>
42 
43 #include <hardware/audio.h>
44 #include <hardware/hardware.h>
45 #include <system/audio.h>
46 
47 #include "osi/include/hash_map_utils.h"
48 #include "osi/include/osi.h"
49 #include "osi/include/socket_utils/sockets.h"
50 
51 #include "audio_a2dp_hw.h"
52 
53 /*****************************************************************************
54  *  Constants & Macros
55  *****************************************************************************/
56 
57 #define CTRL_CHAN_RETRY_COUNT 3
58 #define USEC_PER_SEC 1000000L
59 #define SOCK_SEND_TIMEOUT_MS 2000 /* Timeout for sending */
60 #define SOCK_RECV_TIMEOUT_MS 5000 /* Timeout for receiving */
61 #define SEC_TO_MS 1000
62 #define SEC_TO_NS 1000000000
63 #define MS_TO_NS 1000000
64 #define DELAY_TO_NS 100000
65 
66 #define MIN_DELAY_MS 100
67 #define MAX_DELAY_MS 1000
68 
69 // set WRITE_POLL_MS to 0 for blocking sockets, nonzero for polled non-blocking
70 // sockets
71 #define WRITE_POLL_MS 20
72 
73 #define FNLOG() ALOGV("%s:%d %s: ", __FILE__, __LINE__, __func__)
74 #define DEBUG(fmt, args...) \
75   ALOGD("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args)
76 #define INFO(fmt, args...) \
77   ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args)
78 #define WARN(fmt, args...) \
79   ALOGW("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args)
80 #define ERROR(fmt, args...) \
81   ALOGE("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args)
82 
83 #define ASSERTC(cond, msg, val)                                           \
84   if (!(cond)) {                                                          \
85     ERROR("### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, \
86           val);                                                           \
87   }
88 
89 /*****************************************************************************
90  *  Local type definitions
91  *****************************************************************************/
92 
93 typedef enum {
94   AUDIO_A2DP_STATE_STARTING,
95   AUDIO_A2DP_STATE_STARTED,
96   AUDIO_A2DP_STATE_STOPPING,
97   AUDIO_A2DP_STATE_STOPPED,
98   /* need explicit set param call to resume (suspend=false) */
99   AUDIO_A2DP_STATE_SUSPENDED,
100   AUDIO_A2DP_STATE_STANDBY /* allows write to autoresume */
101 } a2dp_state_t;
102 
103 struct a2dp_stream_in;
104 struct a2dp_stream_out;
105 
106 struct a2dp_audio_device {
107   // Important: device must be first as an audio_hw_device* may be cast to
108   // a2dp_audio_device* when the type is implicitly known.
109   struct audio_hw_device device;
110   std::recursive_mutex* mutex;  // See note below on mutex acquisition order.
111   struct a2dp_stream_in* input;
112   struct a2dp_stream_out* output;
113 };
114 
115 struct a2dp_config {
116   uint32_t rate;
117   audio_channel_mask_t channel_mask;
118   bool is_stereo_to_mono;  // True if fetching Stereo and mixing into Mono
119   int format;
120 };
121 
122 /* move ctrl_fd outside output stream and keep open until HAL unloaded ? */
123 
124 struct a2dp_stream_common {
125   std::recursive_mutex* mutex;  // See note below on mutex acquisition order.
126   int ctrl_fd;
127   int audio_fd;
128   size_t buffer_sz;
129   struct a2dp_config cfg;
130   a2dp_state_t state;
131 };
132 
133 struct a2dp_stream_out {
134   struct audio_stream_out stream;
135   struct a2dp_stream_common common;
136   uint64_t frames_presented;  // frames written, never reset
137   uint64_t frames_rendered;   // frames written, reset on standby
138 };
139 
140 struct a2dp_stream_in {
141   struct audio_stream_in stream;
142   struct a2dp_stream_common common;
143 };
144 
145 /*
146  * Mutex acquisition order:
147  *
148  * The a2dp_audio_device (adev) mutex must be acquired before
149  * the a2dp_stream_common (out or in) mutex.
150  *
151  * This may differ from other audio HALs.
152  */
153 
154 /*****************************************************************************
155  *  Static variables
156  *****************************************************************************/
157 
158 static bool enable_delay_reporting = false;
159 
160 /*****************************************************************************
161  *  Static functions
162  *****************************************************************************/
163 
164 static size_t out_get_buffer_size(const struct audio_stream* stream);
165 static uint32_t out_get_latency(const struct audio_stream_out* stream);
166 
167 /*****************************************************************************
168  *  Externs
169  *****************************************************************************/
170 
171 /*****************************************************************************
172  *  Functions
173  *****************************************************************************/
174 static void a2dp_open_ctrl_path(struct a2dp_stream_common* common);
175 
176 /*****************************************************************************
177  *   Miscellaneous helper functions
178  *****************************************************************************/
hash_map_utils_dump_string_keys_string_values(std::unordered_map<std::string,std::string> & map)179 static void hash_map_utils_dump_string_keys_string_values(
180     std::unordered_map<std::string, std::string>& map) {
181   for (const auto& ptr : map) {
182     INFO("key: '%s' value: '%s'\n", ptr.first.c_str(), ptr.second.c_str());
183   }
184 }
185 
186 /* logs timestamp with microsec precision
187    pprev is optional in case a dedicated diff is required */
ts_log(UNUSED_ATTR const char * tag,UNUSED_ATTR int val,struct timespec * pprev_opt)188 static void ts_log(UNUSED_ATTR const char* tag, UNUSED_ATTR int val,
189                    struct timespec* pprev_opt) {
190   struct timespec now;
191   static struct timespec prev = {0, 0};
192   unsigned long long now_us;
193   unsigned long long diff_us;
194 
195   clock_gettime(CLOCK_MONOTONIC, &now);
196 
197   now_us = now.tv_sec * USEC_PER_SEC + now.tv_nsec / 1000;
198 
199   if (pprev_opt) {
200     diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC +
201               (now.tv_nsec - prev.tv_nsec) / 1000;
202     *pprev_opt = now;
203     DEBUG("[%s] ts %08lld, *diff %08lld, val %d", tag, now_us, diff_us, val);
204   } else {
205     diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC +
206               (now.tv_nsec - prev.tv_nsec) / 1000;
207     prev = now;
208     DEBUG("[%s] ts %08lld, diff %08lld, val %d", tag, now_us, diff_us, val);
209   }
210 }
211 
calc_audiotime_usec(struct a2dp_config cfg,int bytes)212 static int calc_audiotime_usec(struct a2dp_config cfg, int bytes) {
213   int chan_count = audio_channel_count_from_out_mask(cfg.channel_mask);
214   int bytes_per_sample;
215 
216   switch (cfg.format) {
217     case AUDIO_FORMAT_PCM_8_BIT:
218       bytes_per_sample = 1;
219       break;
220     case AUDIO_FORMAT_PCM_16_BIT:
221       bytes_per_sample = 2;
222       break;
223     case AUDIO_FORMAT_PCM_24_BIT_PACKED:
224       bytes_per_sample = 3;
225       break;
226     case AUDIO_FORMAT_PCM_8_24_BIT:
227       bytes_per_sample = 4;
228       break;
229     case AUDIO_FORMAT_PCM_32_BIT:
230       bytes_per_sample = 4;
231       break;
232     default:
233       ASSERTC(false, "unsupported sample format", cfg.format);
234       bytes_per_sample = 2;
235       break;
236   }
237 
238   return (
239       int)(((int64_t)bytes * (USEC_PER_SEC / (chan_count * bytes_per_sample))) /
240            cfg.rate);
241 }
242 
243 /*****************************************************************************
244  *
245  *   bluedroid stack adaptation
246  *
247  ****************************************************************************/
248 
skt_connect(const char * path,size_t buffer_sz)249 static int skt_connect(const char* path, size_t buffer_sz) {
250   int ret;
251   int skt_fd;
252   int len;
253 
254   INFO("connect to %s (sz %zu)", path, buffer_sz);
255 
256   skt_fd = socket(AF_LOCAL, SOCK_STREAM, 0);
257 
258   if (osi_socket_local_client_connect(
259           skt_fd, path, ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM) < 0) {
260     ERROR("failed to connect (%s)", strerror(errno));
261     close(skt_fd);
262     return -1;
263   }
264 
265   len = buffer_sz;
266   ret =
267       setsockopt(skt_fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, (int)sizeof(len));
268   if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno));
269 
270   ret =
271       setsockopt(skt_fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, (int)sizeof(len));
272   if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno));
273 
274   /* Socket send/receive timeout value */
275   struct timeval tv;
276   tv.tv_sec = SOCK_SEND_TIMEOUT_MS / 1000;
277   tv.tv_usec = (SOCK_SEND_TIMEOUT_MS % 1000) * 1000;
278 
279   ret = setsockopt(skt_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
280   if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno));
281 
282   tv.tv_sec = SOCK_RECV_TIMEOUT_MS / 1000;
283   tv.tv_usec = (SOCK_RECV_TIMEOUT_MS % 1000) * 1000;
284 
285   ret = setsockopt(skt_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
286   if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno));
287 
288   INFO("connected to stack fd = %d", skt_fd);
289 
290   return skt_fd;
291 }
292 
skt_read(int fd,void * p,size_t len)293 static int skt_read(int fd, void* p, size_t len) {
294   ssize_t read;
295 
296   FNLOG();
297 
298   ts_log("skt_read recv", len, NULL);
299 
300   OSI_NO_INTR(read = recv(fd, p, len, MSG_NOSIGNAL));
301   if (read == -1) ERROR("read failed with errno=%d\n", errno);
302 
303   return (int)read;
304 }
305 
skt_write(int fd,const void * p,size_t len)306 static int skt_write(int fd, const void* p, size_t len) {
307   ssize_t sent;
308   FNLOG();
309 
310   ts_log("skt_write", len, NULL);
311 
312   if (WRITE_POLL_MS == 0) {
313     // do not poll, use blocking send
314     OSI_NO_INTR(sent = send(fd, p, len, MSG_NOSIGNAL));
315     if (sent == -1) ERROR("write failed with error(%s)", strerror(errno));
316 
317     return (int)sent;
318   }
319 
320   // use non-blocking send, poll
321   int ms_timeout = SOCK_SEND_TIMEOUT_MS;
322   size_t count = 0;
323   while (count < len) {
324     OSI_NO_INTR(sent = send(fd, p, len - count, MSG_NOSIGNAL | MSG_DONTWAIT));
325     if (sent == -1) {
326       if (errno != EAGAIN && errno != EWOULDBLOCK) {
327         ERROR("write failed with error(%s)", strerror(errno));
328         return -1;
329       }
330       if (ms_timeout >= WRITE_POLL_MS) {
331         usleep(WRITE_POLL_MS * 1000);
332         ms_timeout -= WRITE_POLL_MS;
333         continue;
334       }
335       WARN("write timeout exceeded, sent %zu bytes", count);
336       return -1;
337     }
338     count += sent;
339     p = (const uint8_t*)p + sent;
340   }
341   return (int)count;
342 }
343 
skt_disconnect(int fd)344 static int skt_disconnect(int fd) {
345   INFO("fd %d", fd);
346 
347   if (fd != AUDIO_SKT_DISCONNECTED) {
348     shutdown(fd, SHUT_RDWR);
349     close(fd);
350   }
351   return 0;
352 }
353 
354 /*****************************************************************************
355  *
356  *  AUDIO CONTROL PATH
357  *
358  ****************************************************************************/
359 
a2dp_ctrl_receive(struct a2dp_stream_common * common,void * buffer,size_t length)360 static int a2dp_ctrl_receive(struct a2dp_stream_common* common, void* buffer,
361                              size_t length) {
362   ssize_t ret;
363   int i;
364 
365   for (i = 0;; i++) {
366     OSI_NO_INTR(ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
367     if (ret > 0) {
368       break;
369     }
370     if (ret == 0) {
371       ERROR("receive control data failed: peer closed");
372       break;
373     }
374     if (errno != EWOULDBLOCK && errno != EAGAIN) {
375       ERROR("receive control data failed: error(%s)", strerror(errno));
376       break;
377     }
378     if (i == (CTRL_CHAN_RETRY_COUNT - 1)) {
379       ERROR("receive control data failed: max retry count");
380       break;
381     }
382     INFO("receive control data failed (%s), retrying", strerror(errno));
383   }
384   if (ret <= 0) {
385     skt_disconnect(common->ctrl_fd);
386     common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
387   }
388   return ret;
389 }
390 
391 // Sends control info for stream |common|. The data to send is stored in
392 // |buffer| and has size |length|.
393 // On success, returns the number of octets sent, otherwise -1.
a2dp_ctrl_send(struct a2dp_stream_common * common,const void * buffer,size_t length)394 static int a2dp_ctrl_send(struct a2dp_stream_common* common, const void* buffer,
395                           size_t length) {
396   ssize_t sent;
397   size_t remaining = length;
398   int i;
399 
400   if (length == 0) return 0;  // Nothing to do
401 
402   for (i = 0;; i++) {
403     OSI_NO_INTR(sent = send(common->ctrl_fd, buffer, remaining, MSG_NOSIGNAL));
404     if (sent == static_cast<ssize_t>(remaining)) {
405       remaining = 0;
406       break;
407     }
408     if (sent > 0) {
409       buffer = (static_cast<const char*>(buffer) + sent);
410       remaining -= sent;
411       continue;
412     }
413     if (sent < 0) {
414       if (errno != EWOULDBLOCK && errno != EAGAIN) {
415         ERROR("send control data failed: error(%s)", strerror(errno));
416         break;
417       }
418       INFO("send control data failed (%s), retrying", strerror(errno));
419     }
420     if (i >= (CTRL_CHAN_RETRY_COUNT - 1)) {
421       ERROR("send control data failed: max retry count");
422       break;
423     }
424   }
425   if (remaining > 0) {
426     skt_disconnect(common->ctrl_fd);
427     common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
428     return -1;
429   }
430   return length;
431 }
432 
a2dp_command(struct a2dp_stream_common * common,tA2DP_CTRL_CMD cmd)433 static int a2dp_command(struct a2dp_stream_common* common, tA2DP_CTRL_CMD cmd) {
434   char ack;
435 
436   DEBUG("A2DP COMMAND %s", audio_a2dp_hw_dump_ctrl_event(cmd));
437 
438   if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED) {
439     INFO("starting up or recovering from previous error: command=%s",
440          audio_a2dp_hw_dump_ctrl_event(cmd));
441     a2dp_open_ctrl_path(common);
442     if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED) {
443       ERROR("failure to open ctrl path: command=%s",
444             audio_a2dp_hw_dump_ctrl_event(cmd));
445       return -1;
446     }
447   }
448 
449   /* send command */
450   ssize_t sent;
451   OSI_NO_INTR(sent = send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL));
452   if (sent == -1) {
453     ERROR("cmd failed (%s): command=%s", strerror(errno),
454           audio_a2dp_hw_dump_ctrl_event(cmd));
455     skt_disconnect(common->ctrl_fd);
456     common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
457     return -1;
458   }
459 
460   /* wait for ack byte */
461   if (a2dp_ctrl_receive(common, &ack, 1) < 0) {
462     ERROR("A2DP COMMAND %s: no ACK", audio_a2dp_hw_dump_ctrl_event(cmd));
463     return -1;
464   }
465 
466   DEBUG("A2DP COMMAND %s DONE STATUS %d", audio_a2dp_hw_dump_ctrl_event(cmd),
467         ack);
468 
469   if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) {
470     ERROR("A2DP COMMAND %s error %d", audio_a2dp_hw_dump_ctrl_event(cmd), ack);
471     return ack;
472   }
473   if (ack != A2DP_CTRL_ACK_SUCCESS) {
474     ERROR("A2DP COMMAND %s error %d", audio_a2dp_hw_dump_ctrl_event(cmd), ack);
475     return -1;
476   }
477 
478   return 0;
479 }
480 
check_a2dp_ready(struct a2dp_stream_common * common)481 static int check_a2dp_ready(struct a2dp_stream_common* common) {
482   if (a2dp_command(common, A2DP_CTRL_CMD_CHECK_READY) < 0) {
483     ERROR("check a2dp ready failed");
484     return -1;
485   }
486   return 0;
487 }
488 
a2dp_read_input_audio_config(struct a2dp_stream_common * common)489 static int a2dp_read_input_audio_config(struct a2dp_stream_common* common) {
490   tA2DP_SAMPLE_RATE sample_rate;
491   tA2DP_CHANNEL_COUNT channel_count;
492 
493   if (a2dp_command(common, A2DP_CTRL_GET_INPUT_AUDIO_CONFIG) < 0) {
494     ERROR("get a2dp input audio config failed");
495     return -1;
496   }
497 
498   if (a2dp_ctrl_receive(common, &sample_rate, sizeof(tA2DP_SAMPLE_RATE)) < 0)
499     return -1;
500   if (a2dp_ctrl_receive(common, &channel_count, sizeof(tA2DP_CHANNEL_COUNT)) <
501       0) {
502     return -1;
503   }
504 
505   switch (sample_rate) {
506     case 44100:
507     case 48000:
508       common->cfg.rate = sample_rate;
509       break;
510     default:
511       ERROR("Invalid sample rate: %" PRIu32, sample_rate);
512       return -1;
513   }
514 
515   switch (channel_count) {
516     case 1:
517       common->cfg.channel_mask = AUDIO_CHANNEL_IN_MONO;
518       break;
519     case 2:
520       common->cfg.channel_mask = AUDIO_CHANNEL_IN_STEREO;
521       break;
522     default:
523       ERROR("Invalid channel count: %" PRIu32, channel_count);
524       return -1;
525   }
526 
527   // TODO: For now input audio format is always hard-coded as PCM 16-bit
528   common->cfg.format = AUDIO_FORMAT_PCM_16_BIT;
529 
530   INFO("got input audio config %d %d", common->cfg.format, common->cfg.rate);
531 
532   return 0;
533 }
534 
a2dp_read_output_audio_config(struct a2dp_stream_common * common,btav_a2dp_codec_config_t * codec_config,btav_a2dp_codec_config_t * codec_capability,bool update_stream_config)535 static int a2dp_read_output_audio_config(
536     struct a2dp_stream_common* common, btav_a2dp_codec_config_t* codec_config,
537     btav_a2dp_codec_config_t* codec_capability, bool update_stream_config) {
538   struct a2dp_config stream_config;
539 
540   if (a2dp_command(common, A2DP_CTRL_GET_OUTPUT_AUDIO_CONFIG) < 0) {
541     ERROR("get a2dp output audio config failed");
542     return -1;
543   }
544 
545   // Receive the current codec config
546   if (a2dp_ctrl_receive(common, &codec_config->sample_rate,
547                         sizeof(btav_a2dp_codec_sample_rate_t)) < 0) {
548     return -1;
549   }
550   if (a2dp_ctrl_receive(common, &codec_config->bits_per_sample,
551                         sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) {
552     return -1;
553   }
554   if (a2dp_ctrl_receive(common, &codec_config->channel_mode,
555                         sizeof(btav_a2dp_codec_channel_mode_t)) < 0) {
556     return -1;
557   }
558 
559   // Receive the current codec capability
560   if (a2dp_ctrl_receive(common, &codec_capability->sample_rate,
561                         sizeof(btav_a2dp_codec_sample_rate_t)) < 0) {
562     return -1;
563   }
564   if (a2dp_ctrl_receive(common, &codec_capability->bits_per_sample,
565                         sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) {
566     return -1;
567   }
568   if (a2dp_ctrl_receive(common, &codec_capability->channel_mode,
569                         sizeof(btav_a2dp_codec_channel_mode_t)) < 0) {
570     return -1;
571   }
572 
573   // Check the codec config sample rate
574   switch (codec_config->sample_rate) {
575     case BTAV_A2DP_CODEC_SAMPLE_RATE_44100:
576       stream_config.rate = 44100;
577       break;
578     case BTAV_A2DP_CODEC_SAMPLE_RATE_48000:
579       stream_config.rate = 48000;
580       break;
581     case BTAV_A2DP_CODEC_SAMPLE_RATE_88200:
582       stream_config.rate = 88200;
583       break;
584     case BTAV_A2DP_CODEC_SAMPLE_RATE_96000:
585       stream_config.rate = 96000;
586       break;
587     case BTAV_A2DP_CODEC_SAMPLE_RATE_176400:
588       stream_config.rate = 176400;
589       break;
590     case BTAV_A2DP_CODEC_SAMPLE_RATE_192000:
591       stream_config.rate = 192000;
592       break;
593     case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE:
594     default:
595       ERROR("Invalid sample rate: 0x%x", codec_config->sample_rate);
596       return -1;
597   }
598 
599   // Check the codec config bits per sample
600   switch (codec_config->bits_per_sample) {
601     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
602       stream_config.format = AUDIO_FORMAT_PCM_16_BIT;
603       break;
604     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
605       stream_config.format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
606       break;
607     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
608       stream_config.format = AUDIO_FORMAT_PCM_32_BIT;
609       break;
610     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE:
611     default:
612       ERROR("Invalid bits per sample: 0x%x", codec_config->bits_per_sample);
613       return -1;
614   }
615 
616   // Check the codec config channel mode
617   switch (codec_config->channel_mode) {
618     case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO:
619       stream_config.channel_mask = AUDIO_CHANNEL_OUT_MONO;
620       stream_config.is_stereo_to_mono = true;
621       break;
622     case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO:
623       stream_config.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
624       stream_config.is_stereo_to_mono = false;
625       break;
626     case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE:
627     default:
628       ERROR("Invalid channel mode: 0x%x", codec_config->channel_mode);
629       return -1;
630   }
631   if (stream_config.is_stereo_to_mono) {
632     stream_config.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
633   }
634 
635   // Update the output stream configuration
636   if (update_stream_config) {
637     common->cfg.rate = stream_config.rate;
638     common->cfg.channel_mask = stream_config.channel_mask;
639     common->cfg.is_stereo_to_mono = stream_config.is_stereo_to_mono;
640     common->cfg.format = stream_config.format;
641     common->buffer_sz = audio_a2dp_hw_stream_compute_buffer_size(
642         codec_config->sample_rate, codec_config->bits_per_sample,
643         codec_config->channel_mode);
644     if (common->cfg.is_stereo_to_mono) {
645       // We need to fetch twice as much data from the Audio framework
646       common->buffer_sz *= 2;
647     }
648   }
649 
650   INFO(
651       "got output codec config (update_stream_config=%s): "
652       "sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x",
653       update_stream_config ? "true" : "false", codec_config->sample_rate,
654       codec_config->bits_per_sample, codec_config->channel_mode);
655 
656   INFO(
657       "got output codec capability: sample_rate=0x%x bits_per_sample=0x%x "
658       "channel_mode=0x%x",
659       codec_capability->sample_rate, codec_capability->bits_per_sample,
660       codec_capability->channel_mode);
661 
662   return 0;
663 }
664 
a2dp_write_output_audio_config(struct a2dp_stream_common * common)665 static int a2dp_write_output_audio_config(struct a2dp_stream_common* common) {
666   btav_a2dp_codec_config_t codec_config;
667 
668   if (a2dp_command(common, A2DP_CTRL_SET_OUTPUT_AUDIO_CONFIG) < 0) {
669     ERROR("set a2dp output audio config failed");
670     return -1;
671   }
672 
673   codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
674   codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
675   codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
676 
677   switch (common->cfg.rate) {
678     case 44100:
679       codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_44100;
680       break;
681     case 48000:
682       codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
683       break;
684     case 88200:
685       codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_88200;
686       break;
687     case 96000:
688       codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_96000;
689       break;
690     case 176400:
691       codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_176400;
692       break;
693     case 192000:
694       codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_192000;
695       break;
696     default:
697       ERROR("Invalid sample rate: %" PRIu32, common->cfg.rate);
698       return -1;
699   }
700 
701   switch (common->cfg.format) {
702     case AUDIO_FORMAT_PCM_16_BIT:
703       codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
704       break;
705     case AUDIO_FORMAT_PCM_24_BIT_PACKED:
706       codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
707       break;
708     case AUDIO_FORMAT_PCM_32_BIT:
709       codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
710       break;
711     case AUDIO_FORMAT_PCM_8_24_BIT:
712       // All 24-bit audio is expected in AUDIO_FORMAT_PCM_24_BIT_PACKED format
713       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
714     default:
715       ERROR("Invalid audio format: 0x%x", common->cfg.format);
716       return -1;
717   }
718 
719   switch (common->cfg.channel_mask) {
720     case AUDIO_CHANNEL_OUT_MONO:
721       codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
722       break;
723     case AUDIO_CHANNEL_OUT_STEREO:
724       if (common->cfg.is_stereo_to_mono) {
725         codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
726       } else {
727         codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
728       }
729       break;
730     default:
731       ERROR("Invalid channel mask: 0x%x", common->cfg.channel_mask);
732       return -1;
733   }
734 
735   // Send the current codec config that has been selected by us
736   if (a2dp_ctrl_send(common, &codec_config.sample_rate,
737                      sizeof(btav_a2dp_codec_sample_rate_t)) < 0)
738     return -1;
739   if (a2dp_ctrl_send(common, &codec_config.bits_per_sample,
740                      sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) {
741     return -1;
742   }
743   if (a2dp_ctrl_send(common, &codec_config.channel_mode,
744                      sizeof(btav_a2dp_codec_channel_mode_t)) < 0) {
745     return -1;
746   }
747 
748   INFO(
749       "sent output codec config: sample_rate=0x%x bits_per_sample=0x%x "
750       "channel_mode=0x%x",
751       codec_config.sample_rate, codec_config.bits_per_sample,
752       codec_config.channel_mode);
753 
754   return 0;
755 }
756 
a2dp_get_presentation_position_cmd(struct a2dp_stream_common * common,uint64_t * bytes,uint16_t * delay,struct timespec * timestamp)757 static int a2dp_get_presentation_position_cmd(struct a2dp_stream_common* common,
758                                               uint64_t* bytes, uint16_t* delay,
759                                               struct timespec* timestamp) {
760   if ((common->ctrl_fd == AUDIO_SKT_DISCONNECTED) ||
761       (common->state != AUDIO_A2DP_STATE_STARTED)) {  // Audio is not streaming
762     return -1;
763   }
764 
765   if (a2dp_command(common, A2DP_CTRL_GET_PRESENTATION_POSITION) < 0) {
766     return -1;
767   }
768 
769   if (a2dp_ctrl_receive(common, bytes, sizeof(*bytes)) < 0) {
770     return -1;
771   }
772 
773   if (a2dp_ctrl_receive(common, delay, sizeof(*delay)) < 0) {
774     return -1;
775   }
776 
777   uint32_t seconds;
778   if (a2dp_ctrl_receive(common, &seconds, sizeof(seconds)) < 0) {
779     return -1;
780   }
781 
782   uint32_t nsec;
783   if (a2dp_ctrl_receive(common, &nsec, sizeof(nsec)) < 0) {
784     return -1;
785   }
786 
787   timestamp->tv_sec = seconds;
788   timestamp->tv_nsec = nsec;
789   return 0;
790 }
791 
a2dp_open_ctrl_path(struct a2dp_stream_common * common)792 static void a2dp_open_ctrl_path(struct a2dp_stream_common* common) {
793   int i;
794 
795   if (common->ctrl_fd != AUDIO_SKT_DISCONNECTED) return;  // already connected
796 
797   /* retry logic to catch any timing variations on control channel */
798   for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) {
799     /* connect control channel if not already connected */
800     if ((common->ctrl_fd = skt_connect(
801              A2DP_CTRL_PATH, AUDIO_STREAM_CONTROL_OUTPUT_BUFFER_SZ)) >= 0) {
802       /* success, now check if stack is ready */
803       if (check_a2dp_ready(common) == 0) break;
804 
805       ERROR("error : a2dp not ready, wait 250 ms and retry");
806       usleep(250000);
807       skt_disconnect(common->ctrl_fd);
808       common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
809     }
810 
811     /* ctrl channel not ready, wait a bit */
812     usleep(250000);
813   }
814 }
815 
816 /*****************************************************************************
817  *
818  * AUDIO DATA PATH
819  *
820  ****************************************************************************/
821 
a2dp_stream_common_init(struct a2dp_stream_common * common)822 static void a2dp_stream_common_init(struct a2dp_stream_common* common) {
823   FNLOG();
824 
825   common->mutex = new std::recursive_mutex;
826 
827   common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
828   common->audio_fd = AUDIO_SKT_DISCONNECTED;
829   common->state = AUDIO_A2DP_STATE_STOPPED;
830 
831   /* manages max capacity of socket pipe */
832   common->buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ;
833 }
834 
a2dp_stream_common_destroy(struct a2dp_stream_common * common)835 static void a2dp_stream_common_destroy(struct a2dp_stream_common* common) {
836   FNLOG();
837 
838   delete common->mutex;
839   common->mutex = NULL;
840 }
841 
start_audio_datapath(struct a2dp_stream_common * common)842 static int start_audio_datapath(struct a2dp_stream_common* common) {
843   INFO("state %d", common->state);
844 
845   int oldstate = common->state;
846   common->state = AUDIO_A2DP_STATE_STARTING;
847 
848   int a2dp_status = a2dp_command(common, A2DP_CTRL_CMD_START);
849   if (a2dp_status < 0) {
850     ERROR("Audiopath start failed (status %d)", a2dp_status);
851     goto error;
852   } else if (a2dp_status == A2DP_CTRL_ACK_INCALL_FAILURE) {
853     ERROR("Audiopath start failed - in call, move to suspended");
854     goto error;
855   }
856 
857   /* connect socket if not yet connected */
858   if (common->audio_fd == AUDIO_SKT_DISCONNECTED) {
859     common->audio_fd = skt_connect(A2DP_DATA_PATH, common->buffer_sz);
860     if (common->audio_fd < 0) {
861       ERROR("Audiopath start failed - error opening data socket");
862       goto error;
863     }
864   }
865   common->state = (a2dp_state_t)AUDIO_A2DP_STATE_STARTED;
866 
867   /* check to see if delay reporting is enabled */
868   enable_delay_reporting = delay_reporting_enabled();
869 
870   return 0;
871 
872 error:
873   common->state = (a2dp_state_t)oldstate;
874   return -1;
875 }
876 
stop_audio_datapath(struct a2dp_stream_common * common)877 static int stop_audio_datapath(struct a2dp_stream_common* common) {
878   int oldstate = common->state;
879 
880   INFO("state %d", common->state);
881 
882   /* prevent any stray output writes from autostarting the stream
883      while stopping audiopath */
884   common->state = AUDIO_A2DP_STATE_STOPPING;
885 
886   if (a2dp_command(common, A2DP_CTRL_CMD_STOP) < 0) {
887     ERROR("audiopath stop failed");
888     common->state = (a2dp_state_t)oldstate;
889     return -1;
890   }
891 
892   common->state = (a2dp_state_t)AUDIO_A2DP_STATE_STOPPED;
893 
894   /* disconnect audio path */
895   skt_disconnect(common->audio_fd);
896   common->audio_fd = AUDIO_SKT_DISCONNECTED;
897 
898   return 0;
899 }
900 
suspend_audio_datapath(struct a2dp_stream_common * common,bool standby)901 static int suspend_audio_datapath(struct a2dp_stream_common* common,
902                                   bool standby) {
903   INFO("state %d", common->state);
904 
905   if (common->state == AUDIO_A2DP_STATE_STOPPING) return -1;
906 
907   if (a2dp_command(common, A2DP_CTRL_CMD_SUSPEND) < 0) return -1;
908 
909   if (standby)
910     common->state = AUDIO_A2DP_STATE_STANDBY;
911   else
912     common->state = AUDIO_A2DP_STATE_SUSPENDED;
913 
914   /* disconnect audio path */
915   skt_disconnect(common->audio_fd);
916 
917   common->audio_fd = AUDIO_SKT_DISCONNECTED;
918 
919   return 0;
920 }
921 
922 /*****************************************************************************
923  *
924  *  audio output callbacks
925  *
926  ****************************************************************************/
927 
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)928 static ssize_t out_write(struct audio_stream_out* stream, const void* buffer,
929                          size_t bytes) {
930   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
931   int sent = -1;
932   size_t write_bytes = bytes;
933 
934   DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd);
935 
936   std::unique_lock<std::recursive_mutex> lock(*out->common.mutex);
937   if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED ||
938       out->common.state == AUDIO_A2DP_STATE_STOPPING) {
939     DEBUG("stream suspended or closing");
940     goto finish;
941   }
942 
943   /* only allow autostarting if we are in stopped or standby */
944   if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) ||
945       (out->common.state == AUDIO_A2DP_STATE_STANDBY)) {
946     if (start_audio_datapath(&out->common) < 0) {
947       goto finish;
948     }
949   } else if (out->common.state != AUDIO_A2DP_STATE_STARTED) {
950     ERROR("stream not in stopped or standby");
951     goto finish;
952   }
953 
954   // Mix the stereo into mono if necessary
955   if (out->common.cfg.is_stereo_to_mono) {
956     const size_t frames = bytes / audio_stream_out_frame_size(stream);
957     int16_t* src = (int16_t*)buffer;
958     int16_t* dst = (int16_t*)buffer;
959     for (size_t i = 0; i < frames; i++, dst++, src += 2) {
960       *dst = (int16_t)(((int32_t)src[0] + (int32_t)src[1]) >> 1);
961     }
962     write_bytes /= 2;
963     DEBUG("stereo-to-mono mixing: write %zu bytes (fd %d)", write_bytes,
964           out->common.audio_fd);
965   }
966 
967   lock.unlock();
968   sent = skt_write(out->common.audio_fd, buffer, write_bytes);
969   lock.lock();
970 
971   if (sent == -1) {
972     skt_disconnect(out->common.audio_fd);
973     out->common.audio_fd = AUDIO_SKT_DISCONNECTED;
974     if ((out->common.state != AUDIO_A2DP_STATE_SUSPENDED) &&
975         (out->common.state != AUDIO_A2DP_STATE_STOPPING)) {
976       out->common.state = AUDIO_A2DP_STATE_STOPPED;
977     } else {
978       ERROR("write failed : stream suspended, avoid resetting state");
979     }
980     goto finish;
981   }
982 
983 finish:;
984   const size_t frames = bytes / audio_stream_out_frame_size(stream);
985   out->frames_rendered += frames;
986   out->frames_presented += frames;
987   lock.unlock();
988 
989   // If send didn't work out, sleep to emulate write delay.
990   if (sent == -1) {
991     const int us_delay = calc_audiotime_usec(out->common.cfg, bytes);
992     DEBUG("emulate a2dp write delay (%d us)", us_delay);
993     usleep(us_delay);
994   }
995   return bytes;
996 }
997 
out_get_sample_rate(const struct audio_stream * stream)998 static uint32_t out_get_sample_rate(const struct audio_stream* stream) {
999   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1000 
1001   DEBUG("rate %" PRIu32, out->common.cfg.rate);
1002 
1003   return out->common.cfg.rate;
1004 }
1005 
out_set_sample_rate(struct audio_stream * stream,uint32_t rate)1006 static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
1007   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1008 
1009   DEBUG("out_set_sample_rate : %" PRIu32, rate);
1010 
1011   out->common.cfg.rate = rate;
1012 
1013   return 0;
1014 }
1015 
out_get_buffer_size(const struct audio_stream * stream)1016 static size_t out_get_buffer_size(const struct audio_stream* stream) {
1017   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1018   // period_size is the AudioFlinger mixer buffer size.
1019   const size_t period_size =
1020       out->common.buffer_sz / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS;
1021 
1022   DEBUG("socket buffer size: %zu  period size: %zu", out->common.buffer_sz,
1023         period_size);
1024 
1025   return period_size;
1026 }
1027 
audio_a2dp_hw_stream_compute_buffer_size(btav_a2dp_codec_sample_rate_t codec_sample_rate,btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample,btav_a2dp_codec_channel_mode_t codec_channel_mode)1028 size_t audio_a2dp_hw_stream_compute_buffer_size(
1029     btav_a2dp_codec_sample_rate_t codec_sample_rate,
1030     btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample,
1031     btav_a2dp_codec_channel_mode_t codec_channel_mode) {
1032   size_t buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ;  // Default value
1033   const uint64_t time_period_ms = 20;                // Conservative 20ms
1034   uint32_t sample_rate;
1035   uint32_t bits_per_sample;
1036   uint32_t number_of_channels;
1037 
1038   // Check the codec config sample rate
1039   switch (codec_sample_rate) {
1040     case BTAV_A2DP_CODEC_SAMPLE_RATE_44100:
1041       sample_rate = 44100;
1042       break;
1043     case BTAV_A2DP_CODEC_SAMPLE_RATE_48000:
1044       sample_rate = 48000;
1045       break;
1046     case BTAV_A2DP_CODEC_SAMPLE_RATE_88200:
1047       sample_rate = 88200;
1048       break;
1049     case BTAV_A2DP_CODEC_SAMPLE_RATE_96000:
1050       sample_rate = 96000;
1051       break;
1052     case BTAV_A2DP_CODEC_SAMPLE_RATE_176400:
1053       sample_rate = 176400;
1054       break;
1055     case BTAV_A2DP_CODEC_SAMPLE_RATE_192000:
1056       sample_rate = 192000;
1057       break;
1058     case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE:
1059     default:
1060       ERROR("Invalid sample rate: 0x%x", codec_sample_rate);
1061       return buffer_sz;
1062   }
1063 
1064   // Check the codec config bits per sample
1065   switch (codec_bits_per_sample) {
1066     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
1067       bits_per_sample = 16;
1068       break;
1069     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
1070       bits_per_sample = 24;
1071       break;
1072     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
1073       bits_per_sample = 32;
1074       break;
1075     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE:
1076     default:
1077       ERROR("Invalid bits per sample: 0x%x", codec_bits_per_sample);
1078       return buffer_sz;
1079   }
1080 
1081   // Check the codec config channel mode
1082   switch (codec_channel_mode) {
1083     case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO:
1084       number_of_channels = 1;
1085       break;
1086     case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO:
1087       number_of_channels = 2;
1088       break;
1089     case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE:
1090     default:
1091       ERROR("Invalid channel mode: 0x%x", codec_channel_mode);
1092       return buffer_sz;
1093   }
1094 
1095   //
1096   // The buffer size is computed by using the following formula:
1097   //
1098   // AUDIO_STREAM_OUTPUT_BUFFER_SIZE =
1099   //    (TIME_PERIOD_MS * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS *
1100   //     SAMPLE_RATE_HZ * NUMBER_OF_CHANNELS * (BITS_PER_SAMPLE / 8)) / 1000
1101   //
1102   // AUDIO_STREAM_OUTPUT_BUFFER_PERIODS controls how the socket buffer is
1103   // divided for AudioFlinger data delivery. The AudioFlinger mixer delivers
1104   // data in chunks of
1105   // (AUDIO_STREAM_OUTPUT_BUFFER_SIZE / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS) .
1106   // If the number of periods is 2, the socket buffer represents "double
1107   // buffering" of the AudioFlinger mixer buffer.
1108   //
1109   // Furthermore, the AudioFlinger expects the buffer size to be a multiple
1110   // of 16 frames.
1111   const size_t divisor = (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 *
1112                           number_of_channels * bits_per_sample) /
1113                          8;
1114 
1115   buffer_sz = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS *
1116                sample_rate * number_of_channels * (bits_per_sample / 8)) /
1117               1000;
1118 
1119   // Adjust the buffer size so it can be divided by the divisor
1120   const size_t remainder = buffer_sz % divisor;
1121   if (remainder != 0) {
1122     buffer_sz += divisor - remainder;
1123   }
1124 
1125   return buffer_sz;
1126 }
1127 
out_get_channels(const struct audio_stream * stream)1128 static audio_channel_mask_t out_get_channels(
1129     const struct audio_stream* stream) {
1130   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1131 
1132   DEBUG("channels 0x%" PRIx32, out->common.cfg.channel_mask);
1133 
1134   return (audio_channel_mask_t)out->common.cfg.channel_mask;
1135 }
1136 
out_get_format(const struct audio_stream * stream)1137 static audio_format_t out_get_format(const struct audio_stream* stream) {
1138   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1139   DEBUG("format 0x%x", out->common.cfg.format);
1140   return (audio_format_t)out->common.cfg.format;
1141 }
1142 
out_set_format(UNUSED_ATTR struct audio_stream * stream,UNUSED_ATTR audio_format_t format)1143 static int out_set_format(UNUSED_ATTR struct audio_stream* stream,
1144                           UNUSED_ATTR audio_format_t format) {
1145   DEBUG("setting format not yet supported (0x%x)", format);
1146   return -ENOSYS;
1147 }
1148 
out_standby(struct audio_stream * stream)1149 static int out_standby(struct audio_stream* stream) {
1150   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1151   int retVal = 0;
1152 
1153   FNLOG();
1154 
1155   std::lock_guard<std::recursive_mutex> lock(*out->common.mutex);
1156   // Do nothing in SUSPENDED state.
1157   if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED)
1158     retVal = suspend_audio_datapath(&out->common, true);
1159   out->frames_rendered = 0;  // rendered is reset, presented is not
1160 
1161   return retVal;
1162 }
1163 
out_dump(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR int fd)1164 static int out_dump(UNUSED_ATTR const struct audio_stream* stream,
1165                     UNUSED_ATTR int fd) {
1166   FNLOG();
1167   return 0;
1168 }
1169 
out_set_parameters(struct audio_stream * stream,const char * kvpairs)1170 static int out_set_parameters(struct audio_stream* stream,
1171                               const char* kvpairs) {
1172   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1173 
1174   INFO("state %d kvpairs %s", out->common.state, kvpairs);
1175 
1176   std::unordered_map<std::string, std::string> params =
1177       hash_map_utils_new_from_string_params(kvpairs);
1178   int status = 0;
1179 
1180   if (params.empty()) return status;
1181 
1182   std::lock_guard<std::recursive_mutex> lock(*out->common.mutex);
1183 
1184   /* dump params */
1185   hash_map_utils_dump_string_keys_string_values(params);
1186 
1187   if (params["closing"].compare("true") == 0) {
1188     DEBUG("stream closing, disallow any writes");
1189     out->common.state = AUDIO_A2DP_STATE_STOPPING;
1190   }
1191 
1192   if (params["A2dpSuspended"].compare("true") == 0) {
1193     if (out->common.state == AUDIO_A2DP_STATE_STARTED)
1194       status = suspend_audio_datapath(&out->common, false);
1195   } else {
1196     /* Do not start the streaming automatically. If the phone was streaming
1197      * prior to being suspended, the next out_write shall trigger the
1198      * AVDTP start procedure */
1199     if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED)
1200       out->common.state = AUDIO_A2DP_STATE_STANDBY;
1201     /* Irrespective of the state, return 0 */
1202   }
1203 
1204   return status;
1205 }
1206 
out_get_parameters(const struct audio_stream * stream,const char * keys)1207 static char* out_get_parameters(const struct audio_stream* stream,
1208                                 const char* keys) {
1209   FNLOG();
1210 
1211   btav_a2dp_codec_config_t codec_config;
1212   btav_a2dp_codec_config_t codec_capability;
1213 
1214   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1215 
1216   std::unordered_map<std::string, std::string> params =
1217       hash_map_utils_new_from_string_params(keys);
1218   std::unordered_map<std::string, std::string> return_params;
1219 
1220   if (params.empty()) return strdup("");
1221 
1222   std::lock_guard<std::recursive_mutex> lock(*out->common.mutex);
1223 
1224   if (a2dp_read_output_audio_config(&out->common, &codec_config,
1225                                     &codec_capability,
1226                                     false /* update_stream_config */) < 0) {
1227     ERROR("a2dp_read_output_audio_config failed");
1228     goto done;
1229   }
1230 
1231   // Add the format
1232   if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
1233     std::string param;
1234     if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) {
1235       if (!param.empty()) param += "|";
1236       param += "AUDIO_FORMAT_PCM_16_BIT";
1237     }
1238     if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) {
1239       if (!param.empty()) param += "|";
1240       param += "AUDIO_FORMAT_PCM_24_BIT_PACKED";
1241     }
1242     if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) {
1243       if (!param.empty()) param += "|";
1244       param += "AUDIO_FORMAT_PCM_32_BIT";
1245     }
1246     if (param.empty()) {
1247       ERROR("Invalid codec capability bits_per_sample=0x%x",
1248             codec_capability.bits_per_sample);
1249       goto done;
1250     } else {
1251       return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param;
1252     }
1253   }
1254 
1255   // Add the sample rate
1256   if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) {
1257     std::string param;
1258     if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_44100) {
1259       if (!param.empty()) param += "|";
1260       param += "44100";
1261     }
1262     if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_48000) {
1263       if (!param.empty()) param += "|";
1264       param += "48000";
1265     }
1266     if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_88200) {
1267       if (!param.empty()) param += "|";
1268       param += "88200";
1269     }
1270     if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_96000) {
1271       if (!param.empty()) param += "|";
1272       param += "96000";
1273     }
1274     if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_176400) {
1275       if (!param.empty()) param += "|";
1276       param += "176400";
1277     }
1278     if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_192000) {
1279       if (!param.empty()) param += "|";
1280       param += "192000";
1281     }
1282     if (param.empty()) {
1283       ERROR("Invalid codec capability sample_rate=0x%x",
1284             codec_capability.sample_rate);
1285       goto done;
1286     } else {
1287       return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param;
1288     }
1289   }
1290 
1291   // Add the channel mask
1292   if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) {
1293     std::string param;
1294     if (codec_capability.channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_MONO) {
1295       if (!param.empty()) param += "|";
1296       param += "AUDIO_CHANNEL_OUT_MONO";
1297     }
1298     if (codec_capability.channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO) {
1299       if (!param.empty()) param += "|";
1300       param += "AUDIO_CHANNEL_OUT_STEREO";
1301     }
1302     if (param.empty()) {
1303       ERROR("Invalid codec capability channel_mode=0x%x",
1304             codec_capability.channel_mode);
1305       goto done;
1306     } else {
1307       return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param;
1308     }
1309   }
1310 
1311 done:
1312   std::string result;
1313   for (const auto& ptr : return_params) {
1314     result += ptr.first + "=" + ptr.second + ";";
1315   }
1316 
1317   INFO("get parameters result = %s", result.c_str());
1318 
1319   return strdup(result.c_str());
1320 }
1321 
out_get_latency(const struct audio_stream_out * stream)1322 static uint32_t out_get_latency(const struct audio_stream_out* stream) {
1323   int latency_us;
1324 
1325   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1326 
1327   FNLOG();
1328 
1329   latency_us =
1330       ((out->common.buffer_sz * 1000) /
1331        audio_stream_out_frame_size(&out->stream) / out->common.cfg.rate) *
1332       1000;
1333 
1334   return (latency_us / 1000) + 200;
1335 }
1336 
out_set_volume(UNUSED_ATTR struct audio_stream_out * stream,UNUSED_ATTR float left,UNUSED_ATTR float right)1337 static int out_set_volume(UNUSED_ATTR struct audio_stream_out* stream,
1338                           UNUSED_ATTR float left, UNUSED_ATTR float right) {
1339   FNLOG();
1340 
1341   /* volume controlled in audioflinger mixer (digital) */
1342 
1343   return -ENOSYS;
1344 }
1345 
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)1346 static int out_get_presentation_position(const struct audio_stream_out* stream,
1347                                          uint64_t* frames,
1348                                          struct timespec* timestamp) {
1349   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1350 
1351   FNLOG();
1352   if (stream == NULL || frames == NULL || timestamp == NULL) return -EINVAL;
1353 
1354   std::lock_guard<std::recursive_mutex> lock(*out->common.mutex);
1355 
1356   // bytes is the total number of bytes sent by the Bluetooth stack to a
1357   // remote headset
1358   uint64_t bytes = 0;
1359 
1360   // delay_report is the audio delay from the remote headset receiving data to
1361   // the headset playing sound in units of 1/10ms
1362   uint16_t delay_report = 0;
1363 
1364   // If for some reason getting a delay fails or delay reports are disabled,
1365   // default to old delay
1366   if (enable_delay_reporting &&
1367       a2dp_get_presentation_position_cmd(&out->common, &bytes, &delay_report,
1368                                          timestamp) == 0) {
1369     uint64_t delay_ns = delay_report * DELAY_TO_NS;
1370     if (delay_ns > MIN_DELAY_MS * MS_TO_NS &&
1371         delay_ns < MAX_DELAY_MS * MS_TO_NS) {
1372       *frames = bytes / audio_stream_out_frame_size(stream);
1373 
1374       timestamp->tv_nsec += delay_ns;
1375       if (timestamp->tv_nsec > 1 * SEC_TO_NS) {
1376         timestamp->tv_sec++;
1377         timestamp->tv_nsec -= SEC_TO_NS;
1378       }
1379       return 0;
1380     }
1381   }
1382 
1383   uint64_t latency_frames =
1384       (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000;
1385   if (out->frames_presented >= latency_frames) {
1386     clock_gettime(CLOCK_MONOTONIC, timestamp);
1387     *frames = out->frames_presented - latency_frames;
1388     return 0;
1389   }
1390 
1391   return -EWOULDBLOCK;
1392 }
1393 
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)1394 static int out_get_render_position(const struct audio_stream_out* stream,
1395                                    uint32_t* dsp_frames) {
1396   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1397 
1398   FNLOG();
1399   if (stream == NULL || dsp_frames == NULL) return -EINVAL;
1400 
1401   std::lock_guard<std::recursive_mutex> lock(*out->common.mutex);
1402   uint64_t latency_frames =
1403       (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000;
1404   if (out->frames_rendered >= latency_frames) {
1405     *dsp_frames = (uint32_t)(out->frames_rendered - latency_frames);
1406   } else {
1407     *dsp_frames = 0;
1408   }
1409   return 0;
1410 }
1411 
out_add_audio_effect(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR effect_handle_t effect)1412 static int out_add_audio_effect(UNUSED_ATTR const struct audio_stream* stream,
1413                                 UNUSED_ATTR effect_handle_t effect) {
1414   FNLOG();
1415   return 0;
1416 }
1417 
out_remove_audio_effect(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR effect_handle_t effect)1418 static int out_remove_audio_effect(
1419     UNUSED_ATTR const struct audio_stream* stream,
1420     UNUSED_ATTR effect_handle_t effect) {
1421   FNLOG();
1422   return 0;
1423 }
1424 
1425 /*
1426  * AUDIO INPUT STREAM
1427  */
1428 
in_get_sample_rate(const struct audio_stream * stream)1429 static uint32_t in_get_sample_rate(const struct audio_stream* stream) {
1430   struct a2dp_stream_in* in = (struct a2dp_stream_in*)stream;
1431 
1432   FNLOG();
1433   return in->common.cfg.rate;
1434 }
1435 
in_set_sample_rate(struct audio_stream * stream,uint32_t rate)1436 static int in_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
1437   struct a2dp_stream_in* in = (struct a2dp_stream_in*)stream;
1438 
1439   FNLOG();
1440 
1441   if (in->common.cfg.rate > 0 && in->common.cfg.rate == rate)
1442     return 0;
1443   else
1444     return -1;
1445 }
1446 
in_get_buffer_size(UNUSED_ATTR const struct audio_stream * stream)1447 static size_t in_get_buffer_size(
1448     UNUSED_ATTR const struct audio_stream* stream) {
1449   FNLOG();
1450   return 320;
1451 }
1452 
in_get_channels(const struct audio_stream * stream)1453 static audio_channel_mask_t in_get_channels(const struct audio_stream* stream) {
1454   struct a2dp_stream_in* in = (struct a2dp_stream_in*)stream;
1455 
1456   FNLOG();
1457   return (audio_channel_mask_t)in->common.cfg.channel_mask;
1458 }
1459 
in_get_format(UNUSED_ATTR const struct audio_stream * stream)1460 static audio_format_t in_get_format(
1461     UNUSED_ATTR const struct audio_stream* stream) {
1462   FNLOG();
1463   return AUDIO_FORMAT_PCM_16_BIT;
1464 }
1465 
in_set_format(UNUSED_ATTR struct audio_stream * stream,UNUSED_ATTR audio_format_t format)1466 static int in_set_format(UNUSED_ATTR struct audio_stream* stream,
1467                          UNUSED_ATTR audio_format_t format) {
1468   FNLOG();
1469   if (format == AUDIO_FORMAT_PCM_16_BIT)
1470     return 0;
1471   else
1472     return -1;
1473 }
1474 
in_standby(UNUSED_ATTR struct audio_stream * stream)1475 static int in_standby(UNUSED_ATTR struct audio_stream* stream) {
1476   FNLOG();
1477   return 0;
1478 }
1479 
in_dump(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR int fd)1480 static int in_dump(UNUSED_ATTR const struct audio_stream* stream,
1481                    UNUSED_ATTR int fd) {
1482   FNLOG();
1483   return 0;
1484 }
1485 
in_set_parameters(UNUSED_ATTR struct audio_stream * stream,UNUSED_ATTR const char * kvpairs)1486 static int in_set_parameters(UNUSED_ATTR struct audio_stream* stream,
1487                              UNUSED_ATTR const char* kvpairs) {
1488   FNLOG();
1489   return 0;
1490 }
1491 
in_get_parameters(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR const char * keys)1492 static char* in_get_parameters(UNUSED_ATTR const struct audio_stream* stream,
1493                                UNUSED_ATTR const char* keys) {
1494   FNLOG();
1495   return strdup("");
1496 }
1497 
in_set_gain(UNUSED_ATTR struct audio_stream_in * stream,UNUSED_ATTR float gain)1498 static int in_set_gain(UNUSED_ATTR struct audio_stream_in* stream,
1499                        UNUSED_ATTR float gain) {
1500   FNLOG();
1501   return 0;
1502 }
1503 
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)1504 static ssize_t in_read(struct audio_stream_in* stream, void* buffer,
1505                        size_t bytes) {
1506   struct a2dp_stream_in* in = (struct a2dp_stream_in*)stream;
1507   int read;
1508   int us_delay;
1509 
1510   DEBUG("read %zu bytes, state: %d", bytes, in->common.state);
1511 
1512   std::unique_lock<std::recursive_mutex> lock(*in->common.mutex);
1513   if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED ||
1514       in->common.state == AUDIO_A2DP_STATE_STOPPING) {
1515     DEBUG("stream suspended");
1516     goto error;
1517   }
1518 
1519   /* only allow autostarting if we are in stopped or standby */
1520   if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) ||
1521       (in->common.state == AUDIO_A2DP_STATE_STANDBY)) {
1522     if (start_audio_datapath(&in->common) < 0) {
1523       goto error;
1524     }
1525   } else if (in->common.state != AUDIO_A2DP_STATE_STARTED) {
1526     ERROR("stream not in stopped or standby");
1527     goto error;
1528   }
1529 
1530   lock.unlock();
1531   read = skt_read(in->common.audio_fd, buffer, bytes);
1532   lock.lock();
1533   if (read == -1) {
1534     skt_disconnect(in->common.audio_fd);
1535     in->common.audio_fd = AUDIO_SKT_DISCONNECTED;
1536     if ((in->common.state != AUDIO_A2DP_STATE_SUSPENDED) &&
1537         (in->common.state != AUDIO_A2DP_STATE_STOPPING)) {
1538       in->common.state = AUDIO_A2DP_STATE_STOPPED;
1539     } else {
1540       ERROR("read failed : stream suspended, avoid resetting state");
1541     }
1542     goto error;
1543   } else if (read == 0) {
1544     DEBUG("read time out - return zeros");
1545     memset(buffer, 0, bytes);
1546     read = bytes;
1547   }
1548   lock.unlock();
1549 
1550   DEBUG("read %d bytes out of %zu bytes", read, bytes);
1551   return read;
1552 
1553 error:
1554   memset(buffer, 0, bytes);
1555   us_delay = calc_audiotime_usec(in->common.cfg, bytes);
1556   DEBUG("emulate a2dp read delay (%d us)", us_delay);
1557 
1558   usleep(us_delay);
1559   return bytes;
1560 }
1561 
in_get_input_frames_lost(UNUSED_ATTR struct audio_stream_in * stream)1562 static uint32_t in_get_input_frames_lost(
1563     UNUSED_ATTR struct audio_stream_in* stream) {
1564   FNLOG();
1565   return 0;
1566 }
1567 
in_add_audio_effect(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR effect_handle_t effect)1568 static int in_add_audio_effect(UNUSED_ATTR const struct audio_stream* stream,
1569                                UNUSED_ATTR effect_handle_t effect) {
1570   FNLOG();
1571   return 0;
1572 }
1573 
in_remove_audio_effect(UNUSED_ATTR const struct audio_stream * stream,UNUSED_ATTR effect_handle_t effect)1574 static int in_remove_audio_effect(UNUSED_ATTR const struct audio_stream* stream,
1575                                   UNUSED_ATTR effect_handle_t effect) {
1576   FNLOG();
1577 
1578   return 0;
1579 }
1580 
adev_open_output_stream(struct audio_hw_device * dev,UNUSED_ATTR audio_io_handle_t handle,UNUSED_ATTR audio_devices_t devices,UNUSED_ATTR audio_output_flags_t flags,struct audio_config * config,struct audio_stream_out ** stream_out,UNUSED_ATTR const char * address)1581 static int adev_open_output_stream(struct audio_hw_device* dev,
1582                                    UNUSED_ATTR audio_io_handle_t handle,
1583                                    UNUSED_ATTR audio_devices_t devices,
1584                                    UNUSED_ATTR audio_output_flags_t flags,
1585                                    struct audio_config* config,
1586                                    struct audio_stream_out** stream_out,
1587                                    UNUSED_ATTR const char* address)
1588 
1589 {
1590   struct a2dp_audio_device* a2dp_dev = (struct a2dp_audio_device*)dev;
1591   struct a2dp_stream_out* out;
1592   int ret = 0;
1593 
1594   INFO("opening output");
1595   // protect against adev->output and stream_out from being inconsistent
1596   std::lock_guard<std::recursive_mutex> lock(*a2dp_dev->mutex);
1597   out = (struct a2dp_stream_out*)calloc(1, sizeof(struct a2dp_stream_out));
1598 
1599   if (!out) return -ENOMEM;
1600 
1601   out->stream.common.get_sample_rate = out_get_sample_rate;
1602   out->stream.common.set_sample_rate = out_set_sample_rate;
1603   out->stream.common.get_buffer_size = out_get_buffer_size;
1604   out->stream.common.get_channels = out_get_channels;
1605   out->stream.common.get_format = out_get_format;
1606   out->stream.common.set_format = out_set_format;
1607   out->stream.common.standby = out_standby;
1608   out->stream.common.dump = out_dump;
1609   out->stream.common.set_parameters = out_set_parameters;
1610   out->stream.common.get_parameters = out_get_parameters;
1611   out->stream.common.add_audio_effect = out_add_audio_effect;
1612   out->stream.common.remove_audio_effect = out_remove_audio_effect;
1613   out->stream.get_latency = out_get_latency;
1614   out->stream.set_volume = out_set_volume;
1615   out->stream.write = out_write;
1616   out->stream.get_render_position = out_get_render_position;
1617   out->stream.get_presentation_position = out_get_presentation_position;
1618 
1619   /* initialize a2dp specifics */
1620   a2dp_stream_common_init(&out->common);
1621 
1622   // Make sure we always have the feeding parameters configured
1623   btav_a2dp_codec_config_t codec_config;
1624   btav_a2dp_codec_config_t codec_capability;
1625   if (a2dp_read_output_audio_config(&out->common, &codec_config,
1626                                     &codec_capability,
1627                                     true /* update_stream_config */) < 0) {
1628     ERROR("a2dp_read_output_audio_config failed");
1629     ret = -1;
1630     goto err_open;
1631   }
1632   // a2dp_read_output_audio_config() opens the socket control path (or fails)
1633 
1634   /* set output config values */
1635   if (config != nullptr) {
1636     // Try to use the config parameters and send it to the remote side
1637     // TODO: Shall we use out_set_format() and similar?
1638     if (config->format != 0) out->common.cfg.format = config->format;
1639     if (config->sample_rate != 0) out->common.cfg.rate = config->sample_rate;
1640     if (config->channel_mask != 0)
1641       out->common.cfg.channel_mask = config->channel_mask;
1642     if ((out->common.cfg.format != 0) || (out->common.cfg.rate != 0) ||
1643         (out->common.cfg.channel_mask != 0)) {
1644       if (a2dp_write_output_audio_config(&out->common) < 0) {
1645         ERROR("a2dp_write_output_audio_config failed");
1646         ret = -1;
1647         goto err_open;
1648       }
1649       // Read again and make sure we use the same parameters as the remote side
1650       if (a2dp_read_output_audio_config(&out->common, &codec_config,
1651                                         &codec_capability,
1652                                         true /* update_stream_config */) < 0) {
1653         ERROR("a2dp_read_output_audio_config failed");
1654         ret = -1;
1655         goto err_open;
1656       }
1657     }
1658     config->format = out_get_format((const struct audio_stream*)&out->stream);
1659     config->sample_rate =
1660         out_get_sample_rate((const struct audio_stream*)&out->stream);
1661     config->channel_mask =
1662         out_get_channels((const struct audio_stream*)&out->stream);
1663 
1664     INFO(
1665         "Output stream config: format=0x%x sample_rate=%d channel_mask=0x%x "
1666         "buffer_sz=%zu",
1667         config->format, config->sample_rate, config->channel_mask,
1668         out->common.buffer_sz);
1669   }
1670   *stream_out = &out->stream;
1671   a2dp_dev->output = out;
1672 
1673   DEBUG("success");
1674   /* Delay to ensure Headset is in proper state when START is initiated from
1675    * DUT immediately after the connection due to ongoing music playback. */
1676   usleep(250000);
1677   return 0;
1678 
1679 err_open:
1680   a2dp_stream_common_destroy(&out->common);
1681   free(out);
1682   *stream_out = NULL;
1683   a2dp_dev->output = NULL;
1684   ERROR("failed");
1685   return ret;
1686 }
1687 
adev_close_output_stream(struct audio_hw_device * dev,struct audio_stream_out * stream)1688 static void adev_close_output_stream(struct audio_hw_device* dev,
1689                                      struct audio_stream_out* stream) {
1690   struct a2dp_audio_device* a2dp_dev = (struct a2dp_audio_device*)dev;
1691   struct a2dp_stream_out* out = (struct a2dp_stream_out*)stream;
1692 
1693   INFO("%s: state %d", __func__, out->common.state);
1694 
1695   // prevent interference with adev_set_parameters.
1696   std::lock_guard<std::recursive_mutex> lock(*a2dp_dev->mutex);
1697   {
1698     std::lock_guard<std::recursive_mutex> lock(*out->common.mutex);
1699     const a2dp_state_t state = out->common.state;
1700     INFO("closing output (state %d)", (int)state);
1701     if ((state == AUDIO_A2DP_STATE_STARTED) ||
1702         (state == AUDIO_A2DP_STATE_STOPPING)) {
1703       stop_audio_datapath(&out->common);
1704     }
1705 
1706     skt_disconnect(out->common.ctrl_fd);
1707     out->common.ctrl_fd = AUDIO_SKT_DISCONNECTED;
1708   }
1709 
1710   a2dp_stream_common_destroy(&out->common);
1711   free(stream);
1712   a2dp_dev->output = NULL;
1713 
1714   DEBUG("done");
1715 }
1716 
adev_set_parameters(struct audio_hw_device * dev,const char * kvpairs)1717 static int adev_set_parameters(struct audio_hw_device* dev,
1718                                const char* kvpairs) {
1719   struct a2dp_audio_device* a2dp_dev = (struct a2dp_audio_device*)dev;
1720   int retval = 0;
1721 
1722   // prevent interference with adev_close_output_stream
1723   std::lock_guard<std::recursive_mutex> lock(*a2dp_dev->mutex);
1724   struct a2dp_stream_out* out = a2dp_dev->output;
1725 
1726   if (out == NULL) return retval;
1727 
1728   INFO("state %d", out->common.state);
1729 
1730   retval =
1731       out->stream.common.set_parameters((struct audio_stream*)out, kvpairs);
1732 
1733   return retval;
1734 }
1735 
adev_get_parameters(UNUSED_ATTR const struct audio_hw_device * dev,const char * keys)1736 static char* adev_get_parameters(UNUSED_ATTR const struct audio_hw_device* dev,
1737                                  const char* keys) {
1738   FNLOG();
1739 
1740   std::unordered_map<std::string, std::string> params =
1741       hash_map_utils_new_from_string_params(keys);
1742   hash_map_utils_dump_string_keys_string_values(params);
1743 
1744   return strdup("");
1745 }
1746 
adev_init_check(UNUSED_ATTR const struct audio_hw_device * dev)1747 static int adev_init_check(UNUSED_ATTR const struct audio_hw_device* dev) {
1748   FNLOG();
1749 
1750   return 0;
1751 }
1752 
adev_set_voice_volume(UNUSED_ATTR struct audio_hw_device * dev,UNUSED_ATTR float volume)1753 static int adev_set_voice_volume(UNUSED_ATTR struct audio_hw_device* dev,
1754                                  UNUSED_ATTR float volume) {
1755   FNLOG();
1756 
1757   return -ENOSYS;
1758 }
1759 
adev_set_master_volume(UNUSED_ATTR struct audio_hw_device * dev,UNUSED_ATTR float volume)1760 static int adev_set_master_volume(UNUSED_ATTR struct audio_hw_device* dev,
1761                                   UNUSED_ATTR float volume) {
1762   FNLOG();
1763 
1764   return -ENOSYS;
1765 }
1766 
adev_set_mode(UNUSED_ATTR struct audio_hw_device * dev,UNUSED_ATTR audio_mode_t mode)1767 static int adev_set_mode(UNUSED_ATTR struct audio_hw_device* dev,
1768                          UNUSED_ATTR audio_mode_t mode) {
1769   FNLOG();
1770 
1771   return 0;
1772 }
1773 
adev_set_mic_mute(UNUSED_ATTR struct audio_hw_device * dev,UNUSED_ATTR bool state)1774 static int adev_set_mic_mute(UNUSED_ATTR struct audio_hw_device* dev,
1775                              UNUSED_ATTR bool state) {
1776   FNLOG();
1777 
1778   return -ENOSYS;
1779 }
1780 
adev_get_mic_mute(UNUSED_ATTR const struct audio_hw_device * dev,UNUSED_ATTR bool * state)1781 static int adev_get_mic_mute(UNUSED_ATTR const struct audio_hw_device* dev,
1782                              UNUSED_ATTR bool* state) {
1783   FNLOG();
1784 
1785   return -ENOSYS;
1786 }
1787 
adev_get_input_buffer_size(UNUSED_ATTR const struct audio_hw_device * dev,UNUSED_ATTR const struct audio_config * config)1788 static size_t adev_get_input_buffer_size(
1789     UNUSED_ATTR const struct audio_hw_device* dev,
1790     UNUSED_ATTR const struct audio_config* config) {
1791   FNLOG();
1792 
1793   return 320;
1794 }
1795 
adev_open_input_stream(struct audio_hw_device * dev,UNUSED_ATTR audio_io_handle_t handle,UNUSED_ATTR audio_devices_t devices,UNUSED_ATTR struct audio_config * config,struct audio_stream_in ** stream_in,UNUSED_ATTR audio_input_flags_t flags,UNUSED_ATTR const char * address,UNUSED_ATTR audio_source_t source)1796 static int adev_open_input_stream(struct audio_hw_device* dev,
1797                                   UNUSED_ATTR audio_io_handle_t handle,
1798                                   UNUSED_ATTR audio_devices_t devices,
1799                                   UNUSED_ATTR struct audio_config* config,
1800                                   struct audio_stream_in** stream_in,
1801                                   UNUSED_ATTR audio_input_flags_t flags,
1802                                   UNUSED_ATTR const char* address,
1803                                   UNUSED_ATTR audio_source_t source) {
1804   struct a2dp_audio_device* a2dp_dev = (struct a2dp_audio_device*)dev;
1805   struct a2dp_stream_in* in;
1806   int ret;
1807 
1808   FNLOG();
1809 
1810   // protect against adev->input and stream_in from being inconsistent
1811   std::lock_guard<std::recursive_mutex> lock(*a2dp_dev->mutex);
1812   in = (struct a2dp_stream_in*)calloc(1, sizeof(struct a2dp_stream_in));
1813 
1814   if (!in) return -ENOMEM;
1815 
1816   in->stream.common.get_sample_rate = in_get_sample_rate;
1817   in->stream.common.set_sample_rate = in_set_sample_rate;
1818   in->stream.common.get_buffer_size = in_get_buffer_size;
1819   in->stream.common.get_channels = in_get_channels;
1820   in->stream.common.get_format = in_get_format;
1821   in->stream.common.set_format = in_set_format;
1822   in->stream.common.standby = in_standby;
1823   in->stream.common.dump = in_dump;
1824   in->stream.common.set_parameters = in_set_parameters;
1825   in->stream.common.get_parameters = in_get_parameters;
1826   in->stream.common.add_audio_effect = in_add_audio_effect;
1827   in->stream.common.remove_audio_effect = in_remove_audio_effect;
1828   in->stream.set_gain = in_set_gain;
1829   in->stream.read = in_read;
1830   in->stream.get_input_frames_lost = in_get_input_frames_lost;
1831 
1832   /* initialize a2dp specifics */
1833   a2dp_stream_common_init(&in->common);
1834 
1835   *stream_in = &in->stream;
1836   a2dp_dev->input = in;
1837 
1838   if (a2dp_read_input_audio_config(&in->common) < 0) {
1839     ERROR("a2dp_read_input_audio_config failed (%s)", strerror(errno));
1840     ret = -1;
1841     goto err_open;
1842   }
1843   // a2dp_read_input_audio_config() opens socket control path (or fails)
1844 
1845   DEBUG("success");
1846   return 0;
1847 
1848 err_open:
1849   a2dp_stream_common_destroy(&in->common);
1850   free(in);
1851   *stream_in = NULL;
1852   a2dp_dev->input = NULL;
1853   ERROR("failed");
1854   return ret;
1855 }
1856 
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream)1857 static void adev_close_input_stream(struct audio_hw_device* dev,
1858                                     struct audio_stream_in* stream) {
1859   struct a2dp_audio_device* a2dp_dev = (struct a2dp_audio_device*)dev;
1860   struct a2dp_stream_in* in = (struct a2dp_stream_in*)stream;
1861 
1862   std::lock_guard<std::recursive_mutex> lock(*a2dp_dev->mutex);
1863   {
1864     std::lock_guard<std::recursive_mutex> lock(*in->common.mutex);
1865     const a2dp_state_t state = in->common.state;
1866     INFO("closing input (state %d)", (int)state);
1867 
1868     if ((state == AUDIO_A2DP_STATE_STARTED) ||
1869         (state == AUDIO_A2DP_STATE_STOPPING))
1870       stop_audio_datapath(&in->common);
1871 
1872     skt_disconnect(in->common.ctrl_fd);
1873     in->common.ctrl_fd = AUDIO_SKT_DISCONNECTED;
1874   }
1875   a2dp_stream_common_destroy(&in->common);
1876   free(stream);
1877   a2dp_dev->input = NULL;
1878 
1879   DEBUG("done");
1880 }
1881 
adev_dump(UNUSED_ATTR const audio_hw_device_t * device,UNUSED_ATTR int fd)1882 static int adev_dump(UNUSED_ATTR const audio_hw_device_t* device,
1883                      UNUSED_ATTR int fd) {
1884   FNLOG();
1885 
1886   return 0;
1887 }
1888 
adev_close(hw_device_t * device)1889 static int adev_close(hw_device_t* device) {
1890   struct a2dp_audio_device* a2dp_dev = (struct a2dp_audio_device*)device;
1891   FNLOG();
1892 
1893   delete a2dp_dev->mutex;
1894   a2dp_dev->mutex = nullptr;
1895   free(device);
1896   return 0;
1897 }
1898 
adev_open(const hw_module_t * module,const char * name,hw_device_t ** device)1899 static int adev_open(const hw_module_t* module, const char* name,
1900                      hw_device_t** device) {
1901   struct a2dp_audio_device* adev;
1902 
1903   INFO(" adev_open in A2dp_hw module");
1904   FNLOG();
1905 
1906   if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) {
1907     ERROR("interface %s not matching [%s]", name, AUDIO_HARDWARE_INTERFACE);
1908     return -EINVAL;
1909   }
1910 
1911   adev = (struct a2dp_audio_device*)calloc(1, sizeof(struct a2dp_audio_device));
1912 
1913   if (!adev) return -ENOMEM;
1914 
1915   adev->mutex = new std::recursive_mutex;
1916 
1917   adev->device.common.tag = HARDWARE_DEVICE_TAG;
1918   adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
1919   adev->device.common.module = (struct hw_module_t*)module;
1920   adev->device.common.close = adev_close;
1921 
1922   adev->device.init_check = adev_init_check;
1923   adev->device.set_voice_volume = adev_set_voice_volume;
1924   adev->device.set_master_volume = adev_set_master_volume;
1925   adev->device.set_mode = adev_set_mode;
1926   adev->device.set_mic_mute = adev_set_mic_mute;
1927   adev->device.get_mic_mute = adev_get_mic_mute;
1928   adev->device.set_parameters = adev_set_parameters;
1929   adev->device.get_parameters = adev_get_parameters;
1930   adev->device.get_input_buffer_size = adev_get_input_buffer_size;
1931   adev->device.open_output_stream = adev_open_output_stream;
1932   adev->device.close_output_stream = adev_close_output_stream;
1933   adev->device.open_input_stream = adev_open_input_stream;
1934   adev->device.close_input_stream = adev_close_input_stream;
1935   adev->device.dump = adev_dump;
1936 
1937   adev->output = NULL;
1938 
1939   *device = &adev->device.common;
1940 
1941   return 0;
1942 }
1943 
1944 static struct hw_module_methods_t hal_module_methods = {
1945     .open = adev_open,
1946 };
1947 
1948 __attribute__((
1949     visibility("default"))) struct audio_module HAL_MODULE_INFO_SYM = {
1950     .common =
1951         {
1952             .tag = HARDWARE_MODULE_TAG,
1953             .version_major = 1,
1954             .version_minor = 0,
1955             .id = AUDIO_HARDWARE_MODULE_ID,
1956             .name = "A2DP Audio HW HAL",
1957             .author = "The Android Open Source Project",
1958             .methods = &hal_module_methods,
1959         },
1960 };
1961