tizen 2.3.1 release
[framework/connectivity/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 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1058         size_t frame_size = audio_stream_in_frame_size(&in->stream);
1059 #else
1060         size_t frame_size = audio_stream_frame_size(&stream->common);
1061 #endif
1062         size_t frame_num = bytes / frame_size;
1063         size_t input_frame_num = frame_num;
1064         void *read_buf = buffer;
1065         size_t total = bytes;
1066         int ret;
1067
1068         DBG("Read from fd %d bytes %zu", sco_fd, bytes);
1069
1070         if (ipc_get_sco_fd(&in->bd_addr) != SCO_STATUS_SUCCESS)
1071                 return -1;
1072
1073         if (!in->resampler && in->cfg.rate != AUDIO_STREAM_SCO_RATE) {
1074                 error("Cannot find resampler");
1075                 return -1;
1076         }
1077
1078         if (in->resampler) {
1079                 input_frame_num = get_resample_frame_num(AUDIO_STREAM_SCO_RATE,
1080                                                         in->cfg.rate,
1081                                                         frame_num, 0);
1082                 if (input_frame_num > in->resample_frame_num) {
1083                         DBG("resize input frames from %zd to %d",
1084                                 input_frame_num, in->resample_frame_num);
1085                         input_frame_num = in->resample_frame_num;
1086                 }
1087
1088                 read_buf = in->resample_buf;
1089
1090                 total = input_frame_num * sizeof(int16_t) * 1;
1091         }
1092
1093         if(!read_data(in, read_buf, total))
1094                 return -1;
1095
1096         if (in->resampler) {
1097                 ret = in->resampler->resample_from_input(in->resampler,
1098                                                         in->resample_buf,
1099                                                         &input_frame_num,
1100                                                         (int16_t *) buffer,
1101                                                         &frame_num);
1102                 if (ret) {
1103                         error("Failed to resample frames: %zd input %zd (%s)",
1104                                         frame_num, input_frame_num,
1105                                         strerror(ret));
1106                         return -1;
1107                 }
1108
1109                 DBG("resampler: remain %zd output %zd frames", input_frame_num,
1110                                                                 frame_num);
1111         }
1112
1113         return bytes;
1114 }
1115
1116 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1117 {
1118         DBG("");
1119
1120         return -ENOSYS;
1121 }
1122
1123 static int sco_open_input_stream_real(struct audio_hw_device *dev,
1124                                         audio_io_handle_t handle,
1125                                         audio_devices_t devices,
1126                                         struct audio_config *config,
1127                                         struct audio_stream_in **stream_in,
1128                                         audio_input_flags_t flags,
1129                                         const char *address,
1130                                         audio_source_t source)
1131 {
1132         struct sco_dev *sco_dev = (struct sco_dev *) dev;
1133         struct sco_stream_in *in;
1134         int chan_num, ret;
1135         size_t resample_size;
1136
1137         DBG("config %p device flags 0x%02x", config, devices);
1138
1139         if (sco_stream_in) {
1140                 DBG("stream_in already open");
1141                 ret = -EIO;
1142                 goto failed2;
1143         }
1144
1145         in = calloc(1, sizeof(struct sco_stream_in));
1146         if (!in)
1147                 return -ENOMEM;
1148
1149         DBG("stream %p sco fd %d mtu %u", in, sco_fd, sco_mtu);
1150
1151         in->stream.common.get_sample_rate = in_get_sample_rate;
1152         in->stream.common.set_sample_rate = in_set_sample_rate;
1153         in->stream.common.get_buffer_size = in_get_buffer_size;
1154         in->stream.common.get_channels = in_get_channels;
1155         in->stream.common.get_format = in_get_format;
1156         in->stream.common.set_format = in_set_format;
1157         in->stream.common.standby = in_standby;
1158         in->stream.common.dump = in_dump;
1159         in->stream.common.set_parameters = in_set_parameters;
1160         in->stream.common.get_parameters = in_get_parameters;
1161         in->stream.common.add_audio_effect = in_add_audio_effect;
1162         in->stream.common.remove_audio_effect = in_remove_audio_effect;
1163         in->stream.set_gain = in_set_gain;
1164         in->stream.read = in_read;
1165         in->stream.get_input_frames_lost = in_get_input_frames_lost;
1166
1167 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1168         if (address) {
1169                 DBG("address %s", address);
1170
1171                 str2bt_bdaddr_t(address, &in->bd_addr);
1172         }
1173 #endif
1174
1175         if (config) {
1176                 DBG("config: rate %u chan mask %x format %d offload %p",
1177                                 config->sample_rate, config->channel_mask,
1178                                 config->format, &config->offload_info);
1179
1180                 in->cfg.format = config->format;
1181                 in->cfg.channels = config->channel_mask;
1182                 in->cfg.rate = config->sample_rate;
1183         } else {
1184                 in->cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
1185                 in->cfg.channels = AUDIO_CHANNEL_OUT_MONO;
1186                 in->cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
1187         }
1188
1189         in->cfg.frame_num = IN_STREAM_FRAMES;
1190
1191         if (in->cfg.rate == AUDIO_STREAM_SCO_RATE)
1192                 goto skip_resampler;
1193
1194         /* Channel numbers for resampler */
1195         chan_num = 1;
1196
1197         ret = create_resampler(AUDIO_STREAM_SCO_RATE, in->cfg.rate, chan_num,
1198                                                 RESAMPLER_QUALITY_DEFAULT, NULL,
1199                                                 &in->resampler);
1200         if (ret) {
1201                 error("Failed to create resampler (%s)", strerror(-ret));
1202                 goto failed;
1203         }
1204
1205         in->resample_frame_num = get_resample_frame_num(AUDIO_STREAM_SCO_RATE,
1206                                                         in->cfg.rate,
1207                                                         in->cfg.frame_num, 0);
1208
1209         resample_size = sizeof(int16_t) * chan_num * in->resample_frame_num;
1210
1211         in->resample_buf = malloc(resample_size);
1212         if (!in->resample_buf) {
1213                 error("failed to allocate resample buffer for %d frames",
1214                                                         in->resample_frame_num);
1215                 goto failed;
1216         }
1217
1218         DBG("Resampler: input %d output %d chan %d frames %u size %zd",
1219                                 AUDIO_STREAM_SCO_RATE, in->cfg.rate, chan_num,
1220                                 in->resample_frame_num, resample_size);
1221 skip_resampler:
1222         *stream_in = &in->stream;
1223         sco_dev->in = in;
1224         sco_stream_in = in;
1225
1226         return 0;
1227 failed:
1228         if (in->resampler)
1229                 release_resampler(in->resampler);
1230         free(in);
1231 failed2:
1232         *stream_in = NULL;
1233         sco_dev->in = NULL;
1234         sco_stream_in = NULL;
1235
1236         return ret;
1237 }
1238
1239 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1240 static int sco_open_input_stream(struct audio_hw_device *dev,
1241                                         audio_io_handle_t handle,
1242                                         audio_devices_t devices,
1243                                         struct audio_config *config,
1244                                         struct audio_stream_in **stream_in,
1245                                         audio_input_flags_t flags,
1246                                         const char *address,
1247                                         audio_source_t source)
1248 {
1249         return sco_open_input_stream_real(dev, handle, devices, config,
1250                                                 stream_in, flags, address,
1251                                                 source);
1252 }
1253 #else
1254 static int sco_open_input_stream(struct audio_hw_device *dev,
1255                                         audio_io_handle_t handle,
1256                                         audio_devices_t devices,
1257                                         struct audio_config *config,
1258                                         struct audio_stream_in **stream_in)
1259 {
1260         return sco_open_input_stream_real(dev, handle, devices, config,
1261                                                 stream_in, 0, NULL, 0);
1262 }
1263 #endif
1264
1265 static void sco_close_input_stream(struct audio_hw_device *dev,
1266                                         struct audio_stream_in *stream_in)
1267 {
1268         struct sco_dev *sco_dev = (struct sco_dev *) dev;
1269         struct sco_stream_in *in = (struct sco_stream_in *) stream_in;
1270
1271         DBG("dev %p stream %p fd %d", dev, in, sco_fd);
1272
1273         if (in->resampler) {
1274                 release_resampler(in->resampler);
1275                 free(in->resample_buf);
1276         }
1277
1278         free(in);
1279         sco_dev->in = NULL;
1280
1281         pthread_mutex_lock(&sco_mutex);
1282
1283         sco_stream_in = NULL;
1284
1285         if (!sco_stream_out)
1286                 sco_close_socket();
1287
1288         pthread_mutex_unlock(&sco_mutex);
1289 }
1290
1291 static int sco_dump(const audio_hw_device_t *device, int fd)
1292 {
1293         DBG("");
1294
1295         return 0;
1296 }
1297
1298 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1299 static int set_master_mute(struct audio_hw_device *dev, bool mute)
1300 {
1301         DBG("");
1302         return -ENOSYS;
1303 }
1304
1305 static int get_master_mute(struct audio_hw_device *dev, bool *mute)
1306 {
1307         DBG("");
1308         return -ENOSYS;
1309 }
1310
1311 static int create_audio_patch(struct audio_hw_device *dev,
1312                                         unsigned int num_sources,
1313                                         const struct audio_port_config *sources,
1314                                         unsigned int num_sinks,
1315                                         const struct audio_port_config *sinks,
1316                                         audio_patch_handle_t *handle)
1317 {
1318         DBG("");
1319         return -ENOSYS;
1320 }
1321
1322 static int release_audio_patch(struct audio_hw_device *dev,
1323                                         audio_patch_handle_t handle)
1324 {
1325         DBG("");
1326         return -ENOSYS;
1327 }
1328
1329 static int get_audio_port(struct audio_hw_device *dev, struct audio_port *port)
1330 {
1331         DBG("");
1332         return -ENOSYS;
1333 }
1334
1335 static int set_audio_port_config(struct audio_hw_device *dev,
1336                                         const struct audio_port_config *config)
1337 {
1338         DBG("");
1339         return -ENOSYS;
1340 }
1341 #endif
1342
1343 static int sco_close(hw_device_t *device)
1344 {
1345         DBG("");
1346
1347         free(device);
1348
1349         return 0;
1350 }
1351
1352 static void *ipc_handler(void *data)
1353 {
1354         bool done = false;
1355         struct pollfd pfd;
1356         int sk;
1357
1358         DBG("");
1359
1360         while (!done) {
1361                 DBG("Waiting for connection ...");
1362
1363                 sk = accept(listen_sk, NULL, NULL);
1364                 if (sk < 0) {
1365                         int err = errno;
1366
1367                         if (err == EINTR)
1368                                 continue;
1369
1370                         if (err != ECONNABORTED && err != EINVAL)
1371                                 error("sco: Failed to accept socket: %d (%s)",
1372                                                         err, strerror(err));
1373
1374                         break;
1375                 }
1376
1377                 pthread_mutex_lock(&sk_mutex);
1378                 ipc_sk = sk;
1379                 pthread_mutex_unlock(&sk_mutex);
1380
1381                 DBG("SCO IPC: Connected");
1382
1383                 memset(&pfd, 0, sizeof(pfd));
1384                 pfd.fd = ipc_sk;
1385                 pfd.events = POLLHUP | POLLERR | POLLNVAL;
1386
1387                 /* Check if socket is still alive. Empty while loop.*/
1388                 while (poll(&pfd, 1, -1) < 0 && errno == EINTR);
1389
1390                 info("SCO HAL: Socket closed");
1391
1392                 pthread_mutex_lock(&sk_mutex);
1393                 close(ipc_sk);
1394                 ipc_sk = -1;
1395                 pthread_mutex_unlock(&sk_mutex);
1396         }
1397
1398         info("Closing SCO IPC thread");
1399         return NULL;
1400 }
1401
1402 static int sco_ipc_init(void)
1403 {
1404         struct sockaddr_un addr;
1405         int err;
1406         int sk;
1407
1408         DBG("");
1409
1410         sk = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
1411         if (sk < 0) {
1412                 err = -errno;
1413                 error("sco: Failed to create socket: %d (%s)", -err,
1414                                                                 strerror(-err));
1415                 return err;
1416         }
1417
1418         memset(&addr, 0, sizeof(addr));
1419         addr.sun_family = AF_UNIX;
1420
1421         memcpy(addr.sun_path, BLUEZ_SCO_SK_PATH, sizeof(BLUEZ_SCO_SK_PATH));
1422
1423         if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1424                 err = -errno;
1425                 error("sco: Failed to bind socket: %d (%s)", -err,
1426                                                                 strerror(-err));
1427                 goto failed;
1428         }
1429
1430         if (listen(sk, 1) < 0) {
1431                 err = -errno;
1432                 error("sco: Failed to listen on the socket: %d (%s)", -err,
1433                                                                 strerror(-err));
1434                 goto failed;
1435         }
1436
1437         listen_sk = sk;
1438
1439         err = pthread_create(&ipc_th, NULL, ipc_handler, NULL);
1440         if (err) {
1441                 err = -err;
1442                 ipc_th = 0;
1443                 error("sco: Failed to start IPC thread: %d (%s)",
1444                                                         -err, strerror(-err));
1445                 goto failed;
1446         }
1447
1448         return 0;
1449
1450 failed:
1451         close(sk);
1452         return err;
1453 }
1454
1455 static int sco_open(const hw_module_t *module, const char *name,
1456                                                         hw_device_t **device)
1457 {
1458         struct sco_dev *dev;
1459         int err;
1460
1461         DBG("");
1462
1463         if (strcmp(name, AUDIO_HARDWARE_INTERFACE)) {
1464                 error("SCO: interface %s not matching [%s]", name,
1465                                                 AUDIO_HARDWARE_INTERFACE);
1466                 return -EINVAL;
1467         }
1468
1469         err = sco_ipc_init();
1470         if (err < 0)
1471                 return err;
1472
1473         dev = calloc(1, sizeof(struct sco_dev));
1474         if (!dev)
1475                 return -ENOMEM;
1476
1477         dev->dev.common.tag = HARDWARE_DEVICE_TAG;
1478         dev->dev.common.version = AUDIO_DEVICE_API_VERSION_CURRENT;
1479         dev->dev.common.module = (struct hw_module_t *) module;
1480         dev->dev.common.close = sco_close;
1481
1482         dev->dev.init_check = sco_init_check;
1483         dev->dev.set_voice_volume = sco_set_voice_volume;
1484         dev->dev.set_master_volume = sco_set_master_volume;
1485         dev->dev.set_mode = sco_set_mode;
1486         dev->dev.set_mic_mute = sco_set_mic_mute;
1487         dev->dev.get_mic_mute = sco_get_mic_mute;
1488         dev->dev.set_parameters = sco_set_parameters;
1489         dev->dev.get_parameters = sco_get_parameters;
1490         dev->dev.get_input_buffer_size = sco_get_input_buffer_size;
1491         dev->dev.open_output_stream = sco_open_output_stream;
1492         dev->dev.close_output_stream = sco_close_output_stream;
1493         dev->dev.open_input_stream = sco_open_input_stream;
1494         dev->dev.close_input_stream = sco_close_input_stream;
1495         dev->dev.dump = sco_dump;
1496 #if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
1497         dev->dev.set_master_mute = set_master_mute;
1498         dev->dev.get_master_mute = get_master_mute;
1499         dev->dev.create_audio_patch = create_audio_patch;
1500         dev->dev.release_audio_patch = release_audio_patch;
1501         dev->dev.get_audio_port = get_audio_port;
1502         dev->dev.set_audio_port_config = set_audio_port_config;
1503 #endif
1504
1505         *device = &dev->dev.common;
1506
1507         return 0;
1508 }
1509
1510 static struct hw_module_methods_t hal_module_methods = {
1511         .open = sco_open,
1512 };
1513
1514 struct audio_module HAL_MODULE_INFO_SYM = {
1515         .common = {
1516                 .tag = HARDWARE_MODULE_TAG,
1517                 .version_major = 1,
1518                 .version_minor = 0,
1519                 .id = AUDIO_HARDWARE_MODULE_ID,
1520                 .name = "SCO Audio HW HAL",
1521                 .author = "Intel Corporation",
1522                 .methods = &hal_module_methods,
1523         },
1524 };