OSDN Git Service

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