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;
151 /* Bionic does not have clock_nanosleep() prototype in time.h even though
152 * it provides its implementation.
154 extern int clock_nanosleep(clockid_t clock_id, int flags,
155 const struct timespec *request,
156 struct timespec *remain);
159 static int sbc_get_presets(struct audio_preset *preset, size_t *len);
160 static int sbc_codec_init(struct audio_preset *preset, uint16_t mtu,
162 static int sbc_cleanup(void *codec_data);
163 static int sbc_get_config(void *codec_data, struct audio_input_config *config);
164 static size_t sbc_get_buffer_size(void *codec_data);
165 static size_t sbc_get_mediapacket_duration(void *codec_data);
166 static ssize_t sbc_encode_mediapacket(void *codec_data, const uint8_t *buffer,
167 size_t len, struct media_packet *mp,
168 size_t mp_data_len, size_t *written);
173 int (*get_presets) (struct audio_preset *preset, size_t *len);
175 int (*init) (struct audio_preset *preset, uint16_t mtu,
177 int (*cleanup) (void *codec_data);
178 int (*get_config) (void *codec_data,
179 struct audio_input_config *config);
180 size_t (*get_buffer_size) (void *codec_data);
181 size_t (*get_mediapacket_duration) (void *codec_data);
182 ssize_t (*encode_mediapacket) (void *codec_data, const uint8_t *buffer,
183 size_t len, struct media_packet *mp,
184 size_t mp_data_len, size_t *written);
187 static const struct audio_codec audio_codecs[] = {
189 .type = A2DP_CODEC_SBC,
191 .get_presets = sbc_get_presets,
193 .init = sbc_codec_init,
194 .cleanup = sbc_cleanup,
195 .get_config = sbc_get_config,
196 .get_buffer_size = sbc_get_buffer_size,
197 .get_mediapacket_duration = sbc_get_mediapacket_duration,
198 .encode_mediapacket = sbc_encode_mediapacket,
202 #define NUM_CODECS (sizeof(audio_codecs) / sizeof(audio_codecs[0]))
204 #define MAX_AUDIO_ENDPOINTS NUM_CODECS
206 struct audio_endpoint {
208 const struct audio_codec *codec;
212 struct media_packet *mp;
217 struct timespec start;
220 static struct audio_endpoint audio_endpoints[MAX_AUDIO_ENDPOINTS];
223 AUDIO_A2DP_STATE_NONE,
224 AUDIO_A2DP_STATE_STANDBY,
225 AUDIO_A2DP_STATE_SUSPENDED,
226 AUDIO_A2DP_STATE_STARTED
229 struct a2dp_stream_out {
230 struct audio_stream_out stream;
232 struct audio_endpoint *ep;
233 enum a2dp_state_t audio_state;
234 struct audio_input_config cfg;
236 uint8_t *downmix_buf;
239 struct a2dp_audio_dev {
240 struct audio_hw_device dev;
241 struct a2dp_stream_out *out;
244 static const a2dp_sbc_t sbc_presets[] = {
246 .frequency = SBC_SAMPLING_FREQ_44100 | SBC_SAMPLING_FREQ_48000,
247 .channel_mode = SBC_CHANNEL_MODE_MONO |
248 SBC_CHANNEL_MODE_DUAL_CHANNEL |
249 SBC_CHANNEL_MODE_STEREO |
250 SBC_CHANNEL_MODE_JOINT_STEREO,
251 .subbands = SBC_SUBBANDS_4 | SBC_SUBBANDS_8,
252 .allocation_method = SBC_ALLOCATION_SNR |
253 SBC_ALLOCATION_LOUDNESS,
254 .block_length = SBC_BLOCK_LENGTH_4 | SBC_BLOCK_LENGTH_8 |
255 SBC_BLOCK_LENGTH_12 | SBC_BLOCK_LENGTH_16,
256 .min_bitpool = MIN_BITPOOL,
257 .max_bitpool = MAX_BITPOOL
260 .frequency = SBC_SAMPLING_FREQ_44100,
261 .channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO,
262 .subbands = SBC_SUBBANDS_8,
263 .allocation_method = SBC_ALLOCATION_LOUDNESS,
264 .block_length = SBC_BLOCK_LENGTH_16,
265 .min_bitpool = MIN_BITPOOL,
266 .max_bitpool = MAX_BITPOOL
269 .frequency = SBC_SAMPLING_FREQ_48000,
270 .channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO,
271 .subbands = SBC_SUBBANDS_8,
272 .allocation_method = SBC_ALLOCATION_LOUDNESS,
273 .block_length = SBC_BLOCK_LENGTH_16,
274 .min_bitpool = MIN_BITPOOL,
275 .max_bitpool = MAX_BITPOOL
279 static int sbc_get_presets(struct audio_preset *preset, size_t *len)
284 uint8_t *ptr = (uint8_t *) preset;
285 size_t preset_size = sizeof(*preset) + sizeof(a2dp_sbc_t);
287 count = sizeof(sbc_presets) / sizeof(sbc_presets[0]);
289 for (i = 0; i < count; i++) {
290 preset = (struct audio_preset *) ptr;
292 if (new_len + preset_size > *len)
295 preset->len = sizeof(a2dp_sbc_t);
296 memcpy(preset->data, &sbc_presets[i], preset->len);
298 new_len += preset_size;
307 static int sbc_freq2int(uint8_t freq)
310 case SBC_SAMPLING_FREQ_16000:
312 case SBC_SAMPLING_FREQ_32000:
314 case SBC_SAMPLING_FREQ_44100:
316 case SBC_SAMPLING_FREQ_48000:
323 static const char *sbc_mode2str(uint8_t mode)
326 case SBC_CHANNEL_MODE_MONO:
328 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
329 return "DualChannel";
330 case SBC_CHANNEL_MODE_STEREO:
332 case SBC_CHANNEL_MODE_JOINT_STEREO:
333 return "JointStereo";
339 static int sbc_blocks2int(uint8_t blocks)
342 case SBC_BLOCK_LENGTH_4:
344 case SBC_BLOCK_LENGTH_8:
346 case SBC_BLOCK_LENGTH_12:
348 case SBC_BLOCK_LENGTH_16:
355 static int sbc_subbands2int(uint8_t subbands)
367 static const char *sbc_allocation2str(uint8_t allocation)
369 switch (allocation) {
370 case SBC_ALLOCATION_SNR:
372 case SBC_ALLOCATION_LOUDNESS:
379 static void sbc_init_encoder(struct sbc_data *sbc_data)
381 a2dp_sbc_t *in = &sbc_data->sbc;
382 sbc_t *out = &sbc_data->enc;
384 sbc_init_a2dp(out, 0L, in, sizeof(*in));
386 out->endian = SBC_LE;
387 out->bitpool = in->max_bitpool;
389 DBG("frequency=%d channel_mode=%s block_length=%d subbands=%d "
390 "allocation=%s bitpool=%d-%d",
391 sbc_freq2int(in->frequency),
392 sbc_mode2str(in->channel_mode),
393 sbc_blocks2int(in->block_length),
394 sbc_subbands2int(in->subbands),
395 sbc_allocation2str(in->allocation_method),
396 in->min_bitpool, in->max_bitpool);
399 static int sbc_codec_init(struct audio_preset *preset, uint16_t payload_len,
402 struct sbc_data *sbc_data;
404 size_t out_frame_len;
407 if (preset->len != sizeof(a2dp_sbc_t)) {
408 error("SBC: preset size mismatch");
409 return AUDIO_STATUS_FAILED;
412 sbc_data = calloc(sizeof(struct sbc_data), 1);
414 return AUDIO_STATUS_FAILED;
416 memcpy(&sbc_data->sbc, preset->data, preset->len);
418 sbc_init_encoder(sbc_data);
420 in_frame_len = sbc_get_codesize(&sbc_data->enc);
421 out_frame_len = sbc_get_frame_length(&sbc_data->enc);
422 num_frames = payload_len / out_frame_len;
424 sbc_data->in_frame_len = in_frame_len;
425 sbc_data->in_buf_size = num_frames * in_frame_len;
427 sbc_data->out_frame_len = out_frame_len;
429 sbc_data->frame_duration = sbc_get_frame_duration(&sbc_data->enc);
430 sbc_data->frames_per_packet = num_frames;
432 DBG("in_frame_len=%zu out_frame_len=%zu frames_per_packet=%zu",
433 in_frame_len, out_frame_len, num_frames);
435 *codec_data = sbc_data;
437 return AUDIO_STATUS_SUCCESS;
440 static int sbc_cleanup(void *codec_data)
442 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
444 sbc_finish(&sbc_data->enc);
447 return AUDIO_STATUS_SUCCESS;
450 static int sbc_get_config(void *codec_data, struct audio_input_config *config)
452 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
454 switch (sbc_data->sbc.frequency) {
455 case SBC_SAMPLING_FREQ_16000:
456 config->rate = 16000;
458 case SBC_SAMPLING_FREQ_32000:
459 config->rate = 32000;
461 case SBC_SAMPLING_FREQ_44100:
462 config->rate = 44100;
464 case SBC_SAMPLING_FREQ_48000:
465 config->rate = 48000;
468 return AUDIO_STATUS_FAILED;
470 config->channels = sbc_data->sbc.channel_mode == SBC_CHANNEL_MODE_MONO ?
471 AUDIO_CHANNEL_OUT_MONO :
472 AUDIO_CHANNEL_OUT_STEREO;
473 config->format = AUDIO_FORMAT_PCM_16_BIT;
475 return AUDIO_STATUS_SUCCESS;
478 static size_t sbc_get_buffer_size(void *codec_data)
480 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
482 return sbc_data->in_buf_size;
485 static size_t sbc_get_mediapacket_duration(void *codec_data)
487 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
489 return sbc_data->frame_duration * sbc_data->frames_per_packet;
492 static ssize_t sbc_encode_mediapacket(void *codec_data, const uint8_t *buffer,
493 size_t len, struct media_packet *mp,
494 size_t mp_data_len, size_t *written)
496 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
499 uint8_t frame_count = 0;
501 while (len - consumed >= sbc_data->in_frame_len &&
502 mp_data_len - encoded >= sbc_data->out_frame_len &&
503 frame_count < MAX_FRAMES_IN_PAYLOAD) {
507 read = sbc_encode(&sbc_data->enc, buffer + consumed,
508 sbc_data->in_frame_len, mp->data + encoded,
509 mp_data_len - encoded, &written);
512 error("SBC: failed to encode block at frame %d (%zd)",
523 mp->payload.frame_count = frame_count;
528 static int audio_ipc_cmd(uint8_t service_id, uint8_t opcode, uint16_t len,
529 void *param, size_t *rsp_len, void *rsp, int *fd)
535 char cmsgbuf[CMSG_SPACE(sizeof(int))];
537 size_t s_len = sizeof(s);
539 pthread_mutex_lock(&sk_mutex);
542 error("audio: Invalid cmd socket passed to audio_ipc_cmd");
546 if (!rsp || !rsp_len) {
547 memset(&s, 0, s_len);
552 memset(&msg, 0, sizeof(msg));
553 memset(&cmd, 0, sizeof(cmd));
555 cmd.service_id = service_id;
559 iv[0].iov_base = &cmd;
560 iv[0].iov_len = sizeof(cmd);
562 iv[1].iov_base = param;
568 ret = sendmsg(audio_sk, &msg, 0);
570 error("audio: Sending command failed:%s", strerror(errno));
574 /* socket was shutdown */
576 error("audio: Command socket closed");
580 memset(&msg, 0, sizeof(msg));
581 memset(&cmd, 0, sizeof(cmd));
583 iv[0].iov_base = &cmd;
584 iv[0].iov_len = sizeof(cmd);
586 iv[1].iov_base = rsp;
587 iv[1].iov_len = *rsp_len;
593 memset(cmsgbuf, 0, sizeof(cmsgbuf));
594 msg.msg_control = cmsgbuf;
595 msg.msg_controllen = sizeof(cmsgbuf);
598 ret = recvmsg(audio_sk, &msg, 0);
600 error("audio: Receiving command response failed:%s",
605 if (ret < (ssize_t) sizeof(cmd)) {
606 error("audio: Too small response received(%zd bytes)", ret);
610 if (cmd.service_id != service_id) {
611 error("audio: Invalid service id (%u vs %u)", cmd.service_id,
616 if (ret != (ssize_t) (sizeof(cmd) + cmd.len)) {
617 error("audio: Malformed response received(%zd bytes)", ret);
621 if (cmd.opcode != opcode && cmd.opcode != AUDIO_OP_STATUS) {
622 error("audio: Invalid opcode received (%u vs %u)",
627 if (cmd.opcode == AUDIO_OP_STATUS) {
628 struct ipc_status *s = rsp;
630 if (sizeof(*s) != cmd.len) {
631 error("audio: Invalid status length");
635 if (s->code == AUDIO_STATUS_SUCCESS) {
636 error("audio: Invalid success status response");
640 pthread_mutex_unlock(&sk_mutex);
645 pthread_mutex_unlock(&sk_mutex);
647 /* Receive auxiliary data in msg */
649 struct cmsghdr *cmsg;
653 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
654 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
655 if (cmsg->cmsg_level == SOL_SOCKET
656 && cmsg->cmsg_type == SCM_RIGHTS) {
657 memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
669 return AUDIO_STATUS_SUCCESS;
672 /* Some serious issue happen on IPC - recover */
673 shutdown(audio_sk, SHUT_RDWR);
674 pthread_mutex_unlock(&sk_mutex);
676 return AUDIO_STATUS_FAILED;
679 static int ipc_open_cmd(const struct audio_codec *codec)
681 uint8_t buf[BLUEZ_AUDIO_MTU];
682 struct audio_cmd_open *cmd = (struct audio_cmd_open *) buf;
683 struct audio_rsp_open rsp;
684 size_t cmd_len = sizeof(buf) - sizeof(*cmd);
685 size_t rsp_len = sizeof(rsp);
690 memcpy(cmd->uuid, a2dp_src_uuid, sizeof(a2dp_src_uuid));
692 cmd->codec = codec->type;
693 cmd->presets = codec->get_presets(cmd->preset, &cmd_len);
695 cmd_len += sizeof(*cmd);
697 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN, cmd_len, cmd,
698 &rsp_len, &rsp, NULL);
700 if (result != AUDIO_STATUS_SUCCESS)
706 static int ipc_close_cmd(uint8_t endpoint_id)
708 struct audio_cmd_close cmd;
713 cmd.id = endpoint_id;
715 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE,
716 sizeof(cmd), &cmd, NULL, NULL, NULL);
721 static int ipc_open_stream_cmd(uint8_t endpoint_id, uint16_t *mtu, int *fd,
722 struct audio_preset **caps)
724 char buf[BLUEZ_AUDIO_MTU];
725 struct audio_cmd_open_stream cmd;
726 struct audio_rsp_open_stream *rsp =
727 (struct audio_rsp_open_stream *) &buf;
728 size_t rsp_len = sizeof(buf);
734 return AUDIO_STATUS_FAILED;
736 cmd.id = endpoint_id;
738 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN_STREAM,
739 sizeof(cmd), &cmd, &rsp_len, rsp, fd);
740 if (result == AUDIO_STATUS_SUCCESS) {
741 size_t buf_len = sizeof(struct audio_preset) +
744 *caps = malloc(buf_len);
745 memcpy(*caps, &rsp->preset, buf_len);
753 static int ipc_close_stream_cmd(uint8_t endpoint_id)
755 struct audio_cmd_close_stream cmd;
760 cmd.id = endpoint_id;
762 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE_STREAM,
763 sizeof(cmd), &cmd, NULL, NULL, NULL);
768 static int ipc_resume_stream_cmd(uint8_t endpoint_id)
770 struct audio_cmd_resume_stream cmd;
775 cmd.id = endpoint_id;
777 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_RESUME_STREAM,
778 sizeof(cmd), &cmd, NULL, NULL, NULL);
783 static int ipc_suspend_stream_cmd(uint8_t endpoint_id)
785 struct audio_cmd_suspend_stream cmd;
790 cmd.id = endpoint_id;
792 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_SUSPEND_STREAM,
793 sizeof(cmd), &cmd, NULL, NULL, NULL);
798 static int register_endpoints(void)
800 struct audio_endpoint *ep = &audio_endpoints[0];
803 for (i = 0; i < NUM_CODECS; i++, ep++) {
804 const struct audio_codec *codec = &audio_codecs[i];
806 ep->id = ipc_open_cmd(codec);
809 return AUDIO_STATUS_FAILED;
812 ep->codec_data = NULL;
816 return AUDIO_STATUS_SUCCESS;
819 static void unregister_endpoints(void)
823 for (i = 0; i < MAX_AUDIO_ENDPOINTS; i++) {
824 struct audio_endpoint *ep = &audio_endpoints[i];
827 ipc_close_cmd(ep->id);
828 memset(ep, 0, sizeof(*ep));
833 static int set_blocking(int fd)
837 flags = fcntl(fd, F_GETFL, 0);
840 error("fcntl(F_GETFL): %s (%d)", strerror(-err), -err);
844 if (fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) < 0) {
846 error("fcntl(F_SETFL): %s (%d)", strerror(-err), -err);
853 static bool open_endpoint(struct audio_endpoint *ep,
854 struct audio_input_config *cfg)
856 struct audio_preset *preset;
857 const struct audio_codec *codec;
859 uint16_t payload_len;
862 if (ipc_open_stream_cmd(ep->id, &mtu, &fd, &preset) !=
863 AUDIO_STATUS_SUCCESS)
866 if (set_blocking(fd) < 0)
871 payload_len = mtu - sizeof(*ep->mp);
876 codec->init(preset, payload_len, &ep->codec_data);
877 codec->get_config(ep->codec_data, cfg);
879 ep->mp = calloc(mtu, 1);
884 ep->mp->hdr.ssrc = htonl(1);
886 ep->mp_data_len = payload_len;
899 static void close_endpoint(struct audio_endpoint *ep)
901 ipc_close_stream_cmd(ep->id);
909 ep->codec->cleanup(ep->codec_data);
910 ep->codec_data = NULL;
913 static bool resume_endpoint(struct audio_endpoint *ep)
915 if (ipc_resume_stream_cmd(ep->id) != AUDIO_STATUS_SUCCESS)
918 clock_gettime(CLOCK_MONOTONIC, &ep->start);
924 static void downmix_to_mono(struct a2dp_stream_out *out, const uint8_t *buffer,
927 const int16_t *input = (const void *) buffer;
928 int16_t *output = (void *) out->downmix_buf;
931 for (i = 0; i < bytes / 2; i++) {
932 int16_t l = le16_to_cpu(get_unaligned(&input[i * 2]));
933 int16_t r = le16_to_cpu(get_unaligned(&input[i * 2 + 1]));
935 put_unaligned(cpu_to_le16((l + r) / 2), &output[i]);
939 static bool write_data(struct a2dp_stream_out *out, const void *buffer,
942 struct audio_endpoint *ep = out->ep;
943 struct media_packet *mp = (struct media_packet *) ep->mp;
944 size_t free_space = ep->mp_data_len;
947 while (consumed < bytes) {
953 struct timespec anchor;
955 time_us = ep->samples * 1000000ll / out->cfg.rate;
957 timespec_add(&ep->start, time_us, &anchor);
960 ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
967 error("clock_nanosleep failed (%d)", ret);
972 read = ep->codec->encode_mediapacket(ep->codec_data,
974 bytes - consumed, mp,
975 free_space, &written);
977 /* This is non-fatal and we can just assume buffer was processed
978 * properly and wait for next one.
985 mp->hdr.sequence_number = htons(ep->seq++);
986 mp->hdr.timestamp = htonl(ep->samples);
988 /* AudioFlinger provides 16bit PCM, so sample size is 2 bytes
989 * multipled by number of channels. Number of channels is simply
990 * number of bits set in channels mask.
992 samples = read / (2 * popcount(out->cfg.channels));
993 ep->samples += samples;
996 ret = write(ep->fd, mp, sizeof(*mp) + written);
1009 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
1012 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1013 const void *in_buf = buffer;
1014 size_t in_len = bytes;
1016 /* just return in case we're closing */
1017 if (out->audio_state == AUDIO_A2DP_STATE_NONE)
1020 /* We can auto-start only from standby */
1021 if (out->audio_state == AUDIO_A2DP_STATE_STANDBY) {
1022 DBG("stream in standby, auto-start");
1024 if (!resume_endpoint(out->ep))
1027 out->audio_state = AUDIO_A2DP_STATE_STARTED;
1030 if (out->audio_state != AUDIO_A2DP_STATE_STARTED) {
1031 error("audio: stream not started");
1035 if (out->ep->fd < 0) {
1036 error("audio: no transport socket");
1040 /* currently Android audioflinger is not able to provide mono stream on
1041 * A2DP output so down mixing needs to be done in hal-audio plugin.
1044 * AudioFlinger::PlaybackThread::readOutputParameters()
1045 * frameworks/av/services/audioflinger/Threads.cpp:1631
1047 if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1048 if (!out->downmix_buf) {
1049 error("audio: downmix buffer not initialized");
1053 downmix_to_mono(out, buffer, bytes);
1055 in_buf = out->downmix_buf;
1059 if (!write_data(out, in_buf, in_len))
1065 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1067 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1071 return out->cfg.rate;
1074 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1076 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1080 if (rate != out->cfg.rate) {
1081 warn("audio: cannot set sample rate to %d", rate);
1088 static size_t out_get_buffer_size(const struct audio_stream *stream)
1092 /* We should return proper buffer size calculated by codec (so each
1093 * input buffer is encoded into single media packed) but this does not
1094 * work well with AudioFlinger and causes problems. For this reason we
1095 * use magic value here and out_write code takes care of splitting
1096 * input buffer into multiple media packets.
1098 return FIXED_BUFFER_SIZE;
1101 static uint32_t out_get_channels(const struct audio_stream *stream)
1105 /* AudioFlinger can only provide stereo stream, so we return it here and
1106 * later we'll downmix this to mono in case codec requires it
1109 return AUDIO_CHANNEL_OUT_STEREO;
1112 static audio_format_t out_get_format(const struct audio_stream *stream)
1114 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1118 return out->cfg.format;
1121 static int out_set_format(struct audio_stream *stream, audio_format_t format)
1127 static int out_standby(struct audio_stream *stream)
1129 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1133 if (out->audio_state == AUDIO_A2DP_STATE_STARTED) {
1134 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1136 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1142 static int out_dump(const struct audio_stream *stream, int fd)
1148 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1150 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1154 bool enter_suspend = false;
1155 bool exit_suspend = false;
1159 str = strdup(kvpairs);
1163 kvpair = strtok_r(str, ";", &saveptr);
1165 for (; kvpair && *kvpair; kvpair = strtok_r(NULL, ";", &saveptr)) {
1168 keyval = strchr(kvpair, '=');
1175 if (!strcmp(kvpair, "closing")) {
1176 if (!strcmp(keyval, "true"))
1177 out->audio_state = AUDIO_A2DP_STATE_NONE;
1178 } else if (!strcmp(kvpair, "A2dpSuspended")) {
1179 if (!strcmp(keyval, "true"))
1180 enter_suspend = true;
1182 exit_suspend = true;
1188 if (enter_suspend && out->audio_state == AUDIO_A2DP_STATE_STARTED) {
1189 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1191 out->audio_state = AUDIO_A2DP_STATE_SUSPENDED;
1194 if (exit_suspend && out->audio_state == AUDIO_A2DP_STATE_SUSPENDED)
1195 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1200 static char *out_get_parameters(const struct audio_stream *stream,
1207 static uint32_t out_get_latency(const struct audio_stream_out *stream)
1209 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1210 struct audio_endpoint *ep = out->ep;
1211 size_t pkt_duration;
1215 pkt_duration = ep->codec->get_mediapacket_duration(ep->codec_data);
1217 return FIXED_A2DP_PLAYBACK_LATENCY_MS + pkt_duration / 1000;
1220 static int out_set_volume(struct audio_stream_out *stream, float left,
1224 /* volume controlled in audioflinger mixer (digital) */
1228 static int out_get_render_position(const struct audio_stream_out *stream,
1229 uint32_t *dsp_frames)
1235 static int out_add_audio_effect(const struct audio_stream *stream,
1236 effect_handle_t effect)
1242 static int out_remove_audio_effect(const struct audio_stream *stream,
1243 effect_handle_t effect)
1249 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1255 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1261 static size_t in_get_buffer_size(const struct audio_stream *stream)
1267 static uint32_t in_get_channels(const struct audio_stream *stream)
1273 static audio_format_t in_get_format(const struct audio_stream *stream)
1279 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1285 static int in_standby(struct audio_stream *stream)
1291 static int in_dump(const struct audio_stream *stream, int fd)
1297 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1303 static char *in_get_parameters(const struct audio_stream *stream,
1310 static int in_set_gain(struct audio_stream_in *stream, float gain)
1316 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
1323 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1329 static int in_add_audio_effect(const struct audio_stream *stream,
1330 effect_handle_t effect)
1336 static int in_remove_audio_effect(const struct audio_stream *stream,
1337 effect_handle_t effect)
1343 static int audio_open_output_stream(struct audio_hw_device *dev,
1344 audio_io_handle_t handle,
1345 audio_devices_t devices,
1346 audio_output_flags_t flags,
1347 struct audio_config *config,
1348 struct audio_stream_out **stream_out)
1351 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1352 struct a2dp_stream_out *out;
1354 out = calloc(1, sizeof(struct a2dp_stream_out));
1360 out->stream.common.get_sample_rate = out_get_sample_rate;
1361 out->stream.common.set_sample_rate = out_set_sample_rate;
1362 out->stream.common.get_buffer_size = out_get_buffer_size;
1363 out->stream.common.get_channels = out_get_channels;
1364 out->stream.common.get_format = out_get_format;
1365 out->stream.common.set_format = out_set_format;
1366 out->stream.common.standby = out_standby;
1367 out->stream.common.dump = out_dump;
1368 out->stream.common.set_parameters = out_set_parameters;
1369 out->stream.common.get_parameters = out_get_parameters;
1370 out->stream.common.add_audio_effect = out_add_audio_effect;
1371 out->stream.common.remove_audio_effect = out_remove_audio_effect;
1372 out->stream.get_latency = out_get_latency;
1373 out->stream.set_volume = out_set_volume;
1374 out->stream.write = out_write;
1375 out->stream.get_render_position = out_get_render_position;
1377 /* TODO: for now we always use endpoint 0 */
1378 out->ep = &audio_endpoints[0];
1380 if (!open_endpoint(out->ep, &out->cfg))
1383 DBG("rate=%d channels=%d format=%d", out->cfg.rate,
1384 out->cfg.channels, out->cfg.format);
1386 if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1387 out->downmix_buf = malloc(FIXED_BUFFER_SIZE / 2);
1388 if (!out->downmix_buf)
1392 *stream_out = &out->stream;
1393 a2dp_dev->out = out;
1395 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1400 error("audio: cannot open output stream");
1406 static void audio_close_output_stream(struct audio_hw_device *dev,
1407 struct audio_stream_out *stream)
1409 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1410 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1414 close_endpoint(a2dp_dev->out->ep);
1416 free(out->downmix_buf);
1419 a2dp_dev->out = NULL;
1422 static int audio_set_parameters(struct audio_hw_device *dev,
1423 const char *kvpairs)
1425 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1426 struct a2dp_stream_out *out = a2dp_dev->out;
1433 return out->stream.common.set_parameters((struct audio_stream *) out,
1437 static char *audio_get_parameters(const struct audio_hw_device *dev,
1444 static int audio_init_check(const struct audio_hw_device *dev)
1450 static int audio_set_voice_volume(struct audio_hw_device *dev, float volume)
1456 static int audio_set_master_volume(struct audio_hw_device *dev, float volume)
1462 static int audio_set_mode(struct audio_hw_device *dev, int mode)
1468 static int audio_set_mic_mute(struct audio_hw_device *dev, bool state)
1474 static int audio_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1480 static size_t audio_get_input_buffer_size(const struct audio_hw_device *dev,
1481 const struct audio_config *config)
1487 static int audio_open_input_stream(struct audio_hw_device *dev,
1488 audio_io_handle_t handle,
1489 audio_devices_t devices,
1490 struct audio_config *config,
1491 struct audio_stream_in **stream_in)
1493 struct audio_stream_in *in;
1497 in = calloc(1, sizeof(struct audio_stream_in));
1501 in->common.get_sample_rate = in_get_sample_rate;
1502 in->common.set_sample_rate = in_set_sample_rate;
1503 in->common.get_buffer_size = in_get_buffer_size;
1504 in->common.get_channels = in_get_channels;
1505 in->common.get_format = in_get_format;
1506 in->common.set_format = in_set_format;
1507 in->common.standby = in_standby;
1508 in->common.dump = in_dump;
1509 in->common.set_parameters = in_set_parameters;
1510 in->common.get_parameters = in_get_parameters;
1511 in->common.add_audio_effect = in_add_audio_effect;
1512 in->common.remove_audio_effect = in_remove_audio_effect;
1513 in->set_gain = in_set_gain;
1515 in->get_input_frames_lost = in_get_input_frames_lost;
1522 static void audio_close_input_stream(struct audio_hw_device *dev,
1523 struct audio_stream_in *stream_in)
1529 static int audio_dump(const audio_hw_device_t *device, int fd)
1535 static int audio_close(hw_device_t *device)
1537 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *)device;
1541 unregister_endpoints();
1543 shutdown(listen_sk, SHUT_RDWR);
1544 shutdown(audio_sk, SHUT_RDWR);
1546 pthread_join(ipc_th, NULL);
1555 static void *ipc_handler(void *data)
1564 DBG("Waiting for connection ...");
1566 sk = accept(listen_sk, NULL, NULL);
1573 if (err != ECONNABORTED && err != EINVAL)
1574 error("audio: Failed to accept socket: %d (%s)",
1575 err, strerror(err));
1580 pthread_mutex_lock(&sk_mutex);
1582 pthread_mutex_unlock(&sk_mutex);
1584 DBG("Audio IPC: Connected");
1586 if (register_endpoints() != AUDIO_STATUS_SUCCESS) {
1587 error("audio: Failed to register endpoints");
1589 unregister_endpoints();
1591 pthread_mutex_lock(&sk_mutex);
1592 shutdown(audio_sk, SHUT_RDWR);
1595 pthread_mutex_unlock(&sk_mutex);
1600 memset(&pfd, 0, sizeof(pfd));
1602 pfd.events = POLLHUP | POLLERR | POLLNVAL;
1604 /* Check if socket is still alive. Empty while loop.*/
1605 while (poll(&pfd, 1, -1) < 0 && errno == EINTR);
1607 if (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)) {
1608 info("Audio HAL: Socket closed");
1610 pthread_mutex_lock(&sk_mutex);
1613 pthread_mutex_unlock(&sk_mutex);
1617 /* audio_sk is closed at this point, just cleanup endpoints states */
1618 memset(audio_endpoints, 0, sizeof(audio_endpoints));
1620 info("Closing Audio IPC thread");
1624 static int audio_ipc_init(void)
1626 struct sockaddr_un addr;
1632 sk = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
1635 error("audio: Failed to create socket: %d (%s)", -err,
1640 memset(&addr, 0, sizeof(addr));
1641 addr.sun_family = AF_UNIX;
1643 memcpy(addr.sun_path, BLUEZ_AUDIO_SK_PATH,
1644 sizeof(BLUEZ_AUDIO_SK_PATH));
1646 if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1648 error("audio: Failed to bind socket: %d (%s)", -err,
1653 if (listen(sk, 1) < 0) {
1655 error("audio: Failed to listen on the socket: %d (%s)", -err,
1662 err = pthread_create(&ipc_th, NULL, ipc_handler, NULL);
1666 error("audio: Failed to start Audio IPC thread: %d (%s)",
1667 -err, strerror(-err));
1678 static int audio_open(const hw_module_t *module, const char *name,
1679 hw_device_t **device)
1681 struct a2dp_audio_dev *a2dp_dev;
1686 if (strcmp(name, AUDIO_HARDWARE_INTERFACE)) {
1687 error("audio: interface %s not matching [%s]", name,
1688 AUDIO_HARDWARE_INTERFACE);
1692 err = audio_ipc_init();
1696 a2dp_dev = calloc(1, sizeof(struct a2dp_audio_dev));
1700 a2dp_dev->dev.common.tag = HARDWARE_DEVICE_TAG;
1701 a2dp_dev->dev.common.version = AUDIO_DEVICE_API_VERSION_CURRENT;
1702 a2dp_dev->dev.common.module = (struct hw_module_t *) module;
1703 a2dp_dev->dev.common.close = audio_close;
1705 a2dp_dev->dev.init_check = audio_init_check;
1706 a2dp_dev->dev.set_voice_volume = audio_set_voice_volume;
1707 a2dp_dev->dev.set_master_volume = audio_set_master_volume;
1708 a2dp_dev->dev.set_mode = audio_set_mode;
1709 a2dp_dev->dev.set_mic_mute = audio_set_mic_mute;
1710 a2dp_dev->dev.get_mic_mute = audio_get_mic_mute;
1711 a2dp_dev->dev.set_parameters = audio_set_parameters;
1712 a2dp_dev->dev.get_parameters = audio_get_parameters;
1713 a2dp_dev->dev.get_input_buffer_size = audio_get_input_buffer_size;
1714 a2dp_dev->dev.open_output_stream = audio_open_output_stream;
1715 a2dp_dev->dev.close_output_stream = audio_close_output_stream;
1716 a2dp_dev->dev.open_input_stream = audio_open_input_stream;
1717 a2dp_dev->dev.close_input_stream = audio_close_input_stream;
1718 a2dp_dev->dev.dump = audio_dump;
1720 /* Note that &a2dp_dev->dev.common is the same pointer as a2dp_dev.
1721 * This results from the structure of following structs:a2dp_audio_dev,
1722 * audio_hw_device. We will rely on this later in the code.*/
1723 *device = &a2dp_dev->dev.common;
1728 static struct hw_module_methods_t hal_module_methods = {
1732 struct audio_module HAL_MODULE_INFO_SYM = {
1734 .tag = HARDWARE_MODULE_TAG,
1737 .id = AUDIO_HARDWARE_MODULE_ID,
1738 .name = "A2DP Bluez HW HAL",
1739 .author = "Intel Corporation",
1740 .methods = &hal_module_methods,