OSDN Git Service

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