OSDN Git Service

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