OSDN Git Service

Update build files for Fluoride on Linux
[android-x86/system-bt.git] / audio_a2dp_hw / audio_a2dp_hw.c
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 <pthread.h>
33 #include <stdint.h>
34 #include <sys/errno.h>
35 #include <sys/poll.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include <sys/un.h>
40 #include <unistd.h>
41
42 #include <hardware/audio.h>
43 #include <hardware/hardware.h>
44 #include <system/audio.h>
45
46 #include "audio_a2dp_hw.h"
47 #include "bt_utils.h"
48 #include "osi/include/hash_map.h"
49 #include "osi/include/hash_map_utils.h"
50 #include "osi/include/log.h"
51 #include "osi/include/socket_utils/sockets.h"
52
53 /*****************************************************************************
54 **  Constants & Macros
55 ******************************************************************************/
56
57 #define CTRL_CHAN_RETRY_COUNT 3
58 #define USEC_PER_SEC 1000000L
59
60 #define CASE_RETURN_STR(const) case const: return #const;
61
62 #define FNLOG()             LOG_VERBOSE(LOG_TAG, "%s", __FUNCTION__);
63 #define DEBUG(fmt, ...)     LOG_VERBOSE(LOG_TAG, "%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
64 #define INFO(fmt, ...)      LOG_INFO(LOG_TAG, "%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
65 #define ERROR(fmt, ...)     LOG_ERROR(LOG_TAG, "%s: " fmt,__FUNCTION__, ## __VA_ARGS__)
66
67 #define ASSERTC(cond, msg, val) if (!(cond)) {ERROR("### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, val);}
68
69 /*****************************************************************************
70 **  Local type definitions
71 ******************************************************************************/
72
73 typedef enum {
74     AUDIO_A2DP_STATE_STARTING,
75     AUDIO_A2DP_STATE_STARTED,
76     AUDIO_A2DP_STATE_STOPPING,
77     AUDIO_A2DP_STATE_STOPPED,
78     AUDIO_A2DP_STATE_SUSPENDED, /* need explicit set param call to resume (suspend=false) */
79     AUDIO_A2DP_STATE_STANDBY    /* allows write to autoresume */
80 } a2dp_state_t;
81
82 struct a2dp_stream_in;
83 struct a2dp_stream_out;
84
85 struct a2dp_audio_device {
86     struct audio_hw_device device;
87     struct a2dp_stream_in  *input;
88     struct a2dp_stream_out *output;
89 };
90
91 struct a2dp_config {
92     uint32_t                rate;
93     uint32_t                channel_flags;
94     int                     format;
95 };
96
97 /* move ctrl_fd outside output stream and keep open until HAL unloaded ? */
98
99 struct a2dp_stream_common {
100     pthread_mutex_t         lock;
101     int                     ctrl_fd;
102     int                     audio_fd;
103     size_t                  buffer_sz;
104     struct a2dp_config      cfg;
105     a2dp_state_t            state;
106 };
107
108 struct a2dp_stream_out {
109     struct audio_stream_out stream;
110     struct a2dp_stream_common common;
111     uint64_t frames_presented; // frames written, never reset
112     uint64_t frames_rendered;  // frames written, reset on standby
113 };
114
115 struct a2dp_stream_in {
116     struct audio_stream_in  stream;
117     struct a2dp_stream_common common;
118 };
119
120 /*****************************************************************************
121 **  Static variables
122 ******************************************************************************/
123
124 /*****************************************************************************
125 **  Static functions
126 ******************************************************************************/
127
128 static size_t out_get_buffer_size(const struct audio_stream *stream);
129
130 /*****************************************************************************
131 **  Externs
132 ******************************************************************************/
133
134 /*****************************************************************************
135 **  Functions
136 ******************************************************************************/
137 /* Function used only in debug mode */
138 static const char* dump_a2dp_ctrl_event(char event) __attribute__ ((unused));
139
140 /*****************************************************************************
141 **   Miscellaneous helper functions
142 ******************************************************************************/
143
144 static const char* dump_a2dp_ctrl_event(char event)
145 {
146     switch(event)
147     {
148         CASE_RETURN_STR(A2DP_CTRL_CMD_NONE)
149         CASE_RETURN_STR(A2DP_CTRL_CMD_CHECK_READY)
150         CASE_RETURN_STR(A2DP_CTRL_CMD_START)
151         CASE_RETURN_STR(A2DP_CTRL_CMD_STOP)
152         CASE_RETURN_STR(A2DP_CTRL_CMD_SUSPEND)
153         default:
154             return "UNKNOWN MSG ID";
155     }
156 }
157
158 /* logs timestamp with microsec precision
159    pprev is optional in case a dedicated diff is required */
160 static void ts_log(char *tag, int val, struct timespec *pprev_opt)
161 {
162     struct timespec now;
163     static struct timespec prev = {0,0};
164     unsigned long long now_us;
165     unsigned long long diff_us;
166     UNUSED(tag);
167     UNUSED(val);
168
169     clock_gettime(CLOCK_MONOTONIC, &now);
170
171     now_us = now.tv_sec*USEC_PER_SEC + now.tv_nsec/1000;
172
173     if (pprev_opt)
174     {
175         diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (now.tv_nsec - prev.tv_nsec)/1000;
176         *pprev_opt = now;
177         DEBUG("[%s] ts %08lld, *diff %08lld, val %d", tag, now_us, diff_us, val);
178     }
179     else
180     {
181         diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (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
187 static int calc_audiotime(struct a2dp_config cfg, int bytes)
188 {
189     int chan_count = popcount(cfg.channel_flags);
190
191     ASSERTC(cfg.format == AUDIO_FORMAT_PCM_16_BIT,
192             "unsupported sample sz", cfg.format);
193
194     return (int)(((int64_t)bytes * (1000000 / (chan_count * 2))) / cfg.rate);
195 }
196
197 /*****************************************************************************
198 **
199 **   bluedroid stack adaptation
200 **
201 *****************************************************************************/
202
203 static int skt_connect(char *path, size_t buffer_sz)
204 {
205     int ret;
206     int skt_fd;
207     int len;
208
209     INFO("connect to %s (sz %zu)", path, buffer_sz);
210
211     skt_fd = socket(AF_LOCAL, SOCK_STREAM, 0);
212
213     if(osi_socket_local_client_connect(skt_fd, path,
214             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM) < 0)
215     {
216         ERROR("failed to connect (%s)", strerror(errno));
217         close(skt_fd);
218         return -1;
219     }
220
221     len = buffer_sz;
222     ret = setsockopt(skt_fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, (int)sizeof(len));
223
224     /* only issue warning if failed */
225     if (ret < 0)
226         ERROR("setsockopt failed (%s)", strerror(errno));
227
228     ret = setsockopt(skt_fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, (int)sizeof(len));
229
230     /* only issue warning if failed */
231     if (ret < 0)
232         ERROR("setsockopt failed (%s)", strerror(errno));
233
234     INFO("connected to stack fd = %d", skt_fd);
235
236     return skt_fd;
237 }
238
239 static int skt_read(int fd, void *p, size_t len)
240 {
241     int read;
242
243     FNLOG();
244
245     ts_log("skt_read recv", len, NULL);
246
247     if ((read = recv(fd, p, len, MSG_NOSIGNAL)) == -1)
248     {
249         ERROR("write failed with errno=%d\n", errno);
250         return -1;
251     }
252
253     return read;
254 }
255
256 static int skt_write(int fd, const void *p, size_t len)
257 {
258     int sent;
259     struct pollfd pfd;
260
261     FNLOG();
262
263     pfd.fd = fd;
264     pfd.events = POLLOUT;
265
266     /* poll for 500 ms */
267
268     /* send time out */
269     if (poll(&pfd, 1, 500) == 0)
270         return 0;
271
272     ts_log("skt_write", len, NULL);
273
274     if ((sent = send(fd, p, len, MSG_NOSIGNAL)) == -1)
275     {
276         ERROR("write failed with errno=%d\n", errno);
277         return -1;
278     }
279
280     return sent;
281 }
282
283 static int skt_disconnect(int fd)
284 {
285     INFO("fd %d", fd);
286
287     if (fd != AUDIO_SKT_DISCONNECTED)
288     {
289         shutdown(fd, SHUT_RDWR);
290         close(fd);
291     }
292     return 0;
293 }
294
295
296
297 /*****************************************************************************
298 **
299 **  AUDIO CONTROL PATH
300 **
301 *****************************************************************************/
302
303 static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
304 {
305     int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
306     if (ret < 0)
307     {
308         ERROR("ack failed (%s)", strerror(errno));
309         if (errno == EINTR)
310         {
311             /* retry again */
312             ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
313             if (ret < 0)
314             {
315                ERROR("ack failed (%s)", strerror(errno));
316                skt_disconnect(common->ctrl_fd);
317                common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
318                return -1;
319             }
320         }
321         else
322         {
323                skt_disconnect(common->ctrl_fd);
324                common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
325                return -1;
326
327         }
328     }
329     return ret;
330 }
331
332 static int a2dp_command(struct a2dp_stream_common *common, char cmd)
333 {
334     char ack;
335
336     DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd));
337
338     /* send command */
339     if (send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL) == -1)
340     {
341         ERROR("cmd failed (%s)", strerror(errno));
342         skt_disconnect(common->ctrl_fd);
343         common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
344         return -1;
345     }
346
347     /* wait for ack byte */
348     if (a2dp_ctrl_receive(common, &ack, 1) < 0)
349         return -1;
350
351     DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack);
352
353     if (ack == A2DP_CTRL_ACK_INCALL_FAILURE)
354         return ack;
355     if (ack != A2DP_CTRL_ACK_SUCCESS)
356         return -1;
357
358     return 0;
359 }
360
361 static int check_a2dp_ready(struct a2dp_stream_common *common)
362 {
363     if (a2dp_command(common, A2DP_CTRL_CMD_CHECK_READY) < 0)
364     {
365         ERROR("check a2dp ready failed");
366         return -1;
367     }
368     return 0;
369 }
370
371 static int a2dp_read_audio_config(struct a2dp_stream_common *common)
372 {
373     uint32_t sample_rate;
374     uint8_t channel_count;
375
376     if (a2dp_command(common, A2DP_CTRL_GET_AUDIO_CONFIG) < 0)
377     {
378         ERROR("check a2dp ready failed");
379         return -1;
380     }
381
382     if (a2dp_ctrl_receive(common, &sample_rate, 4) < 0)
383         return -1;
384     if (a2dp_ctrl_receive(common, &channel_count, 1) < 0)
385         return -1;
386
387     common->cfg.channel_flags = (channel_count == 1 ? AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO);
388     common->cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
389     common->cfg.rate = sample_rate;
390
391     INFO("got config %d %d", common->cfg.format, common->cfg.rate);
392
393     return 0;
394 }
395
396 static void a2dp_open_ctrl_path(struct a2dp_stream_common *common)
397 {
398     int i;
399
400     /* retry logic to catch any timing variations on control channel */
401     for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++)
402     {
403         /* connect control channel if not already connected */
404         if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0)
405         {
406             /* success, now check if stack is ready */
407             if (check_a2dp_ready(common) == 0)
408                 break;
409
410             ERROR("error : a2dp not ready, wait 250 ms and retry");
411             usleep(250000);
412             skt_disconnect(common->ctrl_fd);
413             common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
414         }
415
416         /* ctrl channel not ready, wait a bit */
417         usleep(250000);
418     }
419 }
420
421 /*****************************************************************************
422 **
423 ** AUDIO DATA PATH
424 **
425 *****************************************************************************/
426
427 static void a2dp_stream_common_init(struct a2dp_stream_common *common)
428 {
429     pthread_mutexattr_t lock_attr;
430
431     FNLOG();
432
433     pthread_mutexattr_init(&lock_attr);
434     pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE);
435     pthread_mutex_init(&common->lock, &lock_attr);
436
437     common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
438     common->audio_fd = AUDIO_SKT_DISCONNECTED;
439     common->state = AUDIO_A2DP_STATE_STOPPED;
440
441     /* manages max capacity of socket pipe */
442     common->buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ;
443 }
444
445 static int start_audio_datapath(struct a2dp_stream_common *common)
446 {
447     INFO("state %d", common->state);
448
449     if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED) {
450         INFO("%s AUDIO_SKT_DISCONNECTED", __func__);
451         return -1;
452     }
453
454     int oldstate = common->state;
455     common->state = AUDIO_A2DP_STATE_STARTING;
456
457     int a2dp_status = a2dp_command(common, A2DP_CTRL_CMD_START);
458     if (a2dp_status < 0)
459     {
460         ERROR("%s Audiopath start failed (status %d)", __func__, a2dp_status);
461
462         common->state = oldstate;
463         return -1;
464     }
465     else if (a2dp_status == A2DP_CTRL_ACK_INCALL_FAILURE)
466     {
467         ERROR("%s Audiopath start failed - in call, move to suspended", __func__);
468         common->state = oldstate;
469         return -1;
470     }
471
472     /* connect socket if not yet connected */
473     if (common->audio_fd == AUDIO_SKT_DISCONNECTED)
474     {
475         common->audio_fd = skt_connect(A2DP_DATA_PATH, common->buffer_sz);
476         if (common->audio_fd < 0)
477         {
478             common->state = oldstate;
479             return -1;
480         }
481
482         common->state = AUDIO_A2DP_STATE_STARTED;
483     }
484
485     return 0;
486 }
487
488 static int stop_audio_datapath(struct a2dp_stream_common *common)
489 {
490     int oldstate = common->state;
491
492     INFO("state %d", common->state);
493
494     if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED)
495          return -1;
496
497     /* prevent any stray output writes from autostarting the stream
498        while stopping audiopath */
499     common->state = AUDIO_A2DP_STATE_STOPPING;
500
501     if (a2dp_command(common, A2DP_CTRL_CMD_STOP) < 0)
502     {
503         ERROR("audiopath stop failed");
504         common->state = oldstate;
505         return -1;
506     }
507
508     common->state = AUDIO_A2DP_STATE_STOPPED;
509
510     /* disconnect audio path */
511     skt_disconnect(common->audio_fd);
512     common->audio_fd = AUDIO_SKT_DISCONNECTED;
513
514     return 0;
515 }
516
517 static int suspend_audio_datapath(struct a2dp_stream_common *common, bool standby)
518 {
519     INFO("state %d", common->state);
520
521     if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED)
522          return -1;
523
524     if (common->state == AUDIO_A2DP_STATE_STOPPING)
525         return -1;
526
527     if (a2dp_command(common, A2DP_CTRL_CMD_SUSPEND) < 0)
528         return -1;
529
530     if (standby)
531         common->state = AUDIO_A2DP_STATE_STANDBY;
532     else
533         common->state = AUDIO_A2DP_STATE_SUSPENDED;
534
535     /* disconnect audio path */
536     skt_disconnect(common->audio_fd);
537
538     common->audio_fd = AUDIO_SKT_DISCONNECTED;
539
540     return 0;
541 }
542
543
544 /*****************************************************************************
545 **
546 **  audio output callbacks
547 **
548 *****************************************************************************/
549
550 static ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
551                          size_t bytes)
552 {
553     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
554     int sent;
555     int us_delay;
556
557     DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd);
558
559     pthread_mutex_lock(&out->common.lock);
560
561     if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED)
562     {
563         DEBUG("stream suspended");
564         pthread_mutex_unlock(&out->common.lock);
565         goto error;
566     }
567
568     /* only allow autostarting if we are in stopped or standby */
569     if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) ||
570         (out->common.state == AUDIO_A2DP_STATE_STANDBY))
571     {
572         if (start_audio_datapath(&out->common) < 0)
573         {
574             pthread_mutex_unlock(&out->common.lock);
575             goto error;
576         }
577     }
578     else if (out->common.state != AUDIO_A2DP_STATE_STARTED)
579     {
580         ERROR("stream not in stopped or standby");
581         pthread_mutex_unlock(&out->common.lock);
582         goto error;
583     }
584
585     pthread_mutex_unlock(&out->common.lock);
586     sent = skt_write(out->common.audio_fd, buffer,  bytes);
587
588     if (sent == -1) {
589         skt_disconnect(out->common.audio_fd);
590         out->common.audio_fd = AUDIO_SKT_DISCONNECTED;
591         if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED)
592             out->common.state = AUDIO_A2DP_STATE_STOPPED;
593         else
594             ERROR("write failed : stream suspended, avoid resetting state");
595         goto error;
596     }
597
598     const size_t frames = bytes / audio_stream_out_frame_size(stream);
599     out->frames_rendered += frames;
600     out->frames_presented += frames;
601     return bytes;
602
603 error:
604     us_delay = calc_audiotime(out->common.cfg, bytes);
605
606     DEBUG("emulate a2dp write delay (%d us)", us_delay);
607
608     usleep(us_delay);
609     return bytes;
610 }
611
612
613 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
614 {
615     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
616
617     DEBUG("rate %" PRIu32,out->common.cfg.rate);
618
619     return out->common.cfg.rate;
620 }
621
622 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
623 {
624     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
625
626     DEBUG("out_set_sample_rate : %" PRIu32, rate);
627
628     if (rate != AUDIO_STREAM_DEFAULT_RATE)
629     {
630         ERROR("only rate %d supported", AUDIO_STREAM_DEFAULT_RATE);
631         return -1;
632     }
633
634     out->common.cfg.rate = rate;
635
636     return 0;
637 }
638
639 static size_t out_get_buffer_size(const struct audio_stream *stream)
640 {
641     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
642
643     DEBUG("buffer_size : %zu", out->common.buffer_sz);
644
645     return out->common.buffer_sz;
646 }
647
648 static uint32_t out_get_channels(const struct audio_stream *stream)
649 {
650     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
651
652     DEBUG("channels 0x%" PRIx32, out->common.cfg.channel_flags);
653
654     return out->common.cfg.channel_flags;
655 }
656
657 static audio_format_t out_get_format(const struct audio_stream *stream)
658 {
659     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
660     DEBUG("format 0x%x", out->common.cfg.format);
661     return out->common.cfg.format;
662 }
663
664 static int out_set_format(struct audio_stream *stream, audio_format_t format)
665 {
666     UNUSED(stream);
667     UNUSED(format);
668     DEBUG("setting format not yet supported (0x%x)", format);
669     return -ENOSYS;
670 }
671
672 static int out_standby(struct audio_stream *stream)
673 {
674     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
675     int retVal = 0;
676
677     FNLOG();
678
679     pthread_mutex_lock(&out->common.lock);
680     // Do nothing in SUSPENDED state.
681     if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED)
682         retVal = suspend_audio_datapath(&out->common, true);
683     out->frames_rendered = 0; // rendered is reset, presented is not
684     pthread_mutex_unlock (&out->common.lock);
685
686     return retVal;
687 }
688
689 static int out_dump(const struct audio_stream *stream, int fd)
690 {
691     UNUSED(stream);
692     UNUSED(fd);
693     FNLOG();
694     return 0;
695 }
696
697 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
698 {
699     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
700
701     INFO("state %d", out->common.state);
702
703     hash_map_t *params = hash_map_utils_new_from_string_params(kvpairs);
704     int status = 0;
705
706     if (!params)
707       return status;
708
709     pthread_mutex_lock(&out->common.lock);
710
711     /* dump params */
712     hash_map_utils_dump_string_keys_string_values(params);
713
714     char *keyval = (char *)hash_map_get(params, "closing");
715
716     if (keyval && strcmp(keyval, "true") == 0)
717     {
718         DEBUG("stream closing, disallow any writes");
719         out->common.state = AUDIO_A2DP_STATE_STOPPING;
720     }
721
722     keyval = (char *)hash_map_get(params, "A2dpSuspended");
723
724     if (keyval && strcmp(keyval, "true") == 0)
725     {
726         if (out->common.state == AUDIO_A2DP_STATE_STARTED)
727             status = suspend_audio_datapath(&out->common, false);
728     }
729     else
730     {
731         /* Do not start the streaming automatically. If the phone was streaming
732          * prior to being suspended, the next out_write shall trigger the
733          * AVDTP start procedure */
734         if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED)
735             out->common.state = AUDIO_A2DP_STATE_STANDBY;
736         /* Irrespective of the state, return 0 */
737     }
738
739     pthread_mutex_unlock(&out->common.lock);
740     hash_map_free(params);
741
742     return status;
743 }
744
745 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
746 {
747     UNUSED(stream);
748     UNUSED(keys);
749     FNLOG();
750
751     /* add populating param here */
752
753     return strdup("");
754 }
755
756 static uint32_t out_get_latency(const struct audio_stream_out *stream)
757 {
758     int latency_us;
759
760     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
761
762     FNLOG();
763
764     latency_us = ((out->common.buffer_sz * 1000 ) /
765                     audio_stream_out_frame_size(&out->stream) /
766                     out->common.cfg.rate) * 1000;
767
768
769     return (latency_us / 1000) + 200;
770 }
771
772 static int out_set_volume(struct audio_stream_out *stream, float left,
773                           float right)
774 {
775     UNUSED(stream);
776     UNUSED(left);
777     UNUSED(right);
778
779     FNLOG();
780
781     /* volume controlled in audioflinger mixer (digital) */
782
783     return -ENOSYS;
784 }
785
786 static int out_get_presentation_position(const struct audio_stream_out *stream,
787                                          uint64_t *frames, struct timespec *timestamp)
788 {
789     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
790
791     FNLOG();
792     if (stream == NULL || frames == NULL || timestamp == NULL)
793         return -EINVAL;
794
795     int ret = -EWOULDBLOCK;
796     pthread_mutex_lock(&out->common.lock);
797     uint64_t latency_frames = (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000;
798     if (out->frames_presented >= latency_frames) {
799         *frames = out->frames_presented - latency_frames;
800         clock_gettime(CLOCK_MONOTONIC, timestamp); // could also be associated with out_write().
801         ret = 0;
802     }
803     pthread_mutex_unlock(&out->common.lock);
804     return ret;
805 }
806
807 static int out_get_render_position(const struct audio_stream_out *stream,
808                                    uint32_t *dsp_frames)
809 {
810     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
811
812     FNLOG();
813     if (stream == NULL || dsp_frames == NULL)
814         return -EINVAL;
815
816     pthread_mutex_lock(&out->common.lock);
817     uint64_t latency_frames = (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000;
818     if (out->frames_rendered >= latency_frames) {
819         *dsp_frames = (uint32_t)(out->frames_rendered - latency_frames);
820     } else {
821         *dsp_frames = 0;
822     }
823     pthread_mutex_unlock(&out->common.lock);
824     return 0;
825 }
826
827 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
828 {
829     UNUSED(stream);
830     UNUSED(effect);
831
832     FNLOG();
833     return 0;
834 }
835
836 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
837 {
838     UNUSED(stream);
839     UNUSED(effect);
840
841     FNLOG();
842     return 0;
843 }
844
845 /*
846  * AUDIO INPUT STREAM
847  */
848
849 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
850 {
851     struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
852
853     FNLOG();
854     return in->common.cfg.rate;
855 }
856
857 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
858 {
859     struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
860
861     FNLOG();
862
863     if (in->common.cfg.rate > 0 && in->common.cfg.rate == rate)
864         return 0;
865     else
866         return -1;
867 }
868
869 static size_t in_get_buffer_size(const struct audio_stream *stream)
870 {
871     UNUSED(stream);
872
873     FNLOG();
874     return 320;
875 }
876
877 static uint32_t in_get_channels(const struct audio_stream *stream)
878 {
879     struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
880
881     FNLOG();
882     return in->common.cfg.channel_flags;
883 }
884
885 static audio_format_t in_get_format(const struct audio_stream *stream)
886 {
887     UNUSED(stream);
888
889     FNLOG();
890     return AUDIO_FORMAT_PCM_16_BIT;
891 }
892
893 static int in_set_format(struct audio_stream *stream, audio_format_t format)
894 {
895     UNUSED(stream);
896     UNUSED(format);
897
898     FNLOG();
899     if (format == AUDIO_FORMAT_PCM_16_BIT)
900         return 0;
901     else
902         return -1;
903 }
904
905 static int in_standby(struct audio_stream *stream)
906 {
907     UNUSED(stream);
908
909     FNLOG();
910     return 0;
911 }
912
913 static int in_dump(const struct audio_stream *stream, int fd)
914 {
915     UNUSED(stream);
916     UNUSED(fd);
917
918     FNLOG();
919     return 0;
920 }
921
922 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
923 {
924     UNUSED(stream);
925     UNUSED(kvpairs);
926
927     FNLOG();
928     return 0;
929 }
930
931 static char * in_get_parameters(const struct audio_stream *stream,
932                                 const char *keys)
933 {
934     UNUSED(stream);
935     UNUSED(keys);
936
937     FNLOG();
938     return strdup("");
939 }
940
941 static int in_set_gain(struct audio_stream_in *stream, float gain)
942 {
943     UNUSED(stream);
944     UNUSED(gain);
945
946     FNLOG();
947     return 0;
948 }
949
950 static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
951                        size_t bytes)
952 {
953     struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
954     int read;
955
956     DEBUG("read %zu bytes, state: %d", bytes, in->common.state);
957
958     if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED)
959     {
960         DEBUG("stream suspended");
961         return -1;
962     }
963
964     /* only allow autostarting if we are in stopped or standby */
965     if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) ||
966         (in->common.state == AUDIO_A2DP_STATE_STANDBY))
967     {
968         pthread_mutex_lock(&in->common.lock);
969
970         if (start_audio_datapath(&in->common) < 0)
971         {
972             /* emulate time this write represents to avoid very fast write
973                failures during transition periods or remote suspend */
974
975             int us_delay = calc_audiotime(in->common.cfg, bytes);
976
977             DEBUG("emulate a2dp read delay (%d us)", us_delay);
978
979             usleep(us_delay);
980             pthread_mutex_unlock(&in->common.lock);
981             return -1;
982         }
983
984         pthread_mutex_unlock(&in->common.lock);
985     }
986     else if (in->common.state != AUDIO_A2DP_STATE_STARTED)
987     {
988         ERROR("stream not in stopped or standby");
989         return -1;
990     }
991
992     read = skt_read(in->common.audio_fd, buffer, bytes);
993
994     if (read == -1)
995     {
996         skt_disconnect(in->common.audio_fd);
997         in->common.audio_fd = AUDIO_SKT_DISCONNECTED;
998         in->common.state = AUDIO_A2DP_STATE_STOPPED;
999     } else if (read == 0) {
1000         DEBUG("read time out - return zeros");
1001         memset(buffer, 0, bytes);
1002         read = bytes;
1003     }
1004
1005     DEBUG("read %d bytes out of %zu bytes", read, bytes);
1006     return read;
1007 }
1008
1009 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1010 {
1011     UNUSED(stream);
1012
1013     FNLOG();
1014     return 0;
1015 }
1016
1017 static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1018 {
1019     UNUSED(stream);
1020     UNUSED(effect);
1021
1022     FNLOG();
1023     return 0;
1024 }
1025
1026 static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1027 {
1028     UNUSED(stream);
1029     UNUSED(effect);
1030
1031     FNLOG();
1032
1033     return 0;
1034 }
1035
1036 static int adev_open_output_stream(struct audio_hw_device *dev,
1037                                    audio_io_handle_t handle,
1038                                    audio_devices_t devices,
1039                                    audio_output_flags_t flags,
1040                                    struct audio_config *config,
1041                                    struct audio_stream_out **stream_out,
1042                                    const char *address)
1043
1044 {
1045     struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
1046     struct a2dp_stream_out *out;
1047     int ret = 0;
1048     UNUSED(address);
1049     UNUSED(handle);
1050     UNUSED(devices);
1051     UNUSED(flags);
1052
1053     INFO("opening output");
1054
1055     out = (struct a2dp_stream_out *)calloc(1, sizeof(struct a2dp_stream_out));
1056
1057     if (!out)
1058         return -ENOMEM;
1059
1060     out->stream.common.get_sample_rate = out_get_sample_rate;
1061     out->stream.common.set_sample_rate = out_set_sample_rate;
1062     out->stream.common.get_buffer_size = out_get_buffer_size;
1063     out->stream.common.get_channels = out_get_channels;
1064     out->stream.common.get_format = out_get_format;
1065     out->stream.common.set_format = out_set_format;
1066     out->stream.common.standby = out_standby;
1067     out->stream.common.dump = out_dump;
1068     out->stream.common.set_parameters = out_set_parameters;
1069     out->stream.common.get_parameters = out_get_parameters;
1070     out->stream.common.add_audio_effect = out_add_audio_effect;
1071     out->stream.common.remove_audio_effect = out_remove_audio_effect;
1072     out->stream.get_latency = out_get_latency;
1073     out->stream.set_volume = out_set_volume;
1074     out->stream.write = out_write;
1075     out->stream.get_render_position = out_get_render_position;
1076     out->stream.get_presentation_position = out_get_presentation_position;
1077
1078
1079     /* initialize a2dp specifics */
1080     a2dp_stream_common_init(&out->common);
1081
1082     out->common.cfg.channel_flags = AUDIO_STREAM_DEFAULT_CHANNEL_FLAG;
1083     out->common.cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
1084     out->common.cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
1085
1086    /* set output config values */
1087    if (config)
1088    {
1089       config->format = out_get_format((const struct audio_stream *)&out->stream);
1090       config->sample_rate = out_get_sample_rate((const struct audio_stream *)&out->stream);
1091       config->channel_mask = out_get_channels((const struct audio_stream *)&out->stream);
1092    }
1093     *stream_out = &out->stream;
1094     a2dp_dev->output = out;
1095
1096     a2dp_open_ctrl_path(&out->common);
1097     if (out->common.ctrl_fd == AUDIO_SKT_DISCONNECTED)
1098     {
1099         ERROR("ctrl socket failed to connect (%s)", strerror(errno));
1100         ret = -1;
1101         goto err_open;
1102     }
1103
1104     DEBUG("success");
1105     /* Delay to ensure Headset is in proper state when START is initiated
1106        from DUT immediately after the connection due to ongoing music playback. */
1107     usleep(250000);
1108     return 0;
1109
1110 err_open:
1111     free(out);
1112     *stream_out = NULL;
1113     a2dp_dev->output = NULL;
1114     ERROR("failed");
1115     return ret;
1116 }
1117
1118 static void adev_close_output_stream(struct audio_hw_device *dev,
1119                                      struct audio_stream_out *stream)
1120 {
1121     struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
1122     struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
1123
1124     INFO("closing output (state %d)", out->common.state);
1125
1126     pthread_mutex_lock(&out->common.lock);
1127     if ((out->common.state == AUDIO_A2DP_STATE_STARTED) || (out->common.state == AUDIO_A2DP_STATE_STOPPING))
1128         stop_audio_datapath(&out->common);
1129
1130     skt_disconnect(out->common.ctrl_fd);
1131     free(stream);
1132     a2dp_dev->output = NULL;
1133     pthread_mutex_unlock(&out->common.lock);
1134
1135     DEBUG("done");
1136 }
1137
1138 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
1139 {
1140     struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
1141     struct a2dp_stream_out *out = a2dp_dev->output;
1142     int retval = 0;
1143
1144     if (out == NULL)
1145         return retval;
1146
1147     INFO("state %d", out->common.state);
1148
1149     retval = out->stream.common.set_parameters((struct audio_stream *)out, kvpairs);
1150
1151     return retval;
1152 }
1153
1154 static char * adev_get_parameters(const struct audio_hw_device *dev,
1155                                   const char *keys)
1156 {
1157     UNUSED(dev);
1158
1159     FNLOG();
1160
1161     hash_map_t *params = hash_map_utils_new_from_string_params(keys);
1162     hash_map_utils_dump_string_keys_string_values(params);
1163     hash_map_free(params);
1164
1165     return strdup("");
1166 }
1167
1168 static int adev_init_check(const struct audio_hw_device *dev)
1169 {
1170     UNUSED(dev);
1171     FNLOG();
1172
1173     return 0;
1174 }
1175
1176 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
1177 {
1178     UNUSED(dev);
1179     UNUSED(volume);
1180
1181     FNLOG();
1182
1183     return -ENOSYS;
1184 }
1185
1186 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
1187 {
1188     UNUSED(dev);
1189     UNUSED(volume);
1190
1191     FNLOG();
1192
1193     return -ENOSYS;
1194 }
1195
1196 static int adev_set_mode(struct audio_hw_device *dev, int mode)
1197 {
1198     UNUSED(dev);
1199     UNUSED(mode);
1200
1201     FNLOG();
1202
1203     return 0;
1204 }
1205
1206 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
1207 {
1208     UNUSED(dev);
1209     UNUSED(state);
1210
1211     FNLOG();
1212
1213     return -ENOSYS;
1214 }
1215
1216 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1217 {
1218     UNUSED(dev);
1219     UNUSED(state);
1220
1221     FNLOG();
1222
1223     return -ENOSYS;
1224 }
1225
1226 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
1227                                          const struct audio_config *config)
1228 {
1229     UNUSED(dev);
1230     UNUSED(config);
1231
1232     FNLOG();
1233
1234     return 320;
1235 }
1236
1237 static int adev_open_input_stream(struct audio_hw_device *dev,
1238                                   audio_io_handle_t handle,
1239                                   audio_devices_t devices,
1240                                   struct audio_config *config,
1241                                   struct audio_stream_in **stream_in,
1242                                   audio_input_flags_t flags,
1243                                   const char *address,
1244                                   audio_source_t source)
1245 {
1246     struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
1247     struct a2dp_stream_in *in;
1248     int ret;
1249     UNUSED(address);
1250     UNUSED(config);
1251     UNUSED(devices);
1252     UNUSED(flags);
1253     UNUSED(handle);
1254     UNUSED(source);
1255
1256     FNLOG();
1257
1258     in = (struct a2dp_stream_in *)calloc(1, sizeof(struct a2dp_stream_in));
1259
1260     if (!in)
1261         return -ENOMEM;
1262
1263     in->stream.common.get_sample_rate = in_get_sample_rate;
1264     in->stream.common.set_sample_rate = in_set_sample_rate;
1265     in->stream.common.get_buffer_size = in_get_buffer_size;
1266     in->stream.common.get_channels = in_get_channels;
1267     in->stream.common.get_format = in_get_format;
1268     in->stream.common.set_format = in_set_format;
1269     in->stream.common.standby = in_standby;
1270     in->stream.common.dump = in_dump;
1271     in->stream.common.set_parameters = in_set_parameters;
1272     in->stream.common.get_parameters = in_get_parameters;
1273     in->stream.common.add_audio_effect = in_add_audio_effect;
1274     in->stream.common.remove_audio_effect = in_remove_audio_effect;
1275     in->stream.set_gain = in_set_gain;
1276     in->stream.read = in_read;
1277     in->stream.get_input_frames_lost = in_get_input_frames_lost;
1278
1279     /* initialize a2dp specifics */
1280     a2dp_stream_common_init(&in->common);
1281
1282     *stream_in = &in->stream;
1283     a2dp_dev->input = in;
1284
1285     a2dp_open_ctrl_path(&in->common);
1286     if (in->common.ctrl_fd == AUDIO_SKT_DISCONNECTED)
1287     {
1288         ERROR("ctrl socket failed to connect (%s)", strerror(errno));
1289         ret = -1;
1290         goto err_open;
1291     }
1292
1293     if (a2dp_read_audio_config(&in->common) < 0) {
1294         ERROR("a2dp_read_audio_config failed (%s)", strerror(errno));
1295         ret = -1;
1296         goto err_open;
1297     }
1298
1299     DEBUG("success");
1300     return 0;
1301
1302 err_open:
1303     free(in);
1304     *stream_in = NULL;
1305     a2dp_dev->input = NULL;
1306     ERROR("failed");
1307     return ret;
1308 }
1309
1310 static void adev_close_input_stream(struct audio_hw_device *dev,
1311                                    struct audio_stream_in *stream)
1312 {
1313     struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
1314     struct a2dp_stream_in* in = (struct a2dp_stream_in *)stream;
1315     a2dp_state_t state = in->common.state;
1316
1317     INFO("closing input (state %d)", state);
1318
1319     if ((state == AUDIO_A2DP_STATE_STARTED) || (state == AUDIO_A2DP_STATE_STOPPING))
1320         stop_audio_datapath(&in->common);
1321
1322     skt_disconnect(in->common.ctrl_fd);
1323     free(stream);
1324     a2dp_dev->input = NULL;
1325
1326     DEBUG("done");
1327 }
1328
1329 static int adev_dump(const audio_hw_device_t *device, int fd)
1330 {
1331     UNUSED(device);
1332     UNUSED(fd);
1333
1334     FNLOG();
1335
1336     return 0;
1337 }
1338
1339 static int adev_close(hw_device_t *device)
1340 {
1341     FNLOG();
1342
1343     free(device);
1344     return 0;
1345 }
1346
1347 static int adev_open(const hw_module_t* module, const char* name,
1348                      hw_device_t** device)
1349 {
1350     struct a2dp_audio_device *adev;
1351
1352     INFO(" adev_open in A2dp_hw module");
1353     FNLOG();
1354
1355     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
1356     {
1357         ERROR("interface %s not matching [%s]", name, AUDIO_HARDWARE_INTERFACE);
1358         return -EINVAL;
1359     }
1360
1361     adev = calloc(1, sizeof(struct a2dp_audio_device));
1362
1363     if (!adev)
1364         return -ENOMEM;
1365
1366     adev->device.common.tag = HARDWARE_DEVICE_TAG;
1367     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
1368     adev->device.common.module = (struct hw_module_t *) module;
1369     adev->device.common.close = adev_close;
1370
1371     adev->device.init_check = adev_init_check;
1372     adev->device.set_voice_volume = adev_set_voice_volume;
1373     adev->device.set_master_volume = adev_set_master_volume;
1374     adev->device.set_mode = adev_set_mode;
1375     adev->device.set_mic_mute = adev_set_mic_mute;
1376     adev->device.get_mic_mute = adev_get_mic_mute;
1377     adev->device.set_parameters = adev_set_parameters;
1378     adev->device.get_parameters = adev_get_parameters;
1379     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
1380     adev->device.open_output_stream = adev_open_output_stream;
1381     adev->device.close_output_stream = adev_close_output_stream;
1382     adev->device.open_input_stream = adev_open_input_stream;
1383     adev->device.close_input_stream = adev_close_input_stream;
1384     adev->device.dump = adev_dump;
1385
1386     adev->output = NULL;
1387
1388
1389     *device = &adev->device.common;
1390
1391     return 0;
1392 }
1393
1394 static struct hw_module_methods_t hal_module_methods = {
1395     .open = adev_open,
1396 };
1397
1398 __attribute__ ((visibility ("default")))
1399 struct audio_module HAL_MODULE_INFO_SYM = {
1400     .common = {
1401         .tag = HARDWARE_MODULE_TAG,
1402         .version_major = 1,
1403         .version_minor = 0,
1404         .id = AUDIO_HARDWARE_MODULE_ID,
1405         .name = "A2DP Audio HW HAL",
1406         .author = "The Android Open Source Project",
1407         .methods = &hal_module_methods,
1408     },
1409 };