2 * Copyright (C) 2013 Intel Corporation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 #include <sys/socket.h>
27 #include <arpa/inet.h>
30 #include <hardware/audio.h>
31 #include <hardware/hardware.h>
35 #include "audio-msg.h"
36 #include "ipc-common.h"
39 #include "../profiles/audio/a2dp-codecs.h"
40 #include "../src/shared/util.h"
42 #define FIXED_A2DP_PLAYBACK_LATENCY_MS 25
44 #define FIXED_BUFFER_SIZE (20 * 512)
46 #define MAX_FRAMES_IN_PAYLOAD 15
48 static const uint8_t a2dp_src_uuid[] = {
49 0x00, 0x00, 0x11, 0x0a, 0x00, 0x00, 0x10, 0x00,
50 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb };
52 static int listen_sk = -1;
53 static int audio_sk = -1;
55 static pthread_t ipc_th = 0;
56 static pthread_mutex_t sk_mutex = PTHREAD_MUTEX_INITIALIZER;
58 #if __BYTE_ORDER == __LITTLE_ENDIAN
69 uint16_t sequence_number;
73 } __attribute__ ((packed));
76 unsigned frame_count:4;
78 unsigned is_last_fragment:1;
79 unsigned is_first_fragment:1;
80 unsigned is_fragmented:1;
81 } __attribute__ ((packed));
83 #elif __BYTE_ORDER == __BIG_ENDIAN
94 uint16_t sequence_number;
98 } __attribute__ ((packed));
101 unsigned is_fragmented:1;
102 unsigned is_first_fragment:1;
103 unsigned is_last_fragment:1;
105 unsigned frame_count:4;
106 } __attribute__ ((packed));
109 #error "Unknown byte order"
112 struct media_packet {
113 struct rtp_header hdr;
114 struct rtp_payload payload;
118 struct audio_input_config {
121 audio_format_t format;
132 size_t out_frame_len;
134 unsigned frame_duration;
135 unsigned frames_per_packet;
138 static void timespec_add(struct timespec *base, uint64_t time_us,
139 struct timespec *res)
141 res->tv_sec = base->tv_sec + time_us / 1000000;
142 res->tv_nsec = base->tv_nsec + (time_us % 1000000) * 1000;
144 if (res->tv_nsec >= 1000000000) {
146 res->tv_nsec -= 1000000000;
150 static void timespec_diff(struct timespec *a, struct timespec *b,
151 struct timespec *res)
153 res->tv_sec = a->tv_sec - b->tv_sec;
154 res->tv_nsec = a->tv_nsec - b->tv_nsec;
156 if (res->tv_nsec < 0) {
158 res->tv_nsec += 1000000000; /* 1sec */
162 static uint64_t timespec_diff_us(struct timespec *a, struct timespec *b)
166 timespec_diff(a, b, &res);
168 return res.tv_sec * 1000000ll + res.tv_nsec / 1000ll;
172 /* Bionic does not have clock_nanosleep() prototype in time.h even though
173 * it provides its implementation.
175 extern int clock_nanosleep(clockid_t clock_id, int flags,
176 const struct timespec *request,
177 struct timespec *remain);
180 static int sbc_get_presets(struct audio_preset *preset, size_t *len);
181 static int sbc_codec_init(struct audio_preset *preset, uint16_t mtu,
183 static int sbc_cleanup(void *codec_data);
184 static int sbc_get_config(void *codec_data, struct audio_input_config *config);
185 static size_t sbc_get_buffer_size(void *codec_data);
186 static size_t sbc_get_mediapacket_duration(void *codec_data);
187 static ssize_t sbc_encode_mediapacket(void *codec_data, const uint8_t *buffer,
188 size_t len, struct media_packet *mp,
189 size_t mp_data_len, size_t *written);
194 int (*get_presets) (struct audio_preset *preset, size_t *len);
196 int (*init) (struct audio_preset *preset, uint16_t mtu,
198 int (*cleanup) (void *codec_data);
199 int (*get_config) (void *codec_data,
200 struct audio_input_config *config);
201 size_t (*get_buffer_size) (void *codec_data);
202 size_t (*get_mediapacket_duration) (void *codec_data);
203 ssize_t (*encode_mediapacket) (void *codec_data, const uint8_t *buffer,
204 size_t len, struct media_packet *mp,
205 size_t mp_data_len, size_t *written);
208 static const struct audio_codec audio_codecs[] = {
210 .type = A2DP_CODEC_SBC,
212 .get_presets = sbc_get_presets,
214 .init = sbc_codec_init,
215 .cleanup = sbc_cleanup,
216 .get_config = sbc_get_config,
217 .get_buffer_size = sbc_get_buffer_size,
218 .get_mediapacket_duration = sbc_get_mediapacket_duration,
219 .encode_mediapacket = sbc_encode_mediapacket,
223 #define NUM_CODECS (sizeof(audio_codecs) / sizeof(audio_codecs[0]))
225 #define MAX_AUDIO_ENDPOINTS NUM_CODECS
227 struct audio_endpoint {
229 const struct audio_codec *codec;
233 struct media_packet *mp;
238 struct timespec start;
241 static struct audio_endpoint audio_endpoints[MAX_AUDIO_ENDPOINTS];
244 AUDIO_A2DP_STATE_NONE,
245 AUDIO_A2DP_STATE_STANDBY,
246 AUDIO_A2DP_STATE_SUSPENDED,
247 AUDIO_A2DP_STATE_STARTED
250 struct a2dp_stream_out {
251 struct audio_stream_out stream;
253 struct audio_endpoint *ep;
254 enum a2dp_state_t audio_state;
255 struct audio_input_config cfg;
257 uint8_t *downmix_buf;
260 struct a2dp_audio_dev {
261 struct audio_hw_device dev;
262 struct a2dp_stream_out *out;
265 static const a2dp_sbc_t sbc_presets[] = {
267 .frequency = SBC_SAMPLING_FREQ_44100 | SBC_SAMPLING_FREQ_48000,
268 .channel_mode = SBC_CHANNEL_MODE_MONO |
269 SBC_CHANNEL_MODE_DUAL_CHANNEL |
270 SBC_CHANNEL_MODE_STEREO |
271 SBC_CHANNEL_MODE_JOINT_STEREO,
272 .subbands = SBC_SUBBANDS_4 | SBC_SUBBANDS_8,
273 .allocation_method = SBC_ALLOCATION_SNR |
274 SBC_ALLOCATION_LOUDNESS,
275 .block_length = SBC_BLOCK_LENGTH_4 | SBC_BLOCK_LENGTH_8 |
276 SBC_BLOCK_LENGTH_12 | SBC_BLOCK_LENGTH_16,
277 .min_bitpool = MIN_BITPOOL,
278 .max_bitpool = MAX_BITPOOL
281 .frequency = SBC_SAMPLING_FREQ_44100,
282 .channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO,
283 .subbands = SBC_SUBBANDS_8,
284 .allocation_method = SBC_ALLOCATION_LOUDNESS,
285 .block_length = SBC_BLOCK_LENGTH_16,
286 .min_bitpool = MIN_BITPOOL,
287 .max_bitpool = MAX_BITPOOL
290 .frequency = SBC_SAMPLING_FREQ_48000,
291 .channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO,
292 .subbands = SBC_SUBBANDS_8,
293 .allocation_method = SBC_ALLOCATION_LOUDNESS,
294 .block_length = SBC_BLOCK_LENGTH_16,
295 .min_bitpool = MIN_BITPOOL,
296 .max_bitpool = MAX_BITPOOL
300 static int sbc_get_presets(struct audio_preset *preset, size_t *len)
305 uint8_t *ptr = (uint8_t *) preset;
306 size_t preset_size = sizeof(*preset) + sizeof(a2dp_sbc_t);
308 count = sizeof(sbc_presets) / sizeof(sbc_presets[0]);
310 for (i = 0; i < count; i++) {
311 preset = (struct audio_preset *) ptr;
313 if (new_len + preset_size > *len)
316 preset->len = sizeof(a2dp_sbc_t);
317 memcpy(preset->data, &sbc_presets[i], preset->len);
319 new_len += preset_size;
328 static int sbc_freq2int(uint8_t freq)
331 case SBC_SAMPLING_FREQ_16000:
333 case SBC_SAMPLING_FREQ_32000:
335 case SBC_SAMPLING_FREQ_44100:
337 case SBC_SAMPLING_FREQ_48000:
344 static const char *sbc_mode2str(uint8_t mode)
347 case SBC_CHANNEL_MODE_MONO:
349 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
350 return "DualChannel";
351 case SBC_CHANNEL_MODE_STEREO:
353 case SBC_CHANNEL_MODE_JOINT_STEREO:
354 return "JointStereo";
360 static int sbc_blocks2int(uint8_t blocks)
363 case SBC_BLOCK_LENGTH_4:
365 case SBC_BLOCK_LENGTH_8:
367 case SBC_BLOCK_LENGTH_12:
369 case SBC_BLOCK_LENGTH_16:
376 static int sbc_subbands2int(uint8_t subbands)
388 static const char *sbc_allocation2str(uint8_t allocation)
390 switch (allocation) {
391 case SBC_ALLOCATION_SNR:
393 case SBC_ALLOCATION_LOUDNESS:
400 static void sbc_init_encoder(struct sbc_data *sbc_data)
402 a2dp_sbc_t *in = &sbc_data->sbc;
403 sbc_t *out = &sbc_data->enc;
405 sbc_init_a2dp(out, 0L, in, sizeof(*in));
407 out->endian = SBC_LE;
408 out->bitpool = in->max_bitpool;
410 DBG("frequency=%d channel_mode=%s block_length=%d subbands=%d "
411 "allocation=%s bitpool=%d-%d",
412 sbc_freq2int(in->frequency),
413 sbc_mode2str(in->channel_mode),
414 sbc_blocks2int(in->block_length),
415 sbc_subbands2int(in->subbands),
416 sbc_allocation2str(in->allocation_method),
417 in->min_bitpool, in->max_bitpool);
420 static int sbc_codec_init(struct audio_preset *preset, uint16_t payload_len,
423 struct sbc_data *sbc_data;
425 size_t out_frame_len;
428 if (preset->len != sizeof(a2dp_sbc_t)) {
429 error("SBC: preset size mismatch");
430 return AUDIO_STATUS_FAILED;
433 sbc_data = calloc(sizeof(struct sbc_data), 1);
435 return AUDIO_STATUS_FAILED;
437 memcpy(&sbc_data->sbc, preset->data, preset->len);
439 sbc_init_encoder(sbc_data);
441 in_frame_len = sbc_get_codesize(&sbc_data->enc);
442 out_frame_len = sbc_get_frame_length(&sbc_data->enc);
443 num_frames = payload_len / out_frame_len;
445 sbc_data->in_frame_len = in_frame_len;
446 sbc_data->in_buf_size = num_frames * in_frame_len;
448 sbc_data->out_frame_len = out_frame_len;
450 sbc_data->frame_duration = sbc_get_frame_duration(&sbc_data->enc);
451 sbc_data->frames_per_packet = num_frames;
453 DBG("in_frame_len=%zu out_frame_len=%zu frames_per_packet=%zu",
454 in_frame_len, out_frame_len, num_frames);
456 *codec_data = sbc_data;
458 return AUDIO_STATUS_SUCCESS;
461 static int sbc_cleanup(void *codec_data)
463 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
465 sbc_finish(&sbc_data->enc);
468 return AUDIO_STATUS_SUCCESS;
471 static int sbc_get_config(void *codec_data, struct audio_input_config *config)
473 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
475 switch (sbc_data->sbc.frequency) {
476 case SBC_SAMPLING_FREQ_16000:
477 config->rate = 16000;
479 case SBC_SAMPLING_FREQ_32000:
480 config->rate = 32000;
482 case SBC_SAMPLING_FREQ_44100:
483 config->rate = 44100;
485 case SBC_SAMPLING_FREQ_48000:
486 config->rate = 48000;
489 return AUDIO_STATUS_FAILED;
491 config->channels = sbc_data->sbc.channel_mode == SBC_CHANNEL_MODE_MONO ?
492 AUDIO_CHANNEL_OUT_MONO :
493 AUDIO_CHANNEL_OUT_STEREO;
494 config->format = AUDIO_FORMAT_PCM_16_BIT;
496 return AUDIO_STATUS_SUCCESS;
499 static size_t sbc_get_buffer_size(void *codec_data)
501 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
503 return sbc_data->in_buf_size;
506 static size_t sbc_get_mediapacket_duration(void *codec_data)
508 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
510 return sbc_data->frame_duration * sbc_data->frames_per_packet;
513 static ssize_t sbc_encode_mediapacket(void *codec_data, const uint8_t *buffer,
514 size_t len, struct media_packet *mp,
515 size_t mp_data_len, size_t *written)
517 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
520 uint8_t frame_count = 0;
522 while (len - consumed >= sbc_data->in_frame_len &&
523 mp_data_len - encoded >= sbc_data->out_frame_len &&
524 frame_count < MAX_FRAMES_IN_PAYLOAD) {
528 read = sbc_encode(&sbc_data->enc, buffer + consumed,
529 sbc_data->in_frame_len, mp->data + encoded,
530 mp_data_len - encoded, &written);
533 error("SBC: failed to encode block at frame %d (%zd)",
544 mp->payload.frame_count = frame_count;
549 static int audio_ipc_cmd(uint8_t service_id, uint8_t opcode, uint16_t len,
550 void *param, size_t *rsp_len, void *rsp, int *fd)
556 char cmsgbuf[CMSG_SPACE(sizeof(int))];
558 size_t s_len = sizeof(s);
560 pthread_mutex_lock(&sk_mutex);
563 error("audio: Invalid cmd socket passed to audio_ipc_cmd");
567 if (!rsp || !rsp_len) {
568 memset(&s, 0, s_len);
573 memset(&msg, 0, sizeof(msg));
574 memset(&cmd, 0, sizeof(cmd));
576 cmd.service_id = service_id;
580 iv[0].iov_base = &cmd;
581 iv[0].iov_len = sizeof(cmd);
583 iv[1].iov_base = param;
589 ret = sendmsg(audio_sk, &msg, 0);
591 error("audio: Sending command failed:%s", strerror(errno));
595 /* socket was shutdown */
597 error("audio: Command socket closed");
601 memset(&msg, 0, sizeof(msg));
602 memset(&cmd, 0, sizeof(cmd));
604 iv[0].iov_base = &cmd;
605 iv[0].iov_len = sizeof(cmd);
607 iv[1].iov_base = rsp;
608 iv[1].iov_len = *rsp_len;
614 memset(cmsgbuf, 0, sizeof(cmsgbuf));
615 msg.msg_control = cmsgbuf;
616 msg.msg_controllen = sizeof(cmsgbuf);
619 ret = recvmsg(audio_sk, &msg, 0);
621 error("audio: Receiving command response failed:%s",
626 if (ret < (ssize_t) sizeof(cmd)) {
627 error("audio: Too small response received(%zd bytes)", ret);
631 if (cmd.service_id != service_id) {
632 error("audio: Invalid service id (%u vs %u)", cmd.service_id,
637 if (ret != (ssize_t) (sizeof(cmd) + cmd.len)) {
638 error("audio: Malformed response received(%zd bytes)", ret);
642 if (cmd.opcode != opcode && cmd.opcode != AUDIO_OP_STATUS) {
643 error("audio: Invalid opcode received (%u vs %u)",
648 if (cmd.opcode == AUDIO_OP_STATUS) {
649 struct ipc_status *s = rsp;
651 if (sizeof(*s) != cmd.len) {
652 error("audio: Invalid status length");
656 if (s->code == AUDIO_STATUS_SUCCESS) {
657 error("audio: Invalid success status response");
661 pthread_mutex_unlock(&sk_mutex);
666 pthread_mutex_unlock(&sk_mutex);
668 /* Receive auxiliary data in msg */
670 struct cmsghdr *cmsg;
674 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
675 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
676 if (cmsg->cmsg_level == SOL_SOCKET
677 && cmsg->cmsg_type == SCM_RIGHTS) {
678 memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
690 return AUDIO_STATUS_SUCCESS;
693 /* Some serious issue happen on IPC - recover */
694 shutdown(audio_sk, SHUT_RDWR);
695 pthread_mutex_unlock(&sk_mutex);
697 return AUDIO_STATUS_FAILED;
700 static int ipc_open_cmd(const struct audio_codec *codec)
702 uint8_t buf[BLUEZ_AUDIO_MTU];
703 struct audio_cmd_open *cmd = (struct audio_cmd_open *) buf;
704 struct audio_rsp_open rsp;
705 size_t cmd_len = sizeof(buf) - sizeof(*cmd);
706 size_t rsp_len = sizeof(rsp);
711 memcpy(cmd->uuid, a2dp_src_uuid, sizeof(a2dp_src_uuid));
713 cmd->codec = codec->type;
714 cmd->presets = codec->get_presets(cmd->preset, &cmd_len);
716 cmd_len += sizeof(*cmd);
718 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN, cmd_len, cmd,
719 &rsp_len, &rsp, NULL);
721 if (result != AUDIO_STATUS_SUCCESS)
727 static int ipc_close_cmd(uint8_t endpoint_id)
729 struct audio_cmd_close cmd;
734 cmd.id = endpoint_id;
736 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE,
737 sizeof(cmd), &cmd, NULL, NULL, NULL);
742 static int ipc_open_stream_cmd(uint8_t endpoint_id, uint16_t *mtu, int *fd,
743 struct audio_preset **caps)
745 char buf[BLUEZ_AUDIO_MTU];
746 struct audio_cmd_open_stream cmd;
747 struct audio_rsp_open_stream *rsp =
748 (struct audio_rsp_open_stream *) &buf;
749 size_t rsp_len = sizeof(buf);
755 return AUDIO_STATUS_FAILED;
757 cmd.id = endpoint_id;
759 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN_STREAM,
760 sizeof(cmd), &cmd, &rsp_len, rsp, fd);
761 if (result == AUDIO_STATUS_SUCCESS) {
762 size_t buf_len = sizeof(struct audio_preset) +
765 *caps = malloc(buf_len);
766 memcpy(*caps, &rsp->preset, buf_len);
774 static int ipc_close_stream_cmd(uint8_t endpoint_id)
776 struct audio_cmd_close_stream cmd;
781 cmd.id = endpoint_id;
783 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE_STREAM,
784 sizeof(cmd), &cmd, NULL, NULL, NULL);
789 static int ipc_resume_stream_cmd(uint8_t endpoint_id)
791 struct audio_cmd_resume_stream cmd;
796 cmd.id = endpoint_id;
798 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_RESUME_STREAM,
799 sizeof(cmd), &cmd, NULL, NULL, NULL);
804 static int ipc_suspend_stream_cmd(uint8_t endpoint_id)
806 struct audio_cmd_suspend_stream cmd;
811 cmd.id = endpoint_id;
813 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_SUSPEND_STREAM,
814 sizeof(cmd), &cmd, NULL, NULL, NULL);
819 static int register_endpoints(void)
821 struct audio_endpoint *ep = &audio_endpoints[0];
824 for (i = 0; i < NUM_CODECS; i++, ep++) {
825 const struct audio_codec *codec = &audio_codecs[i];
827 ep->id = ipc_open_cmd(codec);
830 return AUDIO_STATUS_FAILED;
833 ep->codec_data = NULL;
837 return AUDIO_STATUS_SUCCESS;
840 static void unregister_endpoints(void)
844 for (i = 0; i < MAX_AUDIO_ENDPOINTS; i++) {
845 struct audio_endpoint *ep = &audio_endpoints[i];
848 ipc_close_cmd(ep->id);
849 memset(ep, 0, sizeof(*ep));
854 static bool open_endpoint(struct audio_endpoint *ep,
855 struct audio_input_config *cfg)
857 struct audio_preset *preset;
858 const struct audio_codec *codec;
860 uint16_t payload_len;
863 if (ipc_open_stream_cmd(ep->id, &mtu, &fd, &preset) !=
864 AUDIO_STATUS_SUCCESS)
869 payload_len = mtu - sizeof(*ep->mp);
874 codec->init(preset, payload_len, &ep->codec_data);
875 codec->get_config(ep->codec_data, cfg);
877 ep->mp = calloc(mtu, 1);
882 ep->mp->hdr.ssrc = htonl(1);
884 ep->mp_data_len = payload_len;
897 static void close_endpoint(struct audio_endpoint *ep)
899 ipc_close_stream_cmd(ep->id);
907 ep->codec->cleanup(ep->codec_data);
908 ep->codec_data = NULL;
911 static bool resume_endpoint(struct audio_endpoint *ep)
913 if (ipc_resume_stream_cmd(ep->id) != AUDIO_STATUS_SUCCESS)
921 static void downmix_to_mono(struct a2dp_stream_out *out, const uint8_t *buffer,
924 const int16_t *input = (const void *) buffer;
925 int16_t *output = (void *) out->downmix_buf;
928 for (i = 0; i < bytes / 2; i++) {
929 int16_t l = le16_to_cpu(get_unaligned(&input[i * 2]));
930 int16_t r = le16_to_cpu(get_unaligned(&input[i * 2 + 1]));
932 put_unaligned(cpu_to_le16((l + r) / 2), &output[i]);
936 static bool wait_for_endpoint(struct audio_endpoint *ep, bool *writable)
941 struct pollfd pollfd;
944 pollfd.events = POLLOUT;
947 ret = poll(&pollfd, 1, 500);
950 *writable = !!(pollfd.revents & POLLOUT);
954 if (errno != EINTR) {
956 error("poll failed (%d)", ret);
964 static bool write_to_endpoint(struct audio_endpoint *ep, size_t bytes)
966 struct media_packet *mp = (struct media_packet *) ep->mp;
970 ret = write(ep->fd, mp, sizeof(*mp) + bytes);
975 /* this should not happen so let's issue warning, but do not
976 * fail, we can try to write next packet
978 if (errno == EAGAIN) {
980 warn("write failed (%d)", ret);
984 if (errno != EINTR) {
986 error("write failed (%d)", ret);
994 static bool write_data(struct a2dp_stream_out *out, const void *buffer,
997 struct audio_endpoint *ep = out->ep;
998 struct media_packet *mp = (struct media_packet *) ep->mp;
999 size_t free_space = ep->mp_data_len;
1000 size_t consumed = 0;
1002 while (consumed < bytes) {
1007 struct timespec current;
1008 uint64_t audio_sent, audio_passed;
1009 bool do_write = false;
1011 /* prepare media packet in advance so we don't waste time after
1014 mp->hdr.sequence_number = htons(ep->seq++);
1015 mp->hdr.timestamp = htonl(ep->samples);
1016 read = ep->codec->encode_mediapacket(ep->codec_data,
1018 bytes - consumed, mp,
1019 free_space, &written);
1021 /* not much we can do here, let's just ignore remaining
1027 /* calculate where are we and where we should be */
1028 clock_gettime(CLOCK_MONOTONIC, ¤t);
1030 memcpy(&ep->start, ¤t, sizeof(ep->start));
1031 audio_sent = ep->samples * 1000000ll / out->cfg.rate;
1032 audio_passed = timespec_diff_us(¤t, &ep->start);
1034 /* if we're ahead of stream then wait for next write point */
1035 if (audio_sent > audio_passed) {
1036 struct timespec anchor;
1038 timespec_add(&ep->start, audio_sent, &anchor);
1041 ret = clock_nanosleep(CLOCK_MONOTONIC,
1042 TIMER_ABSTIME, &anchor,
1049 error("clock_nanosleep failed (%d)",
1056 /* wait some time for socket to be ready for write,
1057 * but we'll just skip writing data if timeout occurs
1059 if (!wait_for_endpoint(ep, &do_write))
1063 if (!write_to_endpoint(ep, written))
1066 /* AudioFlinger provides 16bit PCM, so sample size is 2 bytes
1067 * multiplied by number of channels. Number of channels is
1068 * simply number of bits set in channels mask.
1070 samples = read / (2 * popcount(out->cfg.channels));
1071 ep->samples += samples;
1078 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
1081 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1082 const void *in_buf = buffer;
1083 size_t in_len = bytes;
1085 /* just return in case we're closing */
1086 if (out->audio_state == AUDIO_A2DP_STATE_NONE)
1089 /* We can auto-start only from standby */
1090 if (out->audio_state == AUDIO_A2DP_STATE_STANDBY) {
1091 DBG("stream in standby, auto-start");
1093 if (!resume_endpoint(out->ep))
1096 out->audio_state = AUDIO_A2DP_STATE_STARTED;
1099 if (out->audio_state != AUDIO_A2DP_STATE_STARTED) {
1100 error("audio: stream not started");
1104 if (out->ep->fd < 0) {
1105 error("audio: no transport socket");
1109 /* currently Android audioflinger is not able to provide mono stream on
1110 * A2DP output so down mixing needs to be done in hal-audio plugin.
1113 * AudioFlinger::PlaybackThread::readOutputParameters()
1114 * frameworks/av/services/audioflinger/Threads.cpp:1631
1116 if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1117 if (!out->downmix_buf) {
1118 error("audio: downmix buffer not initialized");
1122 downmix_to_mono(out, buffer, bytes);
1124 in_buf = out->downmix_buf;
1128 if (!write_data(out, in_buf, in_len))
1134 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1136 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1140 return out->cfg.rate;
1143 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1145 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1149 if (rate != out->cfg.rate) {
1150 warn("audio: cannot set sample rate to %d", rate);
1157 static size_t out_get_buffer_size(const struct audio_stream *stream)
1161 /* We should return proper buffer size calculated by codec (so each
1162 * input buffer is encoded into single media packed) but this does not
1163 * work well with AudioFlinger and causes problems. For this reason we
1164 * use magic value here and out_write code takes care of splitting
1165 * input buffer into multiple media packets.
1167 return FIXED_BUFFER_SIZE;
1170 static uint32_t out_get_channels(const struct audio_stream *stream)
1174 /* AudioFlinger can only provide stereo stream, so we return it here and
1175 * later we'll downmix this to mono in case codec requires it
1178 return AUDIO_CHANNEL_OUT_STEREO;
1181 static audio_format_t out_get_format(const struct audio_stream *stream)
1183 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1187 return out->cfg.format;
1190 static int out_set_format(struct audio_stream *stream, audio_format_t format)
1196 static int out_standby(struct audio_stream *stream)
1198 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1202 if (out->audio_state == AUDIO_A2DP_STATE_STARTED) {
1203 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1205 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1211 static int out_dump(const struct audio_stream *stream, int fd)
1217 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1219 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1223 bool enter_suspend = false;
1224 bool exit_suspend = false;
1228 str = strdup(kvpairs);
1232 kvpair = strtok_r(str, ";", &saveptr);
1234 for (; kvpair && *kvpair; kvpair = strtok_r(NULL, ";", &saveptr)) {
1237 keyval = strchr(kvpair, '=');
1244 if (!strcmp(kvpair, "closing")) {
1245 if (!strcmp(keyval, "true"))
1246 out->audio_state = AUDIO_A2DP_STATE_NONE;
1247 } else if (!strcmp(kvpair, "A2dpSuspended")) {
1248 if (!strcmp(keyval, "true"))
1249 enter_suspend = true;
1251 exit_suspend = true;
1257 if (enter_suspend && out->audio_state == AUDIO_A2DP_STATE_STARTED) {
1258 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1260 out->audio_state = AUDIO_A2DP_STATE_SUSPENDED;
1263 if (exit_suspend && out->audio_state == AUDIO_A2DP_STATE_SUSPENDED)
1264 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1269 static char *out_get_parameters(const struct audio_stream *stream,
1276 static uint32_t out_get_latency(const struct audio_stream_out *stream)
1278 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1279 struct audio_endpoint *ep = out->ep;
1280 size_t pkt_duration;
1284 pkt_duration = ep->codec->get_mediapacket_duration(ep->codec_data);
1286 return FIXED_A2DP_PLAYBACK_LATENCY_MS + pkt_duration / 1000;
1289 static int out_set_volume(struct audio_stream_out *stream, float left,
1293 /* volume controlled in audioflinger mixer (digital) */
1297 static int out_get_render_position(const struct audio_stream_out *stream,
1298 uint32_t *dsp_frames)
1304 static int out_add_audio_effect(const struct audio_stream *stream,
1305 effect_handle_t effect)
1311 static int out_remove_audio_effect(const struct audio_stream *stream,
1312 effect_handle_t effect)
1318 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1324 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1330 static size_t in_get_buffer_size(const struct audio_stream *stream)
1336 static uint32_t in_get_channels(const struct audio_stream *stream)
1342 static audio_format_t in_get_format(const struct audio_stream *stream)
1348 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1354 static int in_standby(struct audio_stream *stream)
1360 static int in_dump(const struct audio_stream *stream, int fd)
1366 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1372 static char *in_get_parameters(const struct audio_stream *stream,
1379 static int in_set_gain(struct audio_stream_in *stream, float gain)
1385 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
1392 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1398 static int in_add_audio_effect(const struct audio_stream *stream,
1399 effect_handle_t effect)
1405 static int in_remove_audio_effect(const struct audio_stream *stream,
1406 effect_handle_t effect)
1412 static int audio_open_output_stream(struct audio_hw_device *dev,
1413 audio_io_handle_t handle,
1414 audio_devices_t devices,
1415 audio_output_flags_t flags,
1416 struct audio_config *config,
1417 struct audio_stream_out **stream_out)
1420 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1421 struct a2dp_stream_out *out;
1423 out = calloc(1, sizeof(struct a2dp_stream_out));
1429 out->stream.common.get_sample_rate = out_get_sample_rate;
1430 out->stream.common.set_sample_rate = out_set_sample_rate;
1431 out->stream.common.get_buffer_size = out_get_buffer_size;
1432 out->stream.common.get_channels = out_get_channels;
1433 out->stream.common.get_format = out_get_format;
1434 out->stream.common.set_format = out_set_format;
1435 out->stream.common.standby = out_standby;
1436 out->stream.common.dump = out_dump;
1437 out->stream.common.set_parameters = out_set_parameters;
1438 out->stream.common.get_parameters = out_get_parameters;
1439 out->stream.common.add_audio_effect = out_add_audio_effect;
1440 out->stream.common.remove_audio_effect = out_remove_audio_effect;
1441 out->stream.get_latency = out_get_latency;
1442 out->stream.set_volume = out_set_volume;
1443 out->stream.write = out_write;
1444 out->stream.get_render_position = out_get_render_position;
1446 /* TODO: for now we always use endpoint 0 */
1447 out->ep = &audio_endpoints[0];
1449 if (!open_endpoint(out->ep, &out->cfg))
1452 DBG("rate=%d channels=%d format=%d", out->cfg.rate,
1453 out->cfg.channels, out->cfg.format);
1455 if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1456 out->downmix_buf = malloc(FIXED_BUFFER_SIZE / 2);
1457 if (!out->downmix_buf)
1461 *stream_out = &out->stream;
1462 a2dp_dev->out = out;
1464 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1469 error("audio: cannot open output stream");
1475 static void audio_close_output_stream(struct audio_hw_device *dev,
1476 struct audio_stream_out *stream)
1478 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1479 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1483 close_endpoint(a2dp_dev->out->ep);
1485 free(out->downmix_buf);
1488 a2dp_dev->out = NULL;
1491 static int audio_set_parameters(struct audio_hw_device *dev,
1492 const char *kvpairs)
1494 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1495 struct a2dp_stream_out *out = a2dp_dev->out;
1502 return out->stream.common.set_parameters((struct audio_stream *) out,
1506 static char *audio_get_parameters(const struct audio_hw_device *dev,
1513 static int audio_init_check(const struct audio_hw_device *dev)
1519 static int audio_set_voice_volume(struct audio_hw_device *dev, float volume)
1525 static int audio_set_master_volume(struct audio_hw_device *dev, float volume)
1531 static int audio_set_mode(struct audio_hw_device *dev, int mode)
1537 static int audio_set_mic_mute(struct audio_hw_device *dev, bool state)
1543 static int audio_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1549 static size_t audio_get_input_buffer_size(const struct audio_hw_device *dev,
1550 const struct audio_config *config)
1556 static int audio_open_input_stream(struct audio_hw_device *dev,
1557 audio_io_handle_t handle,
1558 audio_devices_t devices,
1559 struct audio_config *config,
1560 struct audio_stream_in **stream_in)
1562 struct audio_stream_in *in;
1566 in = calloc(1, sizeof(struct audio_stream_in));
1570 in->common.get_sample_rate = in_get_sample_rate;
1571 in->common.set_sample_rate = in_set_sample_rate;
1572 in->common.get_buffer_size = in_get_buffer_size;
1573 in->common.get_channels = in_get_channels;
1574 in->common.get_format = in_get_format;
1575 in->common.set_format = in_set_format;
1576 in->common.standby = in_standby;
1577 in->common.dump = in_dump;
1578 in->common.set_parameters = in_set_parameters;
1579 in->common.get_parameters = in_get_parameters;
1580 in->common.add_audio_effect = in_add_audio_effect;
1581 in->common.remove_audio_effect = in_remove_audio_effect;
1582 in->set_gain = in_set_gain;
1584 in->get_input_frames_lost = in_get_input_frames_lost;
1591 static void audio_close_input_stream(struct audio_hw_device *dev,
1592 struct audio_stream_in *stream_in)
1598 static int audio_dump(const audio_hw_device_t *device, int fd)
1604 static int audio_close(hw_device_t *device)
1606 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *)device;
1610 unregister_endpoints();
1612 shutdown(listen_sk, SHUT_RDWR);
1613 shutdown(audio_sk, SHUT_RDWR);
1615 pthread_join(ipc_th, NULL);
1624 static void *ipc_handler(void *data)
1633 DBG("Waiting for connection ...");
1635 sk = accept(listen_sk, NULL, NULL);
1642 if (err != ECONNABORTED && err != EINVAL)
1643 error("audio: Failed to accept socket: %d (%s)",
1644 err, strerror(err));
1649 pthread_mutex_lock(&sk_mutex);
1651 pthread_mutex_unlock(&sk_mutex);
1653 DBG("Audio IPC: Connected");
1655 if (register_endpoints() != AUDIO_STATUS_SUCCESS) {
1656 error("audio: Failed to register endpoints");
1658 unregister_endpoints();
1660 pthread_mutex_lock(&sk_mutex);
1661 shutdown(audio_sk, SHUT_RDWR);
1664 pthread_mutex_unlock(&sk_mutex);
1669 memset(&pfd, 0, sizeof(pfd));
1671 pfd.events = POLLHUP | POLLERR | POLLNVAL;
1673 /* Check if socket is still alive. Empty while loop.*/
1674 while (poll(&pfd, 1, -1) < 0 && errno == EINTR);
1676 if (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)) {
1677 info("Audio HAL: Socket closed");
1679 pthread_mutex_lock(&sk_mutex);
1682 pthread_mutex_unlock(&sk_mutex);
1686 /* audio_sk is closed at this point, just cleanup endpoints states */
1687 memset(audio_endpoints, 0, sizeof(audio_endpoints));
1689 info("Closing Audio IPC thread");
1693 static int audio_ipc_init(void)
1695 struct sockaddr_un addr;
1701 sk = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
1704 error("audio: Failed to create socket: %d (%s)", -err,
1709 memset(&addr, 0, sizeof(addr));
1710 addr.sun_family = AF_UNIX;
1712 memcpy(addr.sun_path, BLUEZ_AUDIO_SK_PATH,
1713 sizeof(BLUEZ_AUDIO_SK_PATH));
1715 if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1717 error("audio: Failed to bind socket: %d (%s)", -err,
1722 if (listen(sk, 1) < 0) {
1724 error("audio: Failed to listen on the socket: %d (%s)", -err,
1731 err = pthread_create(&ipc_th, NULL, ipc_handler, NULL);
1735 error("audio: Failed to start Audio IPC thread: %d (%s)",
1736 -err, strerror(-err));
1747 static int audio_open(const hw_module_t *module, const char *name,
1748 hw_device_t **device)
1750 struct a2dp_audio_dev *a2dp_dev;
1755 if (strcmp(name, AUDIO_HARDWARE_INTERFACE)) {
1756 error("audio: interface %s not matching [%s]", name,
1757 AUDIO_HARDWARE_INTERFACE);
1761 err = audio_ipc_init();
1765 a2dp_dev = calloc(1, sizeof(struct a2dp_audio_dev));
1769 a2dp_dev->dev.common.tag = HARDWARE_DEVICE_TAG;
1770 a2dp_dev->dev.common.version = AUDIO_DEVICE_API_VERSION_CURRENT;
1771 a2dp_dev->dev.common.module = (struct hw_module_t *) module;
1772 a2dp_dev->dev.common.close = audio_close;
1774 a2dp_dev->dev.init_check = audio_init_check;
1775 a2dp_dev->dev.set_voice_volume = audio_set_voice_volume;
1776 a2dp_dev->dev.set_master_volume = audio_set_master_volume;
1777 a2dp_dev->dev.set_mode = audio_set_mode;
1778 a2dp_dev->dev.set_mic_mute = audio_set_mic_mute;
1779 a2dp_dev->dev.get_mic_mute = audio_get_mic_mute;
1780 a2dp_dev->dev.set_parameters = audio_set_parameters;
1781 a2dp_dev->dev.get_parameters = audio_get_parameters;
1782 a2dp_dev->dev.get_input_buffer_size = audio_get_input_buffer_size;
1783 a2dp_dev->dev.open_output_stream = audio_open_output_stream;
1784 a2dp_dev->dev.close_output_stream = audio_close_output_stream;
1785 a2dp_dev->dev.open_input_stream = audio_open_input_stream;
1786 a2dp_dev->dev.close_input_stream = audio_close_input_stream;
1787 a2dp_dev->dev.dump = audio_dump;
1789 /* Note that &a2dp_dev->dev.common is the same pointer as a2dp_dev.
1790 * This results from the structure of following structs:a2dp_audio_dev,
1791 * audio_hw_device. We will rely on this later in the code.*/
1792 *device = &a2dp_dev->dev.common;
1797 static struct hw_module_methods_t hal_module_methods = {
1801 struct audio_module HAL_MODULE_INFO_SYM = {
1803 .tag = HARDWARE_MODULE_TAG,
1806 .id = AUDIO_HARDWARE_MODULE_ID,
1807 .name = "A2DP Bluez HW HAL",
1808 .author = "Intel Corporation",
1809 .methods = &hal_module_methods,