Upgrade bluez5_37 :Merge the code from private
[platform/upstream/bluez.git] / android / hal-sco.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
28 #include <hardware/audio.h>
29 #include <hardware/hardware.h>
30 #include <audio_utils/resampler.h>
31
32 #include "hal-utils.h"
33 #include "sco-msg.h"
34 #include "ipc-common.h"
35 #include "hal-log.h"
36 #include "hal.h"
37
38 #define AUDIO_STREAM_DEFAULT_RATE       44100
39 #define AUDIO_STREAM_SCO_RATE           8000
40 #define AUDIO_STREAM_DEFAULT_FORMAT     AUDIO_FORMAT_PCM_16_BIT
41
42 #define OUT_BUFFER_SIZE                 2560
43 #define OUT_STREAM_FRAMES               2560
44 #define IN_STREAM_FRAMES                5292
45
46 #define SOCKET_POLL_TIMEOUT_MS          500
47
48 static int listen_sk = -1;
49 static int ipc_sk = -1;
50
51 static int sco_fd = -1;
52 static uint16_t sco_mtu = 0;
53 static pthread_mutex_t sco_mutex = PTHREAD_MUTEX_INITIALIZER;
54
55 static pthread_t ipc_th = 0;
56 static pthread_mutex_t sk_mutex = PTHREAD_MUTEX_INITIALIZER;
57
58 static struct sco_stream_in *sco_stream_in = NULL;
59 static struct sco_stream_out *sco_stream_out = NULL;
60
61 struct sco_audio_config {
62         uint32_t rate;
63         uint32_t channels;
64         uint32_t frame_num;
65         audio_format_t format;
66 };
67
68 struct sco_stream_out {
69         struct audio_stream_out stream;
70
71         struct sco_audio_config cfg;
72
73         uint8_t *downmix_buf;
74         uint8_t *cache;
75         size_t cache_len;
76
77         size_t samples;
78         struct timespec start;
79
80         struct resampler_itfe *resampler;
81         int16_t *resample_buf;
82         uint32_t resample_frame_num;
83
84         bt_bdaddr_t bd_addr;
85 };
86
87 static void sco_close_socket(void)
88 {
89         DBG("sco fd %d", sco_fd);
90
91         if (sco_fd < 0)
92                 return;
93
94         shutdown(sco_fd, SHUT_RDWR);
95         close(sco_fd);
96         sco_fd = -1;
97 }
98
99 struct sco_stream_in {
100         struct audio_stream_in stream;
101
102         struct sco_audio_config cfg;
103
104         struct resampler_itfe *resampler;
105         int16_t *resample_buf;
106         uint32_t resample_frame_num;
107
108         bt_bdaddr_t bd_addr;
109 };
110
111 struct sco_dev {
112         struct audio_hw_device dev;
113         struct sco_stream_out *out;
114         struct sco_stream_in *in;
115 };
116
117 /*
118  * return the minimum frame numbers from resampling between BT stack's rate
119  * and audio flinger's. For output stream, 'output' shall be true, otherwise
120  * false for input streams at audio flinger side.
121  */
122 static size_t get_resample_frame_num(uint32_t sco_rate, uint32_t rate,
123                                                 size_t frame_num, bool output)
124 {
125         size_t resample_frames_num = frame_num * sco_rate / rate + output;
126
127         DBG("resampler: sco_rate %d frame_num %zd rate %d resample frames %zd",
128                                 sco_rate, frame_num, rate, resample_frames_num);
129
130         return resample_frames_num;
131 }
132
133 /* SCO IPC functions */
134
135 static int sco_ipc_cmd(uint8_t service_id, uint8_t opcode, uint16_t len,
136                         void *param, size_t *rsp_len, void *rsp, int *fd)
137 {
138         ssize_t ret;
139         struct msghdr msg;
140         struct iovec iv[2];
141         struct ipc_hdr cmd;
142         char cmsgbuf[CMSG_SPACE(sizeof(int))];
143         struct ipc_status s;
144         size_t s_len = sizeof(s);
145
146         pthread_mutex_lock(&sk_mutex);
147
148         if (ipc_sk < 0) {
149                 error("sco: Invalid cmd socket passed to sco_ipc_cmd");
150                 goto failed;
151         }
152
153         if (!rsp || !rsp_len) {
154                 memset(&s, 0, s_len);
155                 rsp_len = &s_len;
156                 rsp = &s;
157         }
158
159         memset(&msg, 0, sizeof(msg));
160         memset(&cmd, 0, sizeof(cmd));
161
162         cmd.service_id = service_id;
163         cmd.opcode = opcode;
164         cmd.len = len;
165
166         iv[0].iov_base = &cmd;
167         iv[0].iov_len = sizeof(cmd);
168
169         iv[1].iov_base = param;
170         iv[1].iov_len = len;
171
172         msg.msg_iov = iv;
173         msg.msg_iovlen = 2;
174
175         ret = sendmsg(ipc_sk, &msg, 0);
176         if (ret < 0) {
177                 error("sco: Sending command failed:%s", strerror(errno));
178                 goto failed;
179         }
180
181         /* socket was shutdown */
182         if (ret == 0) {
183                 error("sco: Command socket closed");
184                 goto failed;
185         }
186
187         memset(&msg, 0, sizeof(msg));
188         memset(&cmd, 0, sizeof(cmd));
189
190         iv[0].iov_base = &cmd;
191         iv[0].iov_len = sizeof(cmd);
192
193         iv[1].iov_base = rsp;
194         iv[1].iov_len = *rsp_len;
195
196         msg.msg_iov = iv;
197         msg.msg_iovlen = 2;
198
199         if (fd) {
200                 memset(cmsgbuf, 0, sizeof(cmsgbuf));
201                 msg.msg_control = cmsgbuf;
202                 msg.msg_controllen = sizeof(cmsgbuf);
203         }
204
205         ret = recvmsg(ipc_sk, &msg, 0);
206         if (ret < 0) {
207                 error("sco: Receiving command response failed:%s",
208                                                         strerror(errno));
209                 goto failed;
210         }
211
212         if (ret < (ssize_t) sizeof(cmd)) {
213                 error("sco: Too small response received(%zd bytes)", ret);
214                 goto failed;
215         }
216
217         if (cmd.service_id != service_id) {
218                 error("sco: Invalid service id (%u vs %u)", cmd.service_id,
219                                                                 service_id);
220                 goto failed;
221         }
222
223         if (ret != (ssize_t) (sizeof(cmd) + cmd.len)) {
224                 error("sco: Malformed response received(%zd bytes)", ret);
225                 goto failed;
226         }
227
228         if (cmd.opcode != opcode && cmd.opcode != SCO_OP_STATUS) {
229                 error("sco: Invalid opcode received (%u vs %u)",
230                                                 cmd.opcode, opcode);
231                 goto failed;
232         }
233
234         if (cmd.opcode == SCO_OP_STATUS) {
235                 struct ipc_status *s = rsp;
236
237                 if (sizeof(*s) != cmd.len) {
238                         error("sco: Invalid status length");
239                         goto failed;
240                 }
241
242                 if (s->code == SCO_STATUS_SUCCESS) {
243                         error("sco: Invalid success status response");
244                         goto failed;
245                 }
246
247                 pthread_mutex_unlock(&sk_mutex);
248
249                 return s->code;
250         }
251
252         pthread_mutex_unlock(&sk_mutex);
253
254         /* Receive auxiliary data in msg */
255         if (fd) {
256                 struct cmsghdr *cmsg;
257
258                 *fd = -1;
259
260                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
261                                         cmsg = CMSG_NXTHDR(&msg, cmsg)) {
262                         if (cmsg->cmsg_level == SOL_SOCKET
263                                         && cmsg->cmsg_type == SCM_RIGHTS) {
264                                 memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
265                                 break;
266                         }
267                 }
268
269                 if (*fd < 0)
270                         goto failed;
271         }
272
273         *rsp_len = cmd.len;
274
275         return SCO_STATUS_SUCCESS;
276
277 failed:
278         /* Some serious issue happen on IPC - recover */
279         shutdown(ipc_sk, SHUT_RDWR);
280         pthread_mutex_unlock(&sk_mutex);
281
282         return SCO_STATUS_FAILED;
283 }
284
285 static int ipc_get_sco_fd(bt_bdaddr_t *bd_addr)
286 {
287         int ret = SCO_STATUS_SUCCESS;
288
289         pthread_mutex_lock(&sco_mutex);
290
291         if (sco_fd < 0) {
292                 struct sco_cmd_get_fd cmd;
293                 struct sco_rsp_get_fd rsp;
294                 size_t rsp_len = sizeof(rsp);
295
296                 DBG("Getting SCO fd");
297
298                 memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));
299
300                 ret = sco_ipc_cmd(SCO_SERVICE_ID, SCO_OP_GET_FD, sizeof(cmd),
301                                                 &cmd, &rsp_len, &rsp, &sco_fd);
302
303                 /* Sometimes mtu returned is wrong */
304                 sco_mtu = /* rsp.mtu */ 48;
305         }
306
307         pthread_mutex_unlock(&sco_mutex);
308
309         return ret;
310 }
311
312 /* Audio stream functions */
313
314 static void downmix_to_mono(struct sco_stream_out *out, const uint8_t *buffer,
315                                                         size_t frame_num)
316 {
317         const int16_t *input = (const void *) buffer;
318         int16_t *output = (void *) out->downmix_buf;
319         size_t i;
320
321         for (i = 0; i < frame_num; i++) {
322                 int16_t l = get_le16(&input[i * 2]);
323                 int16_t r = get_le16(&input[i * 2 + 1]);
324
325                 put_le16((l + r) / 2, &output[i]);
326         }
327 }
328
329 static uint64_t timespec_diff_us(struct timespec *a, struct timespec *b)
330 {
331         struct timespec res;
332
333         res.tv_sec = a->tv_sec - b->tv_sec;
334         res.tv_nsec = a->tv_nsec - b->tv_nsec;
335
336         if (res.tv_nsec < 0) {
337                 res.tv_sec--;
338                 res.tv_nsec += 1000000000ll; /* 1sec */
339         }
340
341         return res.tv_sec * 1000000ll + res.tv_nsec / 1000ll;
342 }
343
344 static bool write_data(struct sco_stream_out *out, const uint8_t *buffer,
345                                                                 size_t bytes)
346 {
347         struct pollfd pfd;
348         size_t len, written = 0;
349         int ret;
350         uint8_t *p;
351         uint64_t audio_sent_us, audio_passed_us;
352
353         pfd.fd = sco_fd;
354         pfd.events = POLLOUT | POLLHUP | POLLNVAL;
355
356         while (bytes > written) {
357                 struct timespec now;
358
359                 /* poll for sending */
360                 if (poll(&pfd, 1, SOCKET_POLL_TIMEOUT_MS) == 0) {
361                         DBG("timeout fd %d", sco_fd);
362                         return false;
363                 }
364
365                 if (pfd.revents & (POLLHUP | POLLNVAL)) {
366                         error("error fd %d, events 0x%x", sco_fd, pfd.revents);
367                         return false;
368                 }
369
370                 len = bytes - written > sco_mtu ? sco_mtu : bytes - written;
371
372                 clock_gettime(CLOCK_REALTIME, &now);
373                 /* Mark start of the stream */
374                 if (!out->samples)
375                         memcpy(&out->start, &now, sizeof(out->start));
376
377                 audio_sent_us = out->samples * 1000000ll / AUDIO_STREAM_SCO_RATE;
378                 audio_passed_us = timespec_diff_us(&now, &out->start);
379                 if ((int) (audio_sent_us - audio_passed_us) > 1500) {
380                         struct timespec timeout = {0,
381                                                 (audio_sent_us -
382                                                 audio_passed_us) * 1000};
383                         DBG("Sleeping for %d ms",
384                                         (int) (audio_sent_us - audio_passed_us));
385                         nanosleep(&timeout, NULL);
386                 } else if ((int)(audio_passed_us - audio_sent_us) > 50000) {
387                         DBG("\n\nResync\n\n");
388                         out->samples = 0;
389                         memcpy(&out->start, &now, sizeof(out->start));
390                 }
391
392                 if (out->cache_len) {
393                         DBG("First packet cache_len %zd", out->cache_len);
394                         memcpy(out->cache + out->cache_len, buffer,
395                                                 sco_mtu - out->cache_len);
396                         p = out->cache;
397                 } else {
398                         if (bytes - written >= sco_mtu)
399                                 p = (void *) buffer + written;
400                         else {
401                                 memcpy(out->cache, buffer + written,
402                                                         bytes - written);
403                                 out->cache_len = bytes - written;
404                                 DBG("Last packet, cache %zd bytes",
405                                                         bytes - written);
406                                 written += bytes - written;
407                                 continue;
408                         }
409                 }
410
411                 ret = write(sco_fd, p, len);
412                 if (ret > 0) {
413                         if (out->cache_len) {
414                                 written = sco_mtu - out->cache_len;
415                                 out->cache_len = 0;
416                         } else
417                                 written += ret;
418
419                         out->samples += ret / 2;
420
421                         DBG("written %d samples %zd total %zd bytes",
422                                         ret, out->samples, written);
423                         continue;
424                 }
425
426                 if (errno == EAGAIN) {
427                         ret = errno;
428                         warn("write failed (%d)", ret);
429                         continue;
430                 }
431
432                 if (errno != EINTR) {
433                         ret = errno;
434                         error("write failed (%d) fd %d bytes %zd", ret, sco_fd,
435                                                                         bytes);
436                         return false;
437                 }
438         }
439
440         DBG("written %zd bytes", bytes);
441
442         return true;
443 }
444
445 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
446                                                                 size_t bytes)
447 {
448         struct sco_stream_out *out = (struct sco_stream_out *) stream;
449 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
450         size_t frame_num = bytes / audio_stream_out_frame_size(stream);
451 #else
452         size_t frame_num = bytes / audio_stream_frame_size(&out->stream.common);
453 #endif
454         size_t output_frame_num = frame_num;
455         void *send_buf = out->downmix_buf;
456         size_t total;
457
458         DBG("write to fd %d bytes %zu", sco_fd, bytes);
459
460         if (ipc_get_sco_fd(&out->bd_addr) != SCO_STATUS_SUCCESS)
461                 return -1;
462
463         if (!out->downmix_buf) {
464                 error("sco: downmix buffer not initialized");
465                 return -1;
466         }
467
468         downmix_to_mono(out, buffer, frame_num);
469
470         if (out->resampler) {
471                 int ret;
472
473                 /* limit resampler's output within what resample buf can hold */
474                 output_frame_num = out->resample_frame_num;
475
476                 ret = out->resampler->resample_from_input(out->resampler,
477                                                         send_buf,
478                                                         &frame_num,
479                                                         out->resample_buf,
480                                                         &output_frame_num);
481                 if (ret) {
482                         error("Failed to resample frames: %zd input %zd (%s)",
483                                 frame_num, output_frame_num, strerror(ret));
484                         return -1;
485                 }
486
487                 send_buf = out->resample_buf;
488
489                 DBG("Resampled: frame_num %zd, output_frame_num %zd",
490                                                 frame_num, output_frame_num);
491         }
492
493         total = output_frame_num * sizeof(int16_t) * 1;
494
495         DBG("total %zd", total);
496
497         if (!write_data(out, send_buf, total))
498                 return -1;
499
500         return bytes;
501 }
502
503 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
504 {
505         struct sco_stream_out *out = (struct sco_stream_out *) stream;
506
507         DBG("rate %u", out->cfg.rate);
508
509         return out->cfg.rate;
510 }
511
512 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
513 {
514         DBG("rate %u", rate);
515
516         return 0;
517 }
518
519 static size_t out_get_buffer_size(const struct audio_stream *stream)
520 {
521         struct sco_stream_out *out = (struct sco_stream_out *) stream;
522 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
523         size_t size = audio_stream_out_frame_size(&out->stream) *
524                                                         out->cfg.frame_num;
525 #else
526         size_t size = audio_stream_frame_size(&out->stream.common) *
527                                                         out->cfg.frame_num;
528 #endif
529
530         /* buffer size without resampling */
531         if (out->cfg.rate == AUDIO_STREAM_SCO_RATE)
532                 size = 576 * 2;
533
534         DBG("buf size %zd", size);
535
536         return size;
537 }
538
539 static uint32_t out_get_channels(const struct audio_stream *stream)
540 {
541         struct sco_stream_out *out = (struct sco_stream_out *) stream;
542
543         DBG("channels num: %u", popcount(out->cfg.channels));
544
545         return out->cfg.channels;
546 }
547
548 static audio_format_t out_get_format(const struct audio_stream *stream)
549 {
550         struct sco_stream_out *out = (struct sco_stream_out *) stream;
551
552         DBG("format: %u", out->cfg.format);
553
554         return out->cfg.format;
555 }
556
557 static int out_set_format(struct audio_stream *stream, audio_format_t format)
558 {
559         DBG("");
560
561         return -ENOSYS;
562 }
563
564 static int out_standby(struct audio_stream *stream)
565 {
566         DBG("");
567
568         return 0;
569 }
570
571 static int out_dump(const struct audio_stream *stream, int fd)
572 {
573         DBG("");
574
575         return -ENOSYS;
576 }
577
578 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
579 {
580         DBG("%s", kvpairs);
581
582         return 0;
583 }
584
585 static char *out_get_parameters(const struct audio_stream *stream,
586                                                         const char *keys)
587 {
588         DBG("");
589
590         return strdup("");
591 }
592
593 static uint32_t out_get_latency(const struct audio_stream_out *stream)
594 {
595         DBG("");
596
597         return 0;
598 }
599
600 static int out_set_volume(struct audio_stream_out *stream, float left,
601                                                                 float right)
602 {
603         DBG("");
604
605         return -ENOSYS;
606 }
607
608 static int out_get_render_position(const struct audio_stream_out *stream,
609                                                         uint32_t *dsp_frames)
610 {
611         DBG("");
612
613         return -ENOSYS;
614 }
615
616 static int out_add_audio_effect(const struct audio_stream *stream,
617                                                         effect_handle_t effect)
618 {
619         DBG("");
620
621         return -ENOSYS;
622 }
623
624 static int out_remove_audio_effect(const struct audio_stream *stream,
625                                                         effect_handle_t effect)
626 {
627         DBG("");
628
629         return -ENOSYS;
630 }
631
632 static int sco_open_output_stream_real(struct audio_hw_device *dev,
633                                         audio_io_handle_t handle,
634                                         audio_devices_t devices,
635                                         audio_output_flags_t flags,
636                                         struct audio_config *config,
637                                         struct audio_stream_out **stream_out,
638                                         const char *address)
639 {
640         struct sco_dev *adev = (struct sco_dev *) dev;
641         struct sco_stream_out *out;
642         int chan_num, ret;
643         size_t resample_size;
644
645         DBG("config %p device flags 0x%02x", config, devices);
646
647         if (sco_stream_out) {
648                 DBG("stream_out already open");
649                 return -EIO;
650         }
651
652         out = calloc(1, sizeof(struct sco_stream_out));
653         if (!out)
654                 return -ENOMEM;
655
656         DBG("stream %p sco fd %d mtu %u", out, sco_fd, sco_mtu);
657
658         out->stream.common.get_sample_rate = out_get_sample_rate;
659         out->stream.common.set_sample_rate = out_set_sample_rate;
660         out->stream.common.get_buffer_size = out_get_buffer_size;
661         out->stream.common.get_channels = out_get_channels;
662         out->stream.common.get_format = out_get_format;
663         out->stream.common.set_format = out_set_format;
664         out->stream.common.standby = out_standby;
665         out->stream.common.dump = out_dump;
666         out->stream.common.set_parameters = out_set_parameters;
667         out->stream.common.get_parameters = out_get_parameters;
668         out->stream.common.add_audio_effect = out_add_audio_effect;
669         out->stream.common.remove_audio_effect = out_remove_audio_effect;
670         out->stream.get_latency = out_get_latency;
671         out->stream.set_volume = out_set_volume;
672         out->stream.write = out_write;
673         out->stream.get_render_position = out_get_render_position;
674
675 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
676         if (address) {
677                 DBG("address %s", address);
678
679                 str2bt_bdaddr_t(address, &out->bd_addr);
680         }
681 #endif
682
683         if (ipc_get_sco_fd(&out->bd_addr) != SCO_STATUS_SUCCESS)
684                 DBG("SCO is not connected yet; get fd on write()");
685
686         if (config) {
687                 DBG("config: rate %u chan mask %x format %d offload %p",
688                                 config->sample_rate, config->channel_mask,
689                                 config->format, &config->offload_info);
690
691                 out->cfg.format = config->format;
692                 out->cfg.channels = config->channel_mask;
693                 out->cfg.rate = config->sample_rate;
694         } else {
695                 out->cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
696                 out->cfg.channels = AUDIO_CHANNEL_OUT_STEREO;
697                 out->cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
698         }
699
700         out->cfg.frame_num = OUT_STREAM_FRAMES;
701
702         out->downmix_buf = malloc(out_get_buffer_size(&out->stream.common));
703         if (!out->downmix_buf) {
704                 free(out);
705                 return -ENOMEM;
706         }
707
708         out->cache = malloc(sco_mtu);
709         if (!out->cache) {
710                 free(out->downmix_buf);
711                 free(out);
712                 return -ENOMEM;
713         }
714
715         if (out->cfg.rate == AUDIO_STREAM_SCO_RATE)
716                 goto skip_resampler;
717
718         /* Channel numbers for resampler */
719         chan_num = 1;
720
721         ret = create_resampler(out->cfg.rate, AUDIO_STREAM_SCO_RATE, chan_num,
722                                                 RESAMPLER_QUALITY_DEFAULT, NULL,
723                                                 &out->resampler);
724         if (ret) {
725                 error("Failed to create resampler (%s)", strerror(-ret));
726                 goto failed;
727         }
728
729         out->resample_frame_num = get_resample_frame_num(AUDIO_STREAM_SCO_RATE,
730                                                         out->cfg.rate,
731                                                         out->cfg.frame_num, 1);
732
733         if (!out->resample_frame_num) {
734                 error("frame num is too small to resample, discard it");
735                 goto failed;
736         }
737
738         resample_size = sizeof(int16_t) * chan_num * out->resample_frame_num;
739
740         out->resample_buf = malloc(resample_size);
741         if (!out->resample_buf) {
742                 error("failed to allocate resample buffer for %u frames",
743                                                 out->resample_frame_num);
744                 goto failed;
745         }
746
747         DBG("Resampler: input %d output %d chan %d frames %u size %zd",
748                                 out->cfg.rate, AUDIO_STREAM_SCO_RATE, chan_num,
749                                 out->resample_frame_num, resample_size);
750 skip_resampler:
751         *stream_out = &out->stream;
752         adev->out = out;
753         sco_stream_out = out;
754
755         return 0;
756 failed:
757         if (out->resampler)
758                 release_resampler(out->resampler);
759
760         free(out->cache);
761         free(out->downmix_buf);
762         free(out);
763         *stream_out = NULL;
764         adev->out = NULL;
765         sco_stream_out = NULL;
766
767         return ret;
768 }
769
770 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
771 static int sco_open_output_stream(struct audio_hw_device *dev,
772                                         audio_io_handle_t handle,
773                                         audio_devices_t devices,
774                                         audio_output_flags_t flags,
775                                         struct audio_config *config,
776                                         struct audio_stream_out **stream_out,
777                                         const char *address)
778 {
779         return  sco_open_output_stream_real(dev, handle, devices, flags,
780                                                 config, stream_out, address);
781 }
782 #else
783 static int sco_open_output_stream(struct audio_hw_device *dev,
784                                         audio_io_handle_t handle,
785                                         audio_devices_t devices,
786                                         audio_output_flags_t flags,
787                                         struct audio_config *config,
788                                         struct audio_stream_out **stream_out)
789 {
790         return sco_open_output_stream_real(dev, handle, devices, flags,
791                                                 config, stream_out, NULL);
792 }
793 #endif
794
795 static void sco_close_output_stream(struct audio_hw_device *dev,
796                                         struct audio_stream_out *stream_out)
797 {
798         struct sco_dev *sco_dev = (struct sco_dev *) dev;
799         struct sco_stream_out *out = (struct sco_stream_out *) stream_out;
800
801         DBG("dev %p stream %p fd %d", dev, out, sco_fd);
802
803         if (out->resampler) {
804                 release_resampler(out->resampler);
805                 free(out->resample_buf);
806         }
807
808         free(out->cache);
809         free(out->downmix_buf);
810         free(out);
811         sco_dev->out = NULL;
812
813         pthread_mutex_lock(&sco_mutex);
814
815         sco_stream_out = NULL;
816
817         if (!sco_stream_in)
818                 sco_close_socket();
819
820         pthread_mutex_unlock(&sco_mutex);
821 }
822
823 static int sco_set_parameters(struct audio_hw_device *dev,
824                                                         const char *kvpairs)
825 {
826         DBG("%s", kvpairs);
827
828         return 0;
829 }
830
831 static char *sco_get_parameters(const struct audio_hw_device *dev,
832                                                         const char *keys)
833 {
834         DBG("");
835
836         return strdup("");
837 }
838
839 static int sco_init_check(const struct audio_hw_device *dev)
840 {
841         DBG("");
842
843         return 0;
844 }
845
846 static int sco_set_voice_volume(struct audio_hw_device *dev, float volume)
847 {
848         DBG("%f", volume);
849
850         return 0;
851 }
852
853 static int sco_set_master_volume(struct audio_hw_device *dev, float volume)
854 {
855         DBG("%f", volume);
856
857         return 0;
858 }
859
860 static int sco_set_mode(struct audio_hw_device *dev, int mode)
861 {
862         DBG("");
863
864         return -ENOSYS;
865 }
866
867 static int sco_set_mic_mute(struct audio_hw_device *dev, bool state)
868 {
869         DBG("");
870
871         return -ENOSYS;
872 }
873
874 static int sco_get_mic_mute(const struct audio_hw_device *dev, bool *state)
875 {
876         DBG("");
877
878         return -ENOSYS;
879 }
880
881 static size_t sco_get_input_buffer_size(const struct audio_hw_device *dev,
882                                         const struct audio_config *config)
883 {
884         DBG("");
885
886         return -ENOSYS;
887 }
888
889 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
890 {
891         struct sco_stream_in *in = (struct sco_stream_in *) stream;
892
893         DBG("rate %u", in->cfg.rate);
894
895         return in->cfg.rate;
896 }
897
898 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
899 {
900         DBG("rate %u", rate);
901
902         return 0;
903 }
904
905 static size_t in_get_buffer_size(const struct audio_stream *stream)
906 {
907         struct sco_stream_in *in = (struct sco_stream_in *) stream;
908 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
909         size_t size = audio_stream_in_frame_size(&in->stream) *
910                                                         in->cfg.frame_num;
911 #else
912         size_t size = audio_stream_frame_size(&in->stream.common) *
913                                                         in->cfg.frame_num;
914 #endif
915
916         /* buffer size without resampling */
917         if (in->cfg.rate == AUDIO_STREAM_SCO_RATE)
918                 size = 576;
919
920         DBG("buf size %zd", size);
921
922         return size;
923 }
924
925 static uint32_t in_get_channels(const struct audio_stream *stream)
926 {
927         struct sco_stream_in *in = (struct sco_stream_in *) stream;
928
929         DBG("channels num: %u", popcount(in->cfg.channels));
930
931         return in->cfg.channels;
932 }
933
934 static audio_format_t in_get_format(const struct audio_stream *stream)
935 {
936         struct sco_stream_in *in = (struct sco_stream_in *) stream;
937
938         DBG("format: %u", in->cfg.format);
939
940         return in->cfg.format;
941 }
942
943 static int in_set_format(struct audio_stream *stream, audio_format_t format)
944 {
945         DBG("");
946
947         return -ENOSYS;
948 }
949
950 static int in_standby(struct audio_stream *stream)
951 {
952         DBG("");
953
954         return 0;
955 }
956
957 static int in_dump(const struct audio_stream *stream, int fd)
958 {
959         DBG("");
960
961         return -ENOSYS;
962 }
963
964 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
965 {
966         DBG("%s", kvpairs);
967
968         return 0;
969 }
970
971 static char *in_get_parameters(const struct audio_stream *stream,
972                                                         const char *keys)
973 {
974         DBG("");
975
976         return strdup("");
977 }
978
979 static int in_add_audio_effect(const struct audio_stream *stream,
980                                                         effect_handle_t effect)
981 {
982         DBG("");
983
984         return -ENOSYS;
985 }
986
987 static int in_remove_audio_effect(const struct audio_stream *stream,
988                                                         effect_handle_t effect)
989 {
990         DBG("");
991
992         return -ENOSYS;
993 }
994
995 static int in_set_gain(struct audio_stream_in *stream, float gain)
996 {
997         DBG("");
998
999         return -ENOSYS;
1000 }
1001
1002 static bool read_data(struct sco_stream_in *in, char *buffer, size_t bytes)
1003 {
1004         struct pollfd pfd;
1005         size_t len, read_bytes = 0;
1006
1007         pfd.fd = sco_fd;
1008         pfd.events = POLLIN | POLLHUP | POLLNVAL;
1009
1010         while (bytes > read_bytes) {
1011                 int ret;
1012
1013                 /* poll for reading */
1014                 if (poll(&pfd, 1, SOCKET_POLL_TIMEOUT_MS) == 0) {
1015                         DBG("timeout fd %d", sco_fd);
1016                         return false;
1017                 }
1018
1019                 if (pfd.revents & (POLLHUP | POLLNVAL)) {
1020                         error("error fd %d, events 0x%x", sco_fd, pfd.revents);
1021                         return false;
1022                 }
1023
1024                 len = bytes - read_bytes > sco_mtu ? sco_mtu :
1025                                                         bytes - read_bytes;
1026
1027                 ret = read(sco_fd, buffer + read_bytes, len);
1028                 if (ret > 0) {
1029                         read_bytes += ret;
1030                         DBG("read %d total %zd", ret, read_bytes);
1031                         continue;
1032                 }
1033
1034                 if (errno == EAGAIN) {
1035                         ret = errno;
1036                         warn("read failed (%d)", ret);
1037                         continue;
1038                 }
1039
1040                 if (errno != EINTR) {
1041                         ret = errno;
1042                         error("read failed (%d) fd %d bytes %zd", ret, sco_fd,
1043                                                                         bytes);
1044                         return false;
1045                 }
1046         }
1047
1048         DBG("read %zd bytes", read_bytes);
1049
1050         return true;
1051 }
1052
1053 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
1054                                                                 size_t bytes)
1055 {
1056         struct sco_stream_in *in = (struct sco_stream_in *) stream;
1057         size_t frame_size, frame_num, input_frame_num;
1058         void *read_buf = buffer;
1059         size_t total = bytes;
1060         int ret;
1061
1062 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1063         frame_size = audio_stream_in_frame_size(&in->stream);
1064 #else
1065         frame_size = audio_stream_frame_size(&stream->common);
1066 #endif
1067
1068         if (!frame_size)
1069                 return -1;
1070
1071         frame_num = bytes / frame_size;
1072         input_frame_num = frame_num;
1073
1074         DBG("Read from fd %d bytes %zu", sco_fd, bytes);
1075
1076         if (ipc_get_sco_fd(&in->bd_addr) != SCO_STATUS_SUCCESS)
1077                 return -1;
1078
1079         if (!in->resampler && in->cfg.rate != AUDIO_STREAM_SCO_RATE) {
1080                 error("Cannot find resampler");
1081                 return -1;
1082         }
1083
1084         if (in->resampler) {
1085                 input_frame_num = get_resample_frame_num(AUDIO_STREAM_SCO_RATE,
1086                                                         in->cfg.rate,
1087                                                         frame_num, 0);
1088                 if (input_frame_num > in->resample_frame_num) {
1089                         DBG("resize input frames from %zd to %d",
1090                                 input_frame_num, in->resample_frame_num);
1091                         input_frame_num = in->resample_frame_num;
1092                 }
1093
1094                 read_buf = in->resample_buf;
1095
1096                 total = input_frame_num * sizeof(int16_t) * 1;
1097         }
1098
1099         if(!read_data(in, read_buf, total))
1100                 return -1;
1101
1102         if (in->resampler) {
1103                 ret = in->resampler->resample_from_input(in->resampler,
1104                                                         in->resample_buf,
1105                                                         &input_frame_num,
1106                                                         (int16_t *) buffer,
1107                                                         &frame_num);
1108                 if (ret) {
1109                         error("Failed to resample frames: %zd input %zd (%s)",
1110                                         frame_num, input_frame_num,
1111                                         strerror(ret));
1112                         return -1;
1113                 }
1114
1115                 DBG("resampler: remain %zd output %zd frames", input_frame_num,
1116                                                                 frame_num);
1117         }
1118
1119         return bytes;
1120 }
1121
1122 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1123 {
1124         DBG("");
1125
1126         return -ENOSYS;
1127 }
1128
1129 static int sco_open_input_stream_real(struct audio_hw_device *dev,
1130                                         audio_io_handle_t handle,
1131                                         audio_devices_t devices,
1132                                         struct audio_config *config,
1133                                         struct audio_stream_in **stream_in,
1134                                         audio_input_flags_t flags,
1135                                         const char *address,
1136                                         audio_source_t source)
1137 {
1138         struct sco_dev *sco_dev = (struct sco_dev *) dev;
1139         struct sco_stream_in *in;
1140         int chan_num, ret;
1141         size_t resample_size;
1142
1143         DBG("config %p device flags 0x%02x", config, devices);
1144
1145         if (sco_stream_in) {
1146                 DBG("stream_in already open");
1147                 ret = -EIO;
1148                 goto failed2;
1149         }
1150
1151         in = calloc(1, sizeof(struct sco_stream_in));
1152         if (!in)
1153                 return -ENOMEM;
1154
1155         DBG("stream %p sco fd %d mtu %u", in, sco_fd, sco_mtu);
1156
1157         in->stream.common.get_sample_rate = in_get_sample_rate;
1158         in->stream.common.set_sample_rate = in_set_sample_rate;
1159         in->stream.common.get_buffer_size = in_get_buffer_size;
1160         in->stream.common.get_channels = in_get_channels;
1161         in->stream.common.get_format = in_get_format;
1162         in->stream.common.set_format = in_set_format;
1163         in->stream.common.standby = in_standby;
1164         in->stream.common.dump = in_dump;
1165         in->stream.common.set_parameters = in_set_parameters;
1166         in->stream.common.get_parameters = in_get_parameters;
1167         in->stream.common.add_audio_effect = in_add_audio_effect;
1168         in->stream.common.remove_audio_effect = in_remove_audio_effect;
1169         in->stream.set_gain = in_set_gain;
1170         in->stream.read = in_read;
1171         in->stream.get_input_frames_lost = in_get_input_frames_lost;
1172
1173 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1174         if (address) {
1175                 DBG("address %s", address);
1176
1177                 str2bt_bdaddr_t(address, &in->bd_addr);
1178         }
1179 #endif
1180
1181         if (config) {
1182                 DBG("config: rate %u chan mask %x format %d offload %p",
1183                                 config->sample_rate, config->channel_mask,
1184                                 config->format, &config->offload_info);
1185
1186                 in->cfg.format = config->format;
1187                 in->cfg.channels = config->channel_mask;
1188                 in->cfg.rate = config->sample_rate;
1189         } else {
1190                 in->cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
1191                 in->cfg.channels = AUDIO_CHANNEL_OUT_MONO;
1192                 in->cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
1193         }
1194
1195         in->cfg.frame_num = IN_STREAM_FRAMES;
1196
1197         if (in->cfg.rate == AUDIO_STREAM_SCO_RATE)
1198                 goto skip_resampler;
1199
1200         /* Channel numbers for resampler */
1201         chan_num = 1;
1202
1203         ret = create_resampler(AUDIO_STREAM_SCO_RATE, in->cfg.rate, chan_num,
1204                                                 RESAMPLER_QUALITY_DEFAULT, NULL,
1205                                                 &in->resampler);
1206         if (ret) {
1207                 error("Failed to create resampler (%s)", strerror(-ret));
1208                 goto failed;
1209         }
1210
1211         in->resample_frame_num = get_resample_frame_num(AUDIO_STREAM_SCO_RATE,
1212                                                         in->cfg.rate,
1213                                                         in->cfg.frame_num, 0);
1214
1215         resample_size = sizeof(int16_t) * chan_num * in->resample_frame_num;
1216
1217         in->resample_buf = malloc(resample_size);
1218         if (!in->resample_buf) {
1219                 error("failed to allocate resample buffer for %d frames",
1220                                                         in->resample_frame_num);
1221                 goto failed;
1222         }
1223
1224         DBG("Resampler: input %d output %d chan %d frames %u size %zd",
1225                                 AUDIO_STREAM_SCO_RATE, in->cfg.rate, chan_num,
1226                                 in->resample_frame_num, resample_size);
1227 skip_resampler:
1228         *stream_in = &in->stream;
1229         sco_dev->in = in;
1230         sco_stream_in = in;
1231
1232         return 0;
1233 failed:
1234         if (in->resampler)
1235                 release_resampler(in->resampler);
1236         free(in);
1237 failed2:
1238         *stream_in = NULL;
1239         sco_dev->in = NULL;
1240         sco_stream_in = NULL;
1241
1242         return ret;
1243 }
1244
1245 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1246 static int sco_open_input_stream(struct audio_hw_device *dev,
1247                                         audio_io_handle_t handle,
1248                                         audio_devices_t devices,
1249                                         struct audio_config *config,
1250                                         struct audio_stream_in **stream_in,
1251                                         audio_input_flags_t flags,
1252                                         const char *address,
1253                                         audio_source_t source)
1254 {
1255         return sco_open_input_stream_real(dev, handle, devices, config,
1256                                                 stream_in, flags, address,
1257                                                 source);
1258 }
1259 #else
1260 static int sco_open_input_stream(struct audio_hw_device *dev,
1261                                         audio_io_handle_t handle,
1262                                         audio_devices_t devices,
1263                                         struct audio_config *config,
1264                                         struct audio_stream_in **stream_in)
1265 {
1266         return sco_open_input_stream_real(dev, handle, devices, config,
1267                                                 stream_in, 0, NULL, 0);
1268 }
1269 #endif
1270
1271 static void sco_close_input_stream(struct audio_hw_device *dev,
1272                                         struct audio_stream_in *stream_in)
1273 {
1274         struct sco_dev *sco_dev = (struct sco_dev *) dev;
1275         struct sco_stream_in *in = (struct sco_stream_in *) stream_in;
1276
1277         DBG("dev %p stream %p fd %d", dev, in, sco_fd);
1278
1279         if (in->resampler) {
1280                 release_resampler(in->resampler);
1281                 free(in->resample_buf);
1282         }
1283
1284         free(in);
1285         sco_dev->in = NULL;
1286
1287         pthread_mutex_lock(&sco_mutex);
1288
1289         sco_stream_in = NULL;
1290
1291         if (!sco_stream_out)
1292                 sco_close_socket();
1293
1294         pthread_mutex_unlock(&sco_mutex);
1295 }
1296
1297 static int sco_dump(const audio_hw_device_t *device, int fd)
1298 {
1299         DBG("");
1300
1301         return 0;
1302 }
1303
1304 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1305 static int set_master_mute(struct audio_hw_device *dev, bool mute)
1306 {
1307         DBG("");
1308         return -ENOSYS;
1309 }
1310
1311 static int get_master_mute(struct audio_hw_device *dev, bool *mute)
1312 {
1313         DBG("");
1314         return -ENOSYS;
1315 }
1316
1317 static int create_audio_patch(struct audio_hw_device *dev,
1318                                         unsigned int num_sources,
1319                                         const struct audio_port_config *sources,
1320                                         unsigned int num_sinks,
1321                                         const struct audio_port_config *sinks,
1322                                         audio_patch_handle_t *handle)
1323 {
1324         DBG("");
1325         return -ENOSYS;
1326 }
1327
1328 static int release_audio_patch(struct audio_hw_device *dev,
1329                                         audio_patch_handle_t handle)
1330 {
1331         DBG("");
1332         return -ENOSYS;
1333 }
1334
1335 static int get_audio_port(struct audio_hw_device *dev, struct audio_port *port)
1336 {
1337         DBG("");
1338         return -ENOSYS;
1339 }
1340
1341 static int set_audio_port_config(struct audio_hw_device *dev,
1342                                         const struct audio_port_config *config)
1343 {
1344         DBG("");
1345         return -ENOSYS;
1346 }
1347 #endif
1348
1349 static int sco_close(hw_device_t *device)
1350 {
1351         DBG("");
1352
1353         free(device);
1354
1355         return 0;
1356 }
1357
1358 static void *ipc_handler(void *data)
1359 {
1360         bool done = false;
1361         struct pollfd pfd;
1362         int sk;
1363
1364         DBG("");
1365
1366         while (!done) {
1367                 DBG("Waiting for connection ...");
1368
1369                 sk = accept(listen_sk, NULL, NULL);
1370                 if (sk < 0) {
1371                         int err = errno;
1372
1373                         if (err == EINTR)
1374                                 continue;
1375
1376                         if (err != ECONNABORTED && err != EINVAL)
1377                                 error("sco: Failed to accept socket: %d (%s)",
1378                                                         err, strerror(err));
1379
1380                         break;
1381                 }
1382
1383                 pthread_mutex_lock(&sk_mutex);
1384                 ipc_sk = sk;
1385                 pthread_mutex_unlock(&sk_mutex);
1386
1387                 DBG("SCO IPC: Connected");
1388
1389                 memset(&pfd, 0, sizeof(pfd));
1390                 pfd.fd = ipc_sk;
1391                 pfd.events = POLLHUP | POLLERR | POLLNVAL;
1392
1393                 /* Check if socket is still alive. Empty while loop.*/
1394                 while (poll(&pfd, 1, -1) < 0 && errno == EINTR);
1395
1396                 info("SCO HAL: Socket closed");
1397
1398                 pthread_mutex_lock(&sk_mutex);
1399                 close(ipc_sk);
1400                 ipc_sk = -1;
1401                 pthread_mutex_unlock(&sk_mutex);
1402         }
1403
1404         info("Closing SCO IPC thread");
1405         return NULL;
1406 }
1407
1408 static int sco_ipc_init(void)
1409 {
1410         struct sockaddr_un addr;
1411         int err;
1412         int sk;
1413
1414         DBG("");
1415
1416         sk = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
1417         if (sk < 0) {
1418                 err = -errno;
1419                 error("sco: Failed to create socket: %d (%s)", -err,
1420                                                                 strerror(-err));
1421                 return err;
1422         }
1423
1424         memset(&addr, 0, sizeof(addr));
1425         addr.sun_family = AF_UNIX;
1426
1427         memcpy(addr.sun_path, BLUEZ_SCO_SK_PATH, sizeof(BLUEZ_SCO_SK_PATH));
1428
1429         if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1430                 err = -errno;
1431                 error("sco: Failed to bind socket: %d (%s)", -err,
1432                                                                 strerror(-err));
1433                 goto failed;
1434         }
1435
1436         if (listen(sk, 1) < 0) {
1437                 err = -errno;
1438                 error("sco: Failed to listen on the socket: %d (%s)", -err,
1439                                                                 strerror(-err));
1440                 goto failed;
1441         }
1442
1443         listen_sk = sk;
1444
1445         err = pthread_create(&ipc_th, NULL, ipc_handler, NULL);
1446         if (err) {
1447                 err = -err;
1448                 ipc_th = 0;
1449                 error("sco: Failed to start IPC thread: %d (%s)",
1450                                                         -err, strerror(-err));
1451                 goto failed;
1452         }
1453
1454         return 0;
1455
1456 failed:
1457         close(sk);
1458         return err;
1459 }
1460
1461 static int sco_open(const hw_module_t *module, const char *name,
1462                                                         hw_device_t **device)
1463 {
1464         struct sco_dev *dev;
1465         int err;
1466
1467         DBG("");
1468
1469         if (strcmp(name, AUDIO_HARDWARE_INTERFACE)) {
1470                 error("SCO: interface %s not matching [%s]", name,
1471                                                 AUDIO_HARDWARE_INTERFACE);
1472                 return -EINVAL;
1473         }
1474
1475         err = sco_ipc_init();
1476         if (err < 0)
1477                 return err;
1478
1479         dev = calloc(1, sizeof(struct sco_dev));
1480         if (!dev)
1481                 return -ENOMEM;
1482
1483         dev->dev.common.tag = HARDWARE_DEVICE_TAG;
1484         dev->dev.common.version = AUDIO_DEVICE_API_VERSION_CURRENT;
1485         dev->dev.common.module = (struct hw_module_t *) module;
1486         dev->dev.common.close = sco_close;
1487
1488         dev->dev.init_check = sco_init_check;
1489         dev->dev.set_voice_volume = sco_set_voice_volume;
1490         dev->dev.set_master_volume = sco_set_master_volume;
1491         dev->dev.set_mode = sco_set_mode;
1492         dev->dev.set_mic_mute = sco_set_mic_mute;
1493         dev->dev.get_mic_mute = sco_get_mic_mute;
1494         dev->dev.set_parameters = sco_set_parameters;
1495         dev->dev.get_parameters = sco_get_parameters;
1496         dev->dev.get_input_buffer_size = sco_get_input_buffer_size;
1497         dev->dev.open_output_stream = sco_open_output_stream;
1498         dev->dev.close_output_stream = sco_close_output_stream;
1499         dev->dev.open_input_stream = sco_open_input_stream;
1500         dev->dev.close_input_stream = sco_close_input_stream;
1501         dev->dev.dump = sco_dump;
1502 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1503         dev->dev.set_master_mute = set_master_mute;
1504         dev->dev.get_master_mute = get_master_mute;
1505         dev->dev.create_audio_patch = create_audio_patch;
1506         dev->dev.release_audio_patch = release_audio_patch;
1507         dev->dev.get_audio_port = get_audio_port;
1508         dev->dev.set_audio_port_config = set_audio_port_config;
1509 #endif
1510
1511         *device = &dev->dev.common;
1512
1513         return 0;
1514 }
1515
1516 static struct hw_module_methods_t hal_module_methods = {
1517         .open = sco_open,
1518 };
1519
1520 struct audio_module HAL_MODULE_INFO_SYM = {
1521         .common = {
1522                 .tag = HARDWARE_MODULE_TAG,
1523                 .version_major = 1,
1524                 .version_minor = 0,
1525                 .id = AUDIO_HARDWARE_MODULE_ID,
1526                 .name = "SCO Audio HW HAL",
1527                 .author = "Intel Corporation",
1528                 .methods = &hal_module_methods,
1529         },
1530 };