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