OSDN Git Service

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