OSDN Git Service

android/hal-audio-aptx: Add initial support for aptX codec
[android-x86/external-bluetooth-bluez.git] / android / hal-audio.c
1 /*
2  * Copyright (C) 2013 Intel Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 #include <errno.h>
19 #include <pthread.h>
20 #include <poll.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/socket.h>
25 #include <sys/un.h>
26 #include <unistd.h>
27 #include <arpa/inet.h>
28 #include <fcntl.h>
29
30 #include <hardware/audio.h>
31 #include <hardware/hardware.h>
32
33 #include "audio-msg.h"
34 #include "ipc-common.h"
35 #include "hal-log.h"
36 #include "hal-msg.h"
37 #include "hal-audio.h"
38 #include "src/shared/util.h"
39 #include "src/shared/queue.h"
40
41 #define FIXED_A2DP_PLAYBACK_LATENCY_MS 25
42
43 #define FIXED_BUFFER_SIZE (20 * 512)
44
45 #define MAX_DELAY       100000 /* 100ms */
46
47 static const uint8_t a2dp_src_uuid[] = {
48                 0x00, 0x00, 0x11, 0x0a, 0x00, 0x00, 0x10, 0x00,
49                 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb };
50
51 static int listen_sk = -1;
52 static int audio_sk = -1;
53
54 static pthread_t ipc_th = 0;
55 static pthread_mutex_t sk_mutex = PTHREAD_MUTEX_INITIALIZER;
56
57 static void timespec_add(struct timespec *base, uint64_t time_us,
58                                                         struct timespec *res)
59 {
60         res->tv_sec = base->tv_sec + time_us / 1000000;
61         res->tv_nsec = base->tv_nsec + (time_us % 1000000) * 1000;
62
63         if (res->tv_nsec >= 1000000000) {
64                 res->tv_sec++;
65                 res->tv_nsec -= 1000000000;
66         }
67 }
68
69 static void timespec_diff(struct timespec *a, struct timespec *b,
70                                                         struct timespec *res)
71 {
72         res->tv_sec = a->tv_sec - b->tv_sec;
73         res->tv_nsec = a->tv_nsec - b->tv_nsec;
74
75         if (res->tv_nsec < 0) {
76                 res->tv_sec--;
77                 res->tv_nsec += 1000000000; /* 1sec */
78         }
79 }
80
81 static uint64_t timespec_diff_us(struct timespec *a, struct timespec *b)
82 {
83         struct timespec res;
84
85         timespec_diff(a, b, &res);
86
87         return res.tv_sec * 1000000ll + res.tv_nsec / 1000ll;
88 }
89
90 #if defined(ANDROID)
91 /*
92  * Bionic does not have clock_nanosleep() prototype in time.h even though
93  * it provides its implementation.
94  */
95 extern int clock_nanosleep(clockid_t clock_id, int flags,
96                                         const struct timespec *request,
97                                         struct timespec *remain);
98 #endif
99
100 static const audio_codec_get_t audio_codecs[] = {
101                 codec_aptx,
102                 codec_sbc,
103 };
104
105 #define NUM_CODECS (sizeof(audio_codecs) / sizeof(audio_codecs[0]))
106
107 #define MAX_AUDIO_ENDPOINTS NUM_CODECS
108
109 static struct queue *loaded_codecs;
110
111 struct audio_endpoint {
112         uint8_t id;
113         const struct audio_codec *codec;
114         void *codec_data;
115         int fd;
116
117         struct media_packet *mp;
118         size_t mp_data_len;
119
120         uint16_t seq;
121         uint32_t samples;
122         struct timespec start;
123
124         bool resync;
125 };
126
127 static struct audio_endpoint audio_endpoints[MAX_AUDIO_ENDPOINTS];
128
129 enum a2dp_state_t {
130         AUDIO_A2DP_STATE_NONE,
131         AUDIO_A2DP_STATE_STANDBY,
132         AUDIO_A2DP_STATE_SUSPENDED,
133         AUDIO_A2DP_STATE_STARTED
134 };
135
136 struct a2dp_stream_out {
137         struct audio_stream_out stream;
138
139         struct audio_endpoint *ep;
140         enum a2dp_state_t audio_state;
141         struct audio_input_config cfg;
142
143         uint8_t *downmix_buf;
144 };
145
146 struct a2dp_audio_dev {
147         struct audio_hw_device dev;
148         struct a2dp_stream_out *out;
149 };
150
151 static int audio_ipc_cmd(uint8_t service_id, uint8_t opcode, uint16_t len,
152                         void *param, size_t *rsp_len, void *rsp, int *fd)
153 {
154         ssize_t ret;
155         struct msghdr msg;
156         struct iovec iv[2];
157         struct ipc_hdr cmd;
158         char cmsgbuf[CMSG_SPACE(sizeof(int))];
159         struct ipc_status s;
160         size_t s_len = sizeof(s);
161
162         pthread_mutex_lock(&sk_mutex);
163
164         if (audio_sk < 0) {
165                 error("audio: Invalid cmd socket passed to audio_ipc_cmd");
166                 goto failed;
167         }
168
169         if (!rsp || !rsp_len) {
170                 memset(&s, 0, s_len);
171                 rsp_len = &s_len;
172                 rsp = &s;
173         }
174
175         memset(&msg, 0, sizeof(msg));
176         memset(&cmd, 0, sizeof(cmd));
177
178         cmd.service_id = service_id;
179         cmd.opcode = opcode;
180         cmd.len = len;
181
182         iv[0].iov_base = &cmd;
183         iv[0].iov_len = sizeof(cmd);
184
185         iv[1].iov_base = param;
186         iv[1].iov_len = len;
187
188         msg.msg_iov = iv;
189         msg.msg_iovlen = 2;
190
191         ret = sendmsg(audio_sk, &msg, 0);
192         if (ret < 0) {
193                 error("audio: Sending command failed:%s", strerror(errno));
194                 goto failed;
195         }
196
197         /* socket was shutdown */
198         if (ret == 0) {
199                 error("audio: Command socket closed");
200                 goto failed;
201         }
202
203         memset(&msg, 0, sizeof(msg));
204         memset(&cmd, 0, sizeof(cmd));
205
206         iv[0].iov_base = &cmd;
207         iv[0].iov_len = sizeof(cmd);
208
209         iv[1].iov_base = rsp;
210         iv[1].iov_len = *rsp_len;
211
212         msg.msg_iov = iv;
213         msg.msg_iovlen = 2;
214
215         if (fd) {
216                 memset(cmsgbuf, 0, sizeof(cmsgbuf));
217                 msg.msg_control = cmsgbuf;
218                 msg.msg_controllen = sizeof(cmsgbuf);
219         }
220
221         ret = recvmsg(audio_sk, &msg, 0);
222         if (ret < 0) {
223                 error("audio: Receiving command response failed:%s",
224                                                         strerror(errno));
225                 goto failed;
226         }
227
228         if (ret < (ssize_t) sizeof(cmd)) {
229                 error("audio: Too small response received(%zd bytes)", ret);
230                 goto failed;
231         }
232
233         if (cmd.service_id != service_id) {
234                 error("audio: Invalid service id (%u vs %u)", cmd.service_id,
235                                                                 service_id);
236                 goto failed;
237         }
238
239         if (ret != (ssize_t) (sizeof(cmd) + cmd.len)) {
240                 error("audio: Malformed response received(%zd bytes)", ret);
241                 goto failed;
242         }
243
244         if (cmd.opcode != opcode && cmd.opcode != AUDIO_OP_STATUS) {
245                 error("audio: Invalid opcode received (%u vs %u)",
246                                                 cmd.opcode, opcode);
247                 goto failed;
248         }
249
250         if (cmd.opcode == AUDIO_OP_STATUS) {
251                 struct ipc_status *s = rsp;
252
253                 if (sizeof(*s) != cmd.len) {
254                         error("audio: Invalid status length");
255                         goto failed;
256                 }
257
258                 if (s->code == AUDIO_STATUS_SUCCESS) {
259                         error("audio: Invalid success status response");
260                         goto failed;
261                 }
262
263                 pthread_mutex_unlock(&sk_mutex);
264
265                 return s->code;
266         }
267
268         pthread_mutex_unlock(&sk_mutex);
269
270         /* Receive auxiliary data in msg */
271         if (fd) {
272                 struct cmsghdr *cmsg;
273
274                 *fd = -1;
275
276                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
277                                         cmsg = CMSG_NXTHDR(&msg, cmsg)) {
278                         if (cmsg->cmsg_level == SOL_SOCKET
279                                         && cmsg->cmsg_type == SCM_RIGHTS) {
280                                 memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
281                                 break;
282                         }
283                 }
284
285                 if (*fd < 0)
286                         goto failed;
287         }
288
289         if (rsp_len)
290                 *rsp_len = cmd.len;
291
292         return AUDIO_STATUS_SUCCESS;
293
294 failed:
295         /* Some serious issue happen on IPC - recover */
296         shutdown(audio_sk, SHUT_RDWR);
297         pthread_mutex_unlock(&sk_mutex);
298
299         return AUDIO_STATUS_FAILED;
300 }
301
302 static int ipc_open_cmd(const struct audio_codec *codec)
303 {
304         uint8_t buf[BLUEZ_AUDIO_MTU];
305         struct audio_cmd_open *cmd = (struct audio_cmd_open *) buf;
306         struct audio_rsp_open rsp;
307         size_t cmd_len = sizeof(buf) - sizeof(*cmd);
308         size_t rsp_len = sizeof(rsp);
309         int result;
310
311         DBG("");
312
313         memcpy(cmd->uuid, a2dp_src_uuid, sizeof(a2dp_src_uuid));
314
315         cmd->codec = codec->type;
316         cmd->presets = codec->get_presets(cmd->preset, &cmd_len);
317
318         cmd_len += sizeof(*cmd);
319
320         result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN, cmd_len, cmd,
321                                 &rsp_len, &rsp, NULL);
322
323         if (result != AUDIO_STATUS_SUCCESS)
324                 return 0;
325
326         return rsp.id;
327 }
328
329 static int ipc_close_cmd(uint8_t endpoint_id)
330 {
331         struct audio_cmd_close cmd;
332         int result;
333
334         DBG("");
335
336         cmd.id = endpoint_id;
337
338         result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE,
339                                 sizeof(cmd), &cmd, NULL, NULL, NULL);
340
341         return result;
342 }
343
344 static int ipc_open_stream_cmd(uint8_t *endpoint_id, uint16_t *mtu, int *fd,
345                                                 struct audio_preset **caps)
346 {
347         char buf[BLUEZ_AUDIO_MTU];
348         struct audio_cmd_open_stream cmd;
349         struct audio_rsp_open_stream *rsp =
350                                         (struct audio_rsp_open_stream *) &buf;
351         size_t rsp_len = sizeof(buf);
352         int result;
353
354         DBG("");
355
356         if (!caps)
357                 return AUDIO_STATUS_FAILED;
358
359         cmd.id = *endpoint_id;
360
361         result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN_STREAM,
362                                 sizeof(cmd), &cmd, &rsp_len, rsp, fd);
363         if (result == AUDIO_STATUS_SUCCESS) {
364                 size_t buf_len = sizeof(struct audio_preset) +
365                                         rsp->preset[0].len;
366                 *endpoint_id = rsp->id;
367                 *mtu = rsp->mtu;
368                 *caps = malloc(buf_len);
369                 memcpy(*caps, &rsp->preset, buf_len);
370         } else {
371                 *caps = NULL;
372         }
373
374         return result;
375 }
376
377 static int ipc_close_stream_cmd(uint8_t endpoint_id)
378 {
379         struct audio_cmd_close_stream cmd;
380         int result;
381
382         DBG("");
383
384         cmd.id = endpoint_id;
385
386         result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE_STREAM,
387                                         sizeof(cmd), &cmd, NULL, NULL, NULL);
388
389         return result;
390 }
391
392 static int ipc_resume_stream_cmd(uint8_t endpoint_id)
393 {
394         struct audio_cmd_resume_stream cmd;
395         int result;
396
397         DBG("");
398
399         cmd.id = endpoint_id;
400
401         result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_RESUME_STREAM,
402                                         sizeof(cmd), &cmd, NULL, NULL, NULL);
403
404         return result;
405 }
406
407 static int ipc_suspend_stream_cmd(uint8_t endpoint_id)
408 {
409         struct audio_cmd_suspend_stream cmd;
410         int result;
411
412         DBG("");
413
414         cmd.id = endpoint_id;
415
416         result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_SUSPEND_STREAM,
417                                         sizeof(cmd), &cmd, NULL, NULL, NULL);
418
419         return result;
420 }
421
422 struct register_state {
423         struct audio_endpoint *ep;
424         bool error;
425 };
426
427 static void register_endpoint(void *data, void *user_data)
428 {
429         struct audio_codec *codec = data;
430         struct register_state *state = user_data;
431         struct audio_endpoint *ep = state->ep;
432
433         /* don't even try to register more endpoints if one failed */
434         if (state->error)
435                 return;
436
437         ep->id = ipc_open_cmd(codec);
438
439         if (!ep->id) {
440                 state->error = true;
441                 error("Failed to register endpoint");
442                 return;
443         }
444
445         ep->codec = codec;
446         ep->codec_data = NULL;
447         ep->fd = -1;
448
449         state->ep++;
450 }
451
452 static int register_endpoints(void)
453 {
454         struct register_state state;
455
456         state.ep = &audio_endpoints[0];
457         state.error = false;
458
459         queue_foreach(loaded_codecs, register_endpoint, &state);
460
461         return state.error ? AUDIO_STATUS_FAILED : AUDIO_STATUS_SUCCESS;
462 }
463
464 static void unregister_endpoints(void)
465 {
466         size_t i;
467
468         for (i = 0; i < MAX_AUDIO_ENDPOINTS; i++) {
469                 struct audio_endpoint *ep = &audio_endpoints[i];
470
471                 if (ep->id) {
472                         ipc_close_cmd(ep->id);
473                         memset(ep, 0, sizeof(*ep));
474                 }
475         }
476 }
477
478 static bool open_endpoint(struct audio_endpoint **epp,
479                                                 struct audio_input_config *cfg)
480 {
481         struct audio_preset *preset;
482         struct audio_endpoint *ep = *epp;
483         const struct audio_codec *codec;
484         uint16_t mtu;
485         uint16_t payload_len;
486         int fd;
487         size_t i;
488         uint8_t ep_id = 0;
489
490         if (ep)
491                 ep_id = ep->id;
492
493         if (ipc_open_stream_cmd(&ep_id, &mtu, &fd, &preset) !=
494                                                         AUDIO_STATUS_SUCCESS)
495                 return false;
496
497         DBG("ep_id=%d mtu=%u", ep_id, mtu);
498
499         for (i = 0; i < MAX_AUDIO_ENDPOINTS; i++)
500                 if (audio_endpoints[i].id == ep_id) {
501                         ep = &audio_endpoints[i];
502                         break;
503                 }
504
505         if (!ep) {
506                 error("Cound not find opened endpoint");
507                 return false;
508         }
509
510         *epp = ep;
511
512         payload_len = mtu;
513         if (ep->codec->use_rtp)
514                 payload_len -= sizeof(struct rtp_header);
515
516         ep->fd = fd;
517
518         codec = ep->codec;
519         codec->init(preset, payload_len, &ep->codec_data);
520         codec->get_config(ep->codec_data, cfg);
521
522         ep->mp = calloc(mtu, 1);
523         if (!ep->mp)
524                 goto failed;
525
526         if (ep->codec->use_rtp) {
527                 struct media_packet_rtp *mp_rtp =
528                                         (struct media_packet_rtp *) ep->mp;
529                 mp_rtp->hdr.v = 2;
530                 mp_rtp->hdr.pt = 0x60;
531                 mp_rtp->hdr.ssrc = htonl(1);
532         }
533
534         ep->mp_data_len = payload_len;
535
536         free(preset);
537
538         return true;
539
540 failed:
541         close(fd);
542         free(preset);
543
544         return false;
545 }
546
547 static void close_endpoint(struct audio_endpoint *ep)
548 {
549         ipc_close_stream_cmd(ep->id);
550         if (ep->fd >= 0) {
551                 close(ep->fd);
552                 ep->fd = -1;
553         }
554
555         free(ep->mp);
556
557         ep->codec->cleanup(ep->codec_data);
558         ep->codec_data = NULL;
559 }
560
561 static bool resume_endpoint(struct audio_endpoint *ep)
562 {
563         if (ipc_resume_stream_cmd(ep->id) != AUDIO_STATUS_SUCCESS)
564                 return false;
565
566         ep->samples = 0;
567         ep->resync = false;
568
569         ep->codec->update_qos(ep->codec_data, QOS_POLICY_DEFAULT);
570
571         return true;
572 }
573
574 static void downmix_to_mono(struct a2dp_stream_out *out, const uint8_t *buffer,
575                                                                 size_t bytes)
576 {
577         const int16_t *input = (const void *) buffer;
578         int16_t *output = (void *) out->downmix_buf;
579         size_t i, frames;
580
581         /* PCM 16bit stereo */
582         frames = bytes / (2 * sizeof(int16_t));
583
584         for (i = 0; i < frames; i++) {
585                 int16_t l = le16_to_cpu(get_unaligned(&input[i * 2]));
586                 int16_t r = le16_to_cpu(get_unaligned(&input[i * 2 + 1]));
587
588                 put_unaligned(cpu_to_le16((l + r) / 2), &output[i]);
589         }
590 }
591
592 static bool wait_for_endpoint(struct audio_endpoint *ep, bool *writable)
593 {
594         int ret;
595
596         while (true) {
597                 struct pollfd pollfd;
598
599                 pollfd.fd = ep->fd;
600                 pollfd.events = POLLOUT;
601                 pollfd.revents = 0;
602
603                 ret = poll(&pollfd, 1, 500);
604
605                 if (ret >= 0) {
606                         *writable = !!(pollfd.revents & POLLOUT);
607                         break;
608                 }
609
610                 if (errno != EINTR) {
611                         ret = errno;
612                         error("poll failed (%d)", ret);
613                         return false;
614                 }
615         }
616
617         return true;
618 }
619
620 static bool write_to_endpoint(struct audio_endpoint *ep, size_t bytes)
621 {
622         struct media_packet *mp = (struct media_packet *) ep->mp;
623         int ret;
624
625         while (true) {
626                 ret = write(ep->fd, mp, bytes);
627
628                 if (ret >= 0)
629                         break;
630
631                 /*
632                  * this should not happen so let's issue warning, but do not
633                  * fail, we can try to write next packet
634                  */
635                 if (errno == EAGAIN) {
636                         ret = errno;
637                         warn("write failed (%d)", ret);
638                         break;
639                 }
640
641                 if (errno != EINTR) {
642                         ret = errno;
643                         error("write failed (%d)", ret);
644                         return false;
645                 }
646         }
647
648         return true;
649 }
650
651 static bool write_data(struct a2dp_stream_out *out, const void *buffer,
652                                                                 size_t bytes)
653 {
654         struct audio_endpoint *ep = out->ep;
655         struct media_packet *mp = (struct media_packet *) ep->mp;
656         struct media_packet_rtp *mp_rtp = (struct media_packet_rtp *) ep->mp;
657         size_t free_space = ep->mp_data_len;
658         size_t consumed = 0;
659
660         while (consumed < bytes) {
661                 size_t written = 0;
662                 ssize_t read;
663                 uint32_t samples;
664                 int ret;
665                 struct timespec current;
666                 uint64_t audio_sent, audio_passed;
667                 bool do_write = false;
668
669                 /*
670                  * prepare media packet in advance so we don't waste time after
671                  * wakeup
672                  */
673                 if (ep->codec->use_rtp) {
674                         mp_rtp->hdr.sequence_number = htons(ep->seq++);
675                         mp_rtp->hdr.timestamp = htonl(ep->samples);
676                 }
677                 read = ep->codec->encode_mediapacket(ep->codec_data,
678                                                 buffer + consumed,
679                                                 bytes - consumed, mp,
680                                                 free_space, &written);
681
682                 /*
683                  * not much we can do here, let's just ignore remaining
684                  * data and continue
685                  */
686                 if (read <= 0)
687                         return true;
688
689                 /* calculate where are we and where we should be */
690                 clock_gettime(CLOCK_MONOTONIC, &current);
691                 if (!ep->samples)
692                         memcpy(&ep->start, &current, sizeof(ep->start));
693                 audio_sent = ep->samples * 1000000ll / out->cfg.rate;
694                 audio_passed = timespec_diff_us(&current, &ep->start);
695
696                 /*
697                  * if we're ahead of stream then wait for next write point,
698                  * if we're lagging more than 100ms then stop writing and just
699                  * skip data until we're back in sync
700                  */
701                 if (audio_sent > audio_passed) {
702                         struct timespec anchor;
703
704                         ep->resync = false;
705
706                         timespec_add(&ep->start, audio_sent, &anchor);
707
708                         while (true) {
709                                 ret = clock_nanosleep(CLOCK_MONOTONIC,
710                                                         TIMER_ABSTIME, &anchor,
711                                                         NULL);
712
713                                 if (!ret)
714                                         break;
715
716                                 if (ret != EINTR) {
717                                         error("clock_nanosleep failed (%d)",
718                                                                         ret);
719                                         return false;
720                                 }
721                         }
722                 } else if (!ep->resync) {
723                         uint64_t diff = audio_passed - audio_sent;
724
725                         if (diff > MAX_DELAY) {
726                                 warn("lag is %jums, resyncing", diff / 1000);
727
728                                 ep->codec->update_qos(ep->codec_data,
729                                                         QOS_POLICY_DECREASE);
730                                 ep->resync = true;
731                         }
732                 }
733
734                 /* we send data only in case codec encoded some data, i.e. some
735                  * codecs do internal buffering and output data only if full
736                  * frame can be encoded
737                  * in resync mode we'll just drop mediapackets
738                  */
739                 if (written > 0 && !ep->resync) {
740                         /* wait some time for socket to be ready for write,
741                          * but we'll just skip writing data if timeout occurs
742                          */
743                         if (!wait_for_endpoint(ep, &do_write))
744                                 return false;
745
746                         if (do_write) {
747                                 if (ep->codec->use_rtp)
748                                         written += sizeof(struct rtp_header);
749
750                                 if (!write_to_endpoint(ep, written))
751                                         return false;
752                         }
753                 }
754
755                 /*
756                  * AudioFlinger provides 16bit PCM, so sample size is 2 bytes
757                  * multiplied by number of channels. Number of channels is
758                  * simply number of bits set in channels mask.
759                  */
760                 samples = read / (2 * popcount(out->cfg.channels));
761                 ep->samples += samples;
762                 consumed += read;
763         }
764
765         return true;
766 }
767
768 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
769                                                                 size_t bytes)
770 {
771         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
772         const void *in_buf = buffer;
773         size_t in_len = bytes;
774
775         /* just return in case we're closing */
776         if (out->audio_state == AUDIO_A2DP_STATE_NONE)
777                 return -1;
778
779         /* We can auto-start only from standby */
780         if (out->audio_state == AUDIO_A2DP_STATE_STANDBY) {
781                 DBG("stream in standby, auto-start");
782
783                 if (!resume_endpoint(out->ep))
784                         return -1;
785
786                 out->audio_state = AUDIO_A2DP_STATE_STARTED;
787         }
788
789         if (out->audio_state != AUDIO_A2DP_STATE_STARTED) {
790                 error("audio: stream not started");
791                 return -1;
792         }
793
794         if (out->ep->fd < 0) {
795                 error("audio: no transport socket");
796                 return -1;
797         }
798
799         /*
800          * currently Android audioflinger is not able to provide mono stream on
801          * A2DP output so down mixing needs to be done in hal-audio plugin.
802          *
803          * for reference see
804          * AudioFlinger::PlaybackThread::readOutputParameters()
805          * frameworks/av/services/audioflinger/Threads.cpp:1631
806          */
807         if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
808                 if (!out->downmix_buf) {
809                         error("audio: downmix buffer not initialized");
810                         return -1;
811                 }
812
813                 downmix_to_mono(out, buffer, bytes);
814
815                 in_buf = out->downmix_buf;
816                 in_len = bytes / 2;
817         }
818
819         if (!write_data(out, in_buf, in_len))
820                 return -1;
821
822         return bytes;
823 }
824
825 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
826 {
827         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
828
829         DBG("");
830
831         return out->cfg.rate;
832 }
833
834 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
835 {
836         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
837
838         DBG("");
839
840         if (rate != out->cfg.rate) {
841                 warn("audio: cannot set sample rate to %d", rate);
842                 return -1;
843         }
844
845         return 0;
846 }
847
848 static size_t out_get_buffer_size(const struct audio_stream *stream)
849 {
850         DBG("");
851
852         /*
853          * We should return proper buffer size calculated by codec (so each
854          * input buffer is encoded into single media packed) but this does not
855          * work well with AudioFlinger and causes problems. For this reason we
856          * use magic value here and out_write code takes care of splitting
857          * input buffer into multiple media packets.
858          */
859         return FIXED_BUFFER_SIZE;
860 }
861
862 static uint32_t out_get_channels(const struct audio_stream *stream)
863 {
864         DBG("");
865
866         /*
867          * AudioFlinger can only provide stereo stream, so we return it here and
868          * later we'll downmix this to mono in case codec requires it
869          */
870
871         return AUDIO_CHANNEL_OUT_STEREO;
872 }
873
874 static audio_format_t out_get_format(const struct audio_stream *stream)
875 {
876         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
877
878         DBG("");
879
880         return out->cfg.format;
881 }
882
883 static int out_set_format(struct audio_stream *stream, audio_format_t format)
884 {
885         DBG("");
886         return -ENOSYS;
887 }
888
889 static int out_standby(struct audio_stream *stream)
890 {
891         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
892
893         DBG("");
894
895         if (out->audio_state == AUDIO_A2DP_STATE_STARTED) {
896                 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
897                         return -1;
898                 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
899         }
900
901         return 0;
902 }
903
904 static int out_dump(const struct audio_stream *stream, int fd)
905 {
906         DBG("");
907         return -ENOSYS;
908 }
909
910 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
911 {
912         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
913         char *kvpair;
914         char *str;
915         char *saveptr;
916         bool enter_suspend = false;
917         bool exit_suspend = false;
918
919         DBG("%s", kvpairs);
920
921         str = strdup(kvpairs);
922         if (!str)
923                 return -ENOMEM;
924
925         kvpair = strtok_r(str, ";", &saveptr);
926
927         for (; kvpair && *kvpair; kvpair = strtok_r(NULL, ";", &saveptr)) {
928                 char *keyval;
929
930                 keyval = strchr(kvpair, '=');
931                 if (!keyval)
932                         continue;
933
934                 *keyval = '\0';
935                 keyval++;
936
937                 if (!strcmp(kvpair, "closing")) {
938                         if (!strcmp(keyval, "true"))
939                                 out->audio_state = AUDIO_A2DP_STATE_NONE;
940                 } else if (!strcmp(kvpair, "A2dpSuspended")) {
941                         if (!strcmp(keyval, "true"))
942                                 enter_suspend = true;
943                         else
944                                 exit_suspend = true;
945                 }
946         }
947
948         free(str);
949
950         if (enter_suspend && out->audio_state == AUDIO_A2DP_STATE_STARTED) {
951                 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
952                         return -1;
953                 out->audio_state = AUDIO_A2DP_STATE_SUSPENDED;
954         }
955
956         if (exit_suspend && out->audio_state == AUDIO_A2DP_STATE_SUSPENDED)
957                 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
958
959         return 0;
960 }
961
962 static char *out_get_parameters(const struct audio_stream *stream,
963                                                         const char *keys)
964 {
965         DBG("");
966         return strdup("");
967 }
968
969 static uint32_t out_get_latency(const struct audio_stream_out *stream)
970 {
971         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
972         struct audio_endpoint *ep = out->ep;
973         size_t pkt_duration;
974
975         DBG("");
976
977         pkt_duration = ep->codec->get_mediapacket_duration(ep->codec_data);
978
979         return FIXED_A2DP_PLAYBACK_LATENCY_MS + pkt_duration / 1000;
980 }
981
982 static int out_set_volume(struct audio_stream_out *stream, float left,
983                                                                 float right)
984 {
985         DBG("");
986         /* volume controlled in audioflinger mixer (digital) */
987         return -ENOSYS;
988 }
989
990 static int out_get_render_position(const struct audio_stream_out *stream,
991                                                         uint32_t *dsp_frames)
992 {
993         DBG("");
994         return -ENOSYS;
995 }
996
997 static int out_add_audio_effect(const struct audio_stream *stream,
998                                                         effect_handle_t effect)
999 {
1000         DBG("");
1001         return -ENOSYS;
1002 }
1003
1004 static int out_remove_audio_effect(const struct audio_stream *stream,
1005                                                         effect_handle_t effect)
1006 {
1007         DBG("");
1008         return -ENOSYS;
1009 }
1010
1011 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1012 {
1013         DBG("");
1014         return -ENOSYS;
1015 }
1016
1017 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1018 {
1019         DBG("");
1020         return -ENOSYS;
1021 }
1022
1023 static size_t in_get_buffer_size(const struct audio_stream *stream)
1024 {
1025         DBG("");
1026         return -ENOSYS;
1027 }
1028
1029 static uint32_t in_get_channels(const struct audio_stream *stream)
1030 {
1031         DBG("");
1032         return -ENOSYS;
1033 }
1034
1035 static audio_format_t in_get_format(const struct audio_stream *stream)
1036 {
1037         DBG("");
1038         return -ENOSYS;
1039 }
1040
1041 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1042 {
1043         DBG("");
1044         return -ENOSYS;
1045 }
1046
1047 static int in_standby(struct audio_stream *stream)
1048 {
1049         DBG("");
1050         return -ENOSYS;
1051 }
1052
1053 static int in_dump(const struct audio_stream *stream, int fd)
1054 {
1055         DBG("");
1056         return -ENOSYS;
1057 }
1058
1059 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1060 {
1061         DBG("");
1062         return -ENOSYS;
1063 }
1064
1065 static char *in_get_parameters(const struct audio_stream *stream,
1066                                                         const char *keys)
1067 {
1068         DBG("");
1069         return strdup("");
1070 }
1071
1072 static int in_set_gain(struct audio_stream_in *stream, float gain)
1073 {
1074         DBG("");
1075         return -ENOSYS;
1076 }
1077
1078 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
1079                                                                 size_t bytes)
1080 {
1081         DBG("");
1082         return -ENOSYS;
1083 }
1084
1085 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1086 {
1087         DBG("");
1088         return -ENOSYS;
1089 }
1090
1091 static int in_add_audio_effect(const struct audio_stream *stream,
1092                                                         effect_handle_t effect)
1093 {
1094         DBG("");
1095         return -ENOSYS;
1096 }
1097
1098 static int in_remove_audio_effect(const struct audio_stream *stream,
1099                                                         effect_handle_t effect)
1100 {
1101         DBG("");
1102         return -ENOSYS;
1103 }
1104
1105 static int audio_open_output_stream(struct audio_hw_device *dev,
1106                                         audio_io_handle_t handle,
1107                                         audio_devices_t devices,
1108                                         audio_output_flags_t flags,
1109                                         struct audio_config *config,
1110                                         struct audio_stream_out **stream_out)
1111
1112 {
1113         struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1114         struct a2dp_stream_out *out;
1115
1116         out = calloc(1, sizeof(struct a2dp_stream_out));
1117         if (!out)
1118                 return -ENOMEM;
1119
1120         DBG("");
1121
1122         out->stream.common.get_sample_rate = out_get_sample_rate;
1123         out->stream.common.set_sample_rate = out_set_sample_rate;
1124         out->stream.common.get_buffer_size = out_get_buffer_size;
1125         out->stream.common.get_channels = out_get_channels;
1126         out->stream.common.get_format = out_get_format;
1127         out->stream.common.set_format = out_set_format;
1128         out->stream.common.standby = out_standby;
1129         out->stream.common.dump = out_dump;
1130         out->stream.common.set_parameters = out_set_parameters;
1131         out->stream.common.get_parameters = out_get_parameters;
1132         out->stream.common.add_audio_effect = out_add_audio_effect;
1133         out->stream.common.remove_audio_effect = out_remove_audio_effect;
1134         out->stream.get_latency = out_get_latency;
1135         out->stream.set_volume = out_set_volume;
1136         out->stream.write = out_write;
1137         out->stream.get_render_position = out_get_render_position;
1138
1139         /* We want to autoselect opened endpoint */
1140         out->ep = NULL;
1141
1142         if (!open_endpoint(&out->ep, &out->cfg))
1143                 goto fail;
1144
1145         DBG("rate=%d channels=%d format=%d", out->cfg.rate,
1146                                         out->cfg.channels, out->cfg.format);
1147
1148         if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1149                 out->downmix_buf = malloc(FIXED_BUFFER_SIZE / 2);
1150                 if (!out->downmix_buf)
1151                         goto fail;
1152         }
1153
1154         *stream_out = &out->stream;
1155         a2dp_dev->out = out;
1156
1157         out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1158
1159         return 0;
1160
1161 fail:
1162         error("audio: cannot open output stream");
1163         free(out);
1164         *stream_out = NULL;
1165         return -EIO;
1166 }
1167
1168 static void audio_close_output_stream(struct audio_hw_device *dev,
1169                                         struct audio_stream_out *stream)
1170 {
1171         struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1172         struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1173
1174         DBG("");
1175
1176         close_endpoint(a2dp_dev->out->ep);
1177
1178         free(out->downmix_buf);
1179
1180         free(stream);
1181         a2dp_dev->out = NULL;
1182 }
1183
1184 static int audio_set_parameters(struct audio_hw_device *dev,
1185                                                         const char *kvpairs)
1186 {
1187         struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1188         struct a2dp_stream_out *out = a2dp_dev->out;
1189
1190         DBG("");
1191
1192         if (!out)
1193                 return 0;
1194
1195         return out->stream.common.set_parameters((struct audio_stream *) out,
1196                                                                 kvpairs);
1197 }
1198
1199 static char *audio_get_parameters(const struct audio_hw_device *dev,
1200                                                         const char *keys)
1201 {
1202         DBG("");
1203         return strdup("");
1204 }
1205
1206 static int audio_init_check(const struct audio_hw_device *dev)
1207 {
1208         DBG("");
1209         return 0;
1210 }
1211
1212 static int audio_set_voice_volume(struct audio_hw_device *dev, float volume)
1213 {
1214         DBG("");
1215         return -ENOSYS;
1216 }
1217
1218 static int audio_set_master_volume(struct audio_hw_device *dev, float volume)
1219 {
1220         DBG("");
1221         return -ENOSYS;
1222 }
1223
1224 static int audio_set_mode(struct audio_hw_device *dev, int mode)
1225 {
1226         DBG("");
1227         return -ENOSYS;
1228 }
1229
1230 static int audio_set_mic_mute(struct audio_hw_device *dev, bool state)
1231 {
1232         DBG("");
1233         return -ENOSYS;
1234 }
1235
1236 static int audio_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1237 {
1238         DBG("");
1239         return -ENOSYS;
1240 }
1241
1242 static size_t audio_get_input_buffer_size(const struct audio_hw_device *dev,
1243                                         const struct audio_config *config)
1244 {
1245         DBG("");
1246         return -ENOSYS;
1247 }
1248
1249 static int audio_open_input_stream(struct audio_hw_device *dev,
1250                                         audio_io_handle_t handle,
1251                                         audio_devices_t devices,
1252                                         struct audio_config *config,
1253                                         struct audio_stream_in **stream_in)
1254 {
1255         struct audio_stream_in *in;
1256
1257         DBG("");
1258
1259         in = calloc(1, sizeof(struct audio_stream_in));
1260         if (!in)
1261                 return -ENOMEM;
1262
1263         in->common.get_sample_rate = in_get_sample_rate;
1264         in->common.set_sample_rate = in_set_sample_rate;
1265         in->common.get_buffer_size = in_get_buffer_size;
1266         in->common.get_channels = in_get_channels;
1267         in->common.get_format = in_get_format;
1268         in->common.set_format = in_set_format;
1269         in->common.standby = in_standby;
1270         in->common.dump = in_dump;
1271         in->common.set_parameters = in_set_parameters;
1272         in->common.get_parameters = in_get_parameters;
1273         in->common.add_audio_effect = in_add_audio_effect;
1274         in->common.remove_audio_effect = in_remove_audio_effect;
1275         in->set_gain = in_set_gain;
1276         in->read = in_read;
1277         in->get_input_frames_lost = in_get_input_frames_lost;
1278
1279         *stream_in = in;
1280
1281         return 0;
1282 }
1283
1284 static void audio_close_input_stream(struct audio_hw_device *dev,
1285                                         struct audio_stream_in *stream_in)
1286 {
1287         DBG("");
1288         free(stream_in);
1289 }
1290
1291 static int audio_dump(const audio_hw_device_t *device, int fd)
1292 {
1293         DBG("");
1294         return -ENOSYS;
1295 }
1296
1297 static void unload_codec(void *data)
1298 {
1299         struct audio_codec *codec = data;
1300
1301         if (codec->unload)
1302                 codec->unload();
1303 }
1304
1305 static int audio_close(hw_device_t *device)
1306 {
1307         struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *)device;
1308
1309         DBG("");
1310
1311         unregister_endpoints();
1312
1313         queue_destroy(loaded_codecs, unload_codec);
1314         loaded_codecs = NULL;
1315
1316         shutdown(listen_sk, SHUT_RDWR);
1317         shutdown(audio_sk, SHUT_RDWR);
1318
1319         pthread_join(ipc_th, NULL);
1320
1321         close(listen_sk);
1322         listen_sk = -1;
1323
1324         free(a2dp_dev);
1325         return 0;
1326 }
1327
1328 static void *ipc_handler(void *data)
1329 {
1330         bool done = false;
1331         struct pollfd pfd;
1332         int sk;
1333
1334         DBG("");
1335
1336         while (!done) {
1337                 DBG("Waiting for connection ...");
1338
1339                 sk = accept(listen_sk, NULL, NULL);
1340                 if (sk < 0) {
1341                         int err = errno;
1342
1343                         if (err == EINTR)
1344                                 continue;
1345
1346                         if (err != ECONNABORTED && err != EINVAL)
1347                                 error("audio: Failed to accept socket: %d (%s)",
1348                                                         err, strerror(err));
1349
1350                         break;
1351                 }
1352
1353                 pthread_mutex_lock(&sk_mutex);
1354                 audio_sk = sk;
1355                 pthread_mutex_unlock(&sk_mutex);
1356
1357                 DBG("Audio IPC: Connected");
1358
1359                 if (register_endpoints() != AUDIO_STATUS_SUCCESS) {
1360                         error("audio: Failed to register endpoints");
1361
1362                         unregister_endpoints();
1363
1364                         pthread_mutex_lock(&sk_mutex);
1365                         shutdown(audio_sk, SHUT_RDWR);
1366                         close(audio_sk);
1367                         audio_sk = -1;
1368                         pthread_mutex_unlock(&sk_mutex);
1369
1370                         continue;
1371                 }
1372
1373                 memset(&pfd, 0, sizeof(pfd));
1374                 pfd.fd = audio_sk;
1375                 pfd.events = POLLHUP | POLLERR | POLLNVAL;
1376
1377                 /* Check if socket is still alive. Empty while loop.*/
1378                 while (poll(&pfd, 1, -1) < 0 && errno == EINTR);
1379
1380                 if (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)) {
1381                         info("Audio HAL: Socket closed");
1382
1383                         pthread_mutex_lock(&sk_mutex);
1384                         close(audio_sk);
1385                         audio_sk = -1;
1386                         pthread_mutex_unlock(&sk_mutex);
1387                 }
1388         }
1389
1390         /* audio_sk is closed at this point, just cleanup endpoints states */
1391         memset(audio_endpoints, 0, sizeof(audio_endpoints));
1392
1393         info("Closing Audio IPC thread");
1394         return NULL;
1395 }
1396
1397 static int audio_ipc_init(void)
1398 {
1399         struct sockaddr_un addr;
1400         int err;
1401         int sk;
1402
1403         DBG("");
1404
1405         sk = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
1406         if (sk < 0) {
1407                 err = -errno;
1408                 error("audio: Failed to create socket: %d (%s)", -err,
1409                                                                 strerror(-err));
1410                 return err;
1411         }
1412
1413         memset(&addr, 0, sizeof(addr));
1414         addr.sun_family = AF_UNIX;
1415
1416         memcpy(addr.sun_path, BLUEZ_AUDIO_SK_PATH,
1417                                         sizeof(BLUEZ_AUDIO_SK_PATH));
1418
1419         if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1420                 err = -errno;
1421                 error("audio: Failed to bind socket: %d (%s)", -err,
1422                                                                 strerror(-err));
1423                 goto failed;
1424         }
1425
1426         if (listen(sk, 1) < 0) {
1427                 err = -errno;
1428                 error("audio: Failed to listen on the socket: %d (%s)", -err,
1429                                                                 strerror(-err));
1430                 goto failed;
1431         }
1432
1433         listen_sk = sk;
1434
1435         err = pthread_create(&ipc_th, NULL, ipc_handler, NULL);
1436         if (err) {
1437                 err = -err;
1438                 ipc_th = 0;
1439                 error("audio: Failed to start Audio IPC thread: %d (%s)",
1440                                                         -err, strerror(-err));
1441                 goto failed;
1442         }
1443
1444         return 0;
1445
1446 failed:
1447         close(sk);
1448         return err;
1449 }
1450
1451 static int audio_open(const hw_module_t *module, const char *name,
1452                                                         hw_device_t **device)
1453 {
1454         struct a2dp_audio_dev *a2dp_dev;
1455         size_t i;
1456         int err;
1457
1458         DBG("");
1459
1460         if (strcmp(name, AUDIO_HARDWARE_INTERFACE)) {
1461                 error("audio: interface %s not matching [%s]", name,
1462                                                 AUDIO_HARDWARE_INTERFACE);
1463                 return -EINVAL;
1464         }
1465
1466         err = audio_ipc_init();
1467         if (err < 0)
1468                 return err;
1469
1470         a2dp_dev = calloc(1, sizeof(struct a2dp_audio_dev));
1471         if (!a2dp_dev)
1472                 return -ENOMEM;
1473
1474         a2dp_dev->dev.common.tag = HARDWARE_DEVICE_TAG;
1475         a2dp_dev->dev.common.version = AUDIO_DEVICE_API_VERSION_CURRENT;
1476         a2dp_dev->dev.common.module = (struct hw_module_t *) module;
1477         a2dp_dev->dev.common.close = audio_close;
1478
1479         a2dp_dev->dev.init_check = audio_init_check;
1480         a2dp_dev->dev.set_voice_volume = audio_set_voice_volume;
1481         a2dp_dev->dev.set_master_volume = audio_set_master_volume;
1482         a2dp_dev->dev.set_mode = audio_set_mode;
1483         a2dp_dev->dev.set_mic_mute = audio_set_mic_mute;
1484         a2dp_dev->dev.get_mic_mute = audio_get_mic_mute;
1485         a2dp_dev->dev.set_parameters = audio_set_parameters;
1486         a2dp_dev->dev.get_parameters = audio_get_parameters;
1487         a2dp_dev->dev.get_input_buffer_size = audio_get_input_buffer_size;
1488         a2dp_dev->dev.open_output_stream = audio_open_output_stream;
1489         a2dp_dev->dev.close_output_stream = audio_close_output_stream;
1490         a2dp_dev->dev.open_input_stream = audio_open_input_stream;
1491         a2dp_dev->dev.close_input_stream = audio_close_input_stream;
1492         a2dp_dev->dev.dump = audio_dump;
1493
1494         loaded_codecs = queue_new();
1495
1496         for (i = 0; i < NUM_CODECS; i++) {
1497                 audio_codec_get_t get_codec = audio_codecs[i];
1498                 const struct audio_codec *codec = get_codec();
1499
1500                 if (codec->load && !codec->load())
1501                         continue;
1502
1503                 queue_push_tail(loaded_codecs, (void *) codec);
1504         }
1505
1506         /*
1507          * Note that &a2dp_dev->dev.common is the same pointer as a2dp_dev.
1508          * This results from the structure of following structs:a2dp_audio_dev,
1509          * audio_hw_device. We will rely on this later in the code.
1510          */
1511         *device = &a2dp_dev->dev.common;
1512
1513         return 0;
1514 }
1515
1516 static struct hw_module_methods_t hal_module_methods = {
1517         .open = audio_open,
1518 };
1519
1520 struct audio_module HAL_MODULE_INFO_SYM = {
1521         .common = {
1522                 .tag = HARDWARE_MODULE_TAG,
1523                 .version_major = 1,
1524                 .version_minor = 0,
1525                 .id = AUDIO_HARDWARE_MODULE_ID,
1526                 .name = "A2DP Bluez HW HAL",
1527                 .author = "Intel Corporation",
1528                 .methods = &hal_module_methods,
1529         },
1530 };