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