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;
136 unsigned frame_duration;
137 unsigned frames_per_packet;
139 struct timespec start;
140 unsigned frames_sent;
146 static inline void timespec_diff(struct timespec *a, struct timespec *b,
147 struct timespec *res)
149 res->tv_sec = a->tv_sec - b->tv_sec;
150 res->tv_nsec = a->tv_nsec - b->tv_nsec;
152 if (res->tv_nsec < 0) {
154 res->tv_nsec += 1000000000; /* 1sec */
158 static int sbc_get_presets(struct audio_preset *preset, size_t *len);
159 static int sbc_codec_init(struct audio_preset *preset, uint16_t mtu,
161 static int sbc_cleanup(void *codec_data);
162 static int sbc_get_config(void *codec_data, struct audio_input_config *config);
163 static size_t sbc_get_buffer_size(void *codec_data);
164 static size_t sbc_get_mediapacket_duration(void *codec_data);
165 static void sbc_resume(void *codec_data);
166 static ssize_t sbc_write_data(void *codec_data, const void *buffer,
167 size_t bytes, int fd);
172 int (*get_presets) (struct audio_preset *preset, size_t *len);
174 int (*init) (struct audio_preset *preset, uint16_t mtu,
176 int (*cleanup) (void *codec_data);
177 int (*get_config) (void *codec_data,
178 struct audio_input_config *config);
179 size_t (*get_buffer_size) (void *codec_data);
180 size_t (*get_mediapacket_duration) (void *codec_data);
181 void (*resume) (void *codec_data);
182 ssize_t (*write_data) (void *codec_data, const void *buffer,
183 size_t bytes, int fd);
186 static const struct audio_codec audio_codecs[] = {
188 .type = A2DP_CODEC_SBC,
190 .get_presets = sbc_get_presets,
192 .init = sbc_codec_init,
193 .cleanup = sbc_cleanup,
194 .get_config = sbc_get_config,
195 .get_buffer_size = sbc_get_buffer_size,
196 .get_mediapacket_duration = sbc_get_mediapacket_duration,
197 .resume = sbc_resume,
198 .write_data = sbc_write_data,
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;
213 static struct audio_endpoint audio_endpoints[MAX_AUDIO_ENDPOINTS];
216 AUDIO_A2DP_STATE_NONE,
217 AUDIO_A2DP_STATE_STANDBY,
218 AUDIO_A2DP_STATE_SUSPENDED,
219 AUDIO_A2DP_STATE_STARTED
222 struct a2dp_stream_out {
223 struct audio_stream_out stream;
225 struct audio_endpoint *ep;
226 enum a2dp_state_t audio_state;
227 struct audio_input_config cfg;
229 uint8_t *downmix_buf;
232 struct a2dp_audio_dev {
233 struct audio_hw_device dev;
234 struct a2dp_stream_out *out;
237 static const a2dp_sbc_t sbc_presets[] = {
239 .frequency = SBC_SAMPLING_FREQ_44100 | SBC_SAMPLING_FREQ_48000,
240 .channel_mode = SBC_CHANNEL_MODE_MONO |
241 SBC_CHANNEL_MODE_DUAL_CHANNEL |
242 SBC_CHANNEL_MODE_STEREO |
243 SBC_CHANNEL_MODE_JOINT_STEREO,
244 .subbands = SBC_SUBBANDS_4 | SBC_SUBBANDS_8,
245 .allocation_method = SBC_ALLOCATION_SNR |
246 SBC_ALLOCATION_LOUDNESS,
247 .block_length = SBC_BLOCK_LENGTH_4 | SBC_BLOCK_LENGTH_8 |
248 SBC_BLOCK_LENGTH_12 | SBC_BLOCK_LENGTH_16,
249 .min_bitpool = MIN_BITPOOL,
250 .max_bitpool = MAX_BITPOOL
253 .frequency = SBC_SAMPLING_FREQ_44100,
254 .channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO,
255 .subbands = SBC_SUBBANDS_8,
256 .allocation_method = SBC_ALLOCATION_LOUDNESS,
257 .block_length = SBC_BLOCK_LENGTH_16,
258 .min_bitpool = MIN_BITPOOL,
259 .max_bitpool = MAX_BITPOOL
262 .frequency = SBC_SAMPLING_FREQ_48000,
263 .channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO,
264 .subbands = SBC_SUBBANDS_8,
265 .allocation_method = SBC_ALLOCATION_LOUDNESS,
266 .block_length = SBC_BLOCK_LENGTH_16,
267 .min_bitpool = MIN_BITPOOL,
268 .max_bitpool = MAX_BITPOOL
272 static int sbc_get_presets(struct audio_preset *preset, size_t *len)
277 uint8_t *ptr = (uint8_t *) preset;
278 size_t preset_size = sizeof(*preset) + sizeof(a2dp_sbc_t);
280 count = sizeof(sbc_presets) / sizeof(sbc_presets[0]);
282 for (i = 0; i < count; i++) {
283 preset = (struct audio_preset *) ptr;
285 if (new_len + preset_size > *len)
288 preset->len = sizeof(a2dp_sbc_t);
289 memcpy(preset->data, &sbc_presets[i], preset->len);
291 new_len += preset_size;
300 static int sbc_freq2int(uint8_t freq)
303 case SBC_SAMPLING_FREQ_16000:
305 case SBC_SAMPLING_FREQ_32000:
307 case SBC_SAMPLING_FREQ_44100:
309 case SBC_SAMPLING_FREQ_48000:
316 static const char *sbc_mode2str(uint8_t mode)
319 case SBC_CHANNEL_MODE_MONO:
321 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
322 return "DualChannel";
323 case SBC_CHANNEL_MODE_STEREO:
325 case SBC_CHANNEL_MODE_JOINT_STEREO:
326 return "JointStereo";
332 static int sbc_blocks2int(uint8_t blocks)
335 case SBC_BLOCK_LENGTH_4:
337 case SBC_BLOCK_LENGTH_8:
339 case SBC_BLOCK_LENGTH_12:
341 case SBC_BLOCK_LENGTH_16:
348 static int sbc_subbands2int(uint8_t subbands)
360 static const char *sbc_allocation2str(uint8_t allocation)
362 switch (allocation) {
363 case SBC_ALLOCATION_SNR:
365 case SBC_ALLOCATION_LOUDNESS:
372 static void sbc_init_encoder(struct sbc_data *sbc_data)
374 a2dp_sbc_t *in = &sbc_data->sbc;
375 sbc_t *out = &sbc_data->enc;
377 sbc_init_a2dp(out, 0L, in, sizeof(*in));
379 out->endian = SBC_LE;
380 out->bitpool = in->max_bitpool;
382 DBG("frequency=%d channel_mode=%s block_length=%d subbands=%d "
383 "allocation=%s bitpool=%d-%d",
384 sbc_freq2int(in->frequency),
385 sbc_mode2str(in->channel_mode),
386 sbc_blocks2int(in->block_length),
387 sbc_subbands2int(in->subbands),
388 sbc_allocation2str(in->allocation_method),
389 in->min_bitpool, in->max_bitpool);
392 static int sbc_codec_init(struct audio_preset *preset, uint16_t mtu,
395 struct sbc_data *sbc_data;
396 size_t hdr_len = sizeof(struct media_packet);
398 size_t out_frame_len;
401 if (preset->len != sizeof(a2dp_sbc_t)) {
402 error("SBC: preset size mismatch");
403 return AUDIO_STATUS_FAILED;
406 sbc_data = calloc(sizeof(struct sbc_data), 1);
408 return AUDIO_STATUS_FAILED;
410 memcpy(&sbc_data->sbc, preset->data, preset->len);
412 sbc_init_encoder(sbc_data);
414 in_frame_len = sbc_get_codesize(&sbc_data->enc);
415 out_frame_len = sbc_get_frame_length(&sbc_data->enc);
416 num_frames = (mtu - hdr_len) / out_frame_len;
418 sbc_data->in_frame_len = in_frame_len;
419 sbc_data->in_buf_size = num_frames * in_frame_len;
421 sbc_data->out_frame_len = out_frame_len;
422 sbc_data->out_buf_size = hdr_len + num_frames * out_frame_len;
423 sbc_data->out_buf = calloc(1, sbc_data->out_buf_size);
425 sbc_data->frame_duration = sbc_get_frame_duration(&sbc_data->enc);
426 sbc_data->frames_per_packet = num_frames;
428 DBG("mtu=%u in_frame_len=%zu out_frame_len=%zu frames_per_packet=%zu",
429 mtu, in_frame_len, out_frame_len, num_frames);
431 *codec_data = sbc_data;
433 return AUDIO_STATUS_SUCCESS;
436 static int sbc_cleanup(void *codec_data)
438 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
440 sbc_finish(&sbc_data->enc);
441 free(sbc_data->out_buf);
444 return AUDIO_STATUS_SUCCESS;
447 static int sbc_get_config(void *codec_data, struct audio_input_config *config)
449 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
451 switch (sbc_data->sbc.frequency) {
452 case SBC_SAMPLING_FREQ_16000:
453 config->rate = 16000;
455 case SBC_SAMPLING_FREQ_32000:
456 config->rate = 32000;
458 case SBC_SAMPLING_FREQ_44100:
459 config->rate = 44100;
461 case SBC_SAMPLING_FREQ_48000:
462 config->rate = 48000;
465 return AUDIO_STATUS_FAILED;
467 config->channels = sbc_data->sbc.channel_mode == SBC_CHANNEL_MODE_MONO ?
468 AUDIO_CHANNEL_OUT_MONO :
469 AUDIO_CHANNEL_OUT_STEREO;
470 config->format = AUDIO_FORMAT_PCM_16_BIT;
472 return AUDIO_STATUS_SUCCESS;
475 static size_t sbc_get_buffer_size(void *codec_data)
477 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
479 return sbc_data->in_buf_size;
482 static size_t sbc_get_mediapacket_duration(void *codec_data)
484 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
486 return sbc_data->frame_duration * sbc_data->frames_per_packet;
489 static void sbc_resume(void *codec_data)
491 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
495 clock_gettime(CLOCK_MONOTONIC, &sbc_data->start);
497 sbc_data->frames_sent = 0;
498 sbc_data->timestamp = 0;
501 static int write_media_packet(int fd, struct sbc_data *sbc_data,
502 struct media_packet *mp, size_t data_len)
505 struct timespec diff;
506 unsigned expected_frames;
510 ret = write(fd, mp, sizeof(*mp) + data_len);
518 sbc_data->frames_sent += mp->payload.frame_count;
520 clock_gettime(CLOCK_MONOTONIC, &cur);
521 timespec_diff(&cur, &sbc_data->start, &diff);
522 expected_frames = (diff.tv_sec * 1000000 + diff.tv_nsec / 1000) /
523 sbc_data->frame_duration;
525 /* AudioFlinger does not seem to provide any *working*
526 * API to provide data in some interval and will just
527 * send another buffer as soon as we process current
528 * one. To prevent overflowing L2CAP socket, we need to
529 * introduce some artificial delay here base on how many
530 * audio frames were sent so far, i.e. if we're not
531 * lagging behind audio stream, we can sleep for
532 * duration of single media packet.
534 if (sbc_data->frames_sent >= expected_frames)
535 usleep(sbc_data->frame_duration *
536 mp->payload.frame_count);
541 static ssize_t sbc_encode_mediapacket(void *codec_data, const uint8_t *buffer,
542 size_t len, struct media_packet *mp,
543 size_t mp_data_len, size_t *written)
545 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
548 uint8_t frame_count = 0;
550 while (len - consumed >= sbc_data->in_frame_len &&
551 mp_data_len - encoded >= sbc_data->out_frame_len &&
552 frame_count < MAX_FRAMES_IN_PAYLOAD) {
556 read = sbc_encode(&sbc_data->enc, buffer + consumed,
557 sbc_data->in_frame_len, mp->data + encoded,
558 mp_data_len - encoded, &written);
561 error("SBC: failed to encode block at frame %d (%zd)",
572 mp->payload.frame_count = frame_count;
577 static ssize_t sbc_write_data(void *codec_data, const void *buffer,
578 size_t bytes, int fd)
580 struct sbc_data *sbc_data = (struct sbc_data *) codec_data;
582 struct media_packet *mp = (struct media_packet *) sbc_data->out_buf;
583 size_t free_space = sbc_data->out_buf_size - sizeof(*mp);
587 mp->hdr.ssrc = htonl(1);
589 while (consumed < bytes) {
594 read = sbc_encode_mediapacket(codec_data, buffer + consumed,
595 bytes - consumed, mp,
600 error("sbc_encode_mediapacket failed (%zd)", read);
606 mp->hdr.sequence_number = htons(sbc_data->seq++);
607 mp->hdr.timestamp = htonl(sbc_data->timestamp);
609 /* AudioFlinger provides PCM 16bit stereo only, thus sample size
612 sbc_data->timestamp += (read / 4);
614 ret = write_media_packet(fd, sbc_data, mp, written);
620 /* we always assume that all data was processed and sent */
624 static int audio_ipc_cmd(uint8_t service_id, uint8_t opcode, uint16_t len,
625 void *param, size_t *rsp_len, void *rsp, int *fd)
631 char cmsgbuf[CMSG_SPACE(sizeof(int))];
633 size_t s_len = sizeof(s);
635 pthread_mutex_lock(&sk_mutex);
638 error("audio: Invalid cmd socket passed to audio_ipc_cmd");
642 if (!rsp || !rsp_len) {
643 memset(&s, 0, s_len);
648 memset(&msg, 0, sizeof(msg));
649 memset(&cmd, 0, sizeof(cmd));
651 cmd.service_id = service_id;
655 iv[0].iov_base = &cmd;
656 iv[0].iov_len = sizeof(cmd);
658 iv[1].iov_base = param;
664 ret = sendmsg(audio_sk, &msg, 0);
666 error("audio: Sending command failed:%s", strerror(errno));
670 /* socket was shutdown */
672 error("audio: Command socket closed");
676 memset(&msg, 0, sizeof(msg));
677 memset(&cmd, 0, sizeof(cmd));
679 iv[0].iov_base = &cmd;
680 iv[0].iov_len = sizeof(cmd);
682 iv[1].iov_base = rsp;
683 iv[1].iov_len = *rsp_len;
689 memset(cmsgbuf, 0, sizeof(cmsgbuf));
690 msg.msg_control = cmsgbuf;
691 msg.msg_controllen = sizeof(cmsgbuf);
694 ret = recvmsg(audio_sk, &msg, 0);
696 error("audio: Receiving command response failed:%s",
701 if (ret < (ssize_t) sizeof(cmd)) {
702 error("audio: Too small response received(%zd bytes)", ret);
706 if (cmd.service_id != service_id) {
707 error("audio: Invalid service id (%u vs %u)", cmd.service_id,
712 if (ret != (ssize_t) (sizeof(cmd) + cmd.len)) {
713 error("audio: Malformed response received(%zd bytes)", ret);
717 if (cmd.opcode != opcode && cmd.opcode != AUDIO_OP_STATUS) {
718 error("audio: Invalid opcode received (%u vs %u)",
723 if (cmd.opcode == AUDIO_OP_STATUS) {
724 struct ipc_status *s = rsp;
726 if (sizeof(*s) != cmd.len) {
727 error("audio: Invalid status length");
731 if (s->code == AUDIO_STATUS_SUCCESS) {
732 error("audio: Invalid success status response");
736 pthread_mutex_unlock(&sk_mutex);
741 pthread_mutex_unlock(&sk_mutex);
743 /* Receive auxiliary data in msg */
745 struct cmsghdr *cmsg;
749 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
750 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
751 if (cmsg->cmsg_level == SOL_SOCKET
752 && cmsg->cmsg_type == SCM_RIGHTS) {
753 memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
765 return AUDIO_STATUS_SUCCESS;
768 /* Some serious issue happen on IPC - recover */
769 shutdown(audio_sk, SHUT_RDWR);
770 pthread_mutex_unlock(&sk_mutex);
772 return AUDIO_STATUS_FAILED;
775 static int ipc_open_cmd(const struct audio_codec *codec)
777 uint8_t buf[BLUEZ_AUDIO_MTU];
778 struct audio_cmd_open *cmd = (struct audio_cmd_open *) buf;
779 struct audio_rsp_open rsp;
780 size_t cmd_len = sizeof(buf) - sizeof(*cmd);
781 size_t rsp_len = sizeof(rsp);
786 memcpy(cmd->uuid, a2dp_src_uuid, sizeof(a2dp_src_uuid));
788 cmd->codec = codec->type;
789 cmd->presets = codec->get_presets(cmd->preset, &cmd_len);
791 cmd_len += sizeof(*cmd);
793 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN, cmd_len, cmd,
794 &rsp_len, &rsp, NULL);
796 if (result != AUDIO_STATUS_SUCCESS)
802 static int ipc_close_cmd(uint8_t endpoint_id)
804 struct audio_cmd_close cmd;
809 cmd.id = endpoint_id;
811 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE,
812 sizeof(cmd), &cmd, NULL, NULL, NULL);
817 static int ipc_open_stream_cmd(uint8_t endpoint_id, uint16_t *mtu, int *fd,
818 struct audio_preset **caps)
820 char buf[BLUEZ_AUDIO_MTU];
821 struct audio_cmd_open_stream cmd;
822 struct audio_rsp_open_stream *rsp =
823 (struct audio_rsp_open_stream *) &buf;
824 size_t rsp_len = sizeof(buf);
830 return AUDIO_STATUS_FAILED;
832 cmd.id = endpoint_id;
834 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_OPEN_STREAM,
835 sizeof(cmd), &cmd, &rsp_len, rsp, fd);
836 if (result == AUDIO_STATUS_SUCCESS) {
837 size_t buf_len = sizeof(struct audio_preset) +
840 *caps = malloc(buf_len);
841 memcpy(*caps, &rsp->preset, buf_len);
849 static int ipc_close_stream_cmd(uint8_t endpoint_id)
851 struct audio_cmd_close_stream cmd;
856 cmd.id = endpoint_id;
858 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_CLOSE_STREAM,
859 sizeof(cmd), &cmd, NULL, NULL, NULL);
864 static int ipc_resume_stream_cmd(uint8_t endpoint_id)
866 struct audio_cmd_resume_stream cmd;
871 cmd.id = endpoint_id;
873 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_RESUME_STREAM,
874 sizeof(cmd), &cmd, NULL, NULL, NULL);
879 static int ipc_suspend_stream_cmd(uint8_t endpoint_id)
881 struct audio_cmd_suspend_stream cmd;
886 cmd.id = endpoint_id;
888 result = audio_ipc_cmd(AUDIO_SERVICE_ID, AUDIO_OP_SUSPEND_STREAM,
889 sizeof(cmd), &cmd, NULL, NULL, NULL);
894 static int register_endpoints(void)
896 struct audio_endpoint *ep = &audio_endpoints[0];
899 for (i = 0; i < NUM_CODECS; i++, ep++) {
900 const struct audio_codec *codec = &audio_codecs[i];
902 ep->id = ipc_open_cmd(codec);
905 return AUDIO_STATUS_FAILED;
908 ep->codec_data = NULL;
912 return AUDIO_STATUS_SUCCESS;
915 static void unregister_endpoints(void)
919 for (i = 0; i < MAX_AUDIO_ENDPOINTS; i++) {
920 struct audio_endpoint *ep = &audio_endpoints[i];
923 ipc_close_cmd(ep->id);
924 memset(ep, 0, sizeof(*ep));
929 static int set_blocking(int fd)
933 flags = fcntl(fd, F_GETFL, 0);
936 error("fcntl(F_GETFL): %s (%d)", strerror(-err), -err);
940 if (fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) < 0) {
942 error("fcntl(F_SETFL): %s (%d)", strerror(-err), -err);
949 static bool open_endpoint(struct audio_endpoint *ep,
950 struct audio_input_config *cfg)
952 struct audio_preset *preset;
953 const struct audio_codec *codec;
957 if (ipc_open_stream_cmd(ep->id, &mtu, &fd, &preset) !=
958 AUDIO_STATUS_SUCCESS)
961 if (set_blocking(fd) < 0)
967 codec->init(preset, mtu, &ep->codec_data);
968 codec->get_config(ep->codec_data, cfg);
981 static void close_endpoint(struct audio_endpoint *ep)
983 ipc_close_stream_cmd(ep->id);
989 ep->codec->cleanup(ep->codec_data);
990 ep->codec_data = NULL;
993 static void downmix_to_mono(struct a2dp_stream_out *out, const uint8_t *buffer,
996 const int16_t *input = (const void *) buffer;
997 int16_t *output = (void *) out->downmix_buf;
1000 for (i = 0; i < bytes / 2; i++) {
1001 int16_t l = le16_to_cpu(get_unaligned(&input[i * 2]));
1002 int16_t r = le16_to_cpu(get_unaligned(&input[i * 2 + 1]));
1004 put_unaligned(cpu_to_le16((l + r) / 2), &output[i]);
1008 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
1011 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1013 /* just return in case we're closing */
1014 if (out->audio_state == AUDIO_A2DP_STATE_NONE)
1017 /* We can auto-start only from standby */
1018 if (out->audio_state == AUDIO_A2DP_STATE_STANDBY) {
1019 DBG("stream in standby, auto-start");
1021 if (ipc_resume_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1024 out->ep->codec->resume(out->ep->codec_data);
1026 out->audio_state = AUDIO_A2DP_STATE_STARTED;
1029 if (out->audio_state != AUDIO_A2DP_STATE_STARTED) {
1030 error("audio: stream not started");
1034 if (out->ep->fd < 0) {
1035 error("audio: no transport socket");
1039 /* currently Android audioflinger is not able to provide mono stream on
1040 * A2DP output so down mixing needs to be done in hal-audio plugin.
1043 * AudioFlinger::PlaybackThread::readOutputParameters()
1044 * frameworks/av/services/audioflinger/Threads.cpp:1631
1046 if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1047 if (!out->downmix_buf) {
1048 error("audio: downmix buffer not initialized");
1052 downmix_to_mono(out, buffer, bytes);
1054 return out->ep->codec->write_data(out->ep->codec_data,
1060 return out->ep->codec->write_data(out->ep->codec_data, buffer,
1061 bytes, out->ep->fd);
1064 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1066 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1070 return out->cfg.rate;
1073 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1075 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1079 if (rate != out->cfg.rate) {
1080 warn("audio: cannot set sample rate to %d", rate);
1087 static size_t out_get_buffer_size(const struct audio_stream *stream)
1091 /* We should return proper buffer size calculated by codec (so each
1092 * input buffer is encoded into single media packed) but this does not
1093 * work well with AudioFlinger and causes problems. For this reason we
1094 * use magic value here and out_write code takes care of splitting
1095 * input buffer into multiple media packets.
1097 return FIXED_BUFFER_SIZE;
1100 static uint32_t out_get_channels(const struct audio_stream *stream)
1104 /* AudioFlinger can only provide stereo stream, so we return it here and
1105 * later we'll downmix this to mono in case codec requires it
1108 return AUDIO_CHANNEL_OUT_STEREO;
1111 static audio_format_t out_get_format(const struct audio_stream *stream)
1113 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1117 return out->cfg.format;
1120 static int out_set_format(struct audio_stream *stream, audio_format_t format)
1126 static int out_standby(struct audio_stream *stream)
1128 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1132 if (out->audio_state == AUDIO_A2DP_STATE_STARTED) {
1133 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1135 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1141 static int out_dump(const struct audio_stream *stream, int fd)
1147 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1149 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1153 bool enter_suspend = false;
1154 bool exit_suspend = false;
1158 str = strdup(kvpairs);
1159 kvpair = strtok_r(str, ";", &saveptr);
1161 for (; kvpair && *kvpair; kvpair = strtok_r(NULL, ";", &saveptr)) {
1164 keyval = strchr(kvpair, '=');
1171 if (!strcmp(kvpair, "closing")) {
1172 if (!strcmp(keyval, "true"))
1173 out->audio_state = AUDIO_A2DP_STATE_NONE;
1174 } else if (!strcmp(kvpair, "A2dpSuspended")) {
1175 if (!strcmp(keyval, "true"))
1176 enter_suspend = true;
1178 exit_suspend = true;
1184 if (enter_suspend && out->audio_state == AUDIO_A2DP_STATE_STARTED) {
1185 if (ipc_suspend_stream_cmd(out->ep->id) != AUDIO_STATUS_SUCCESS)
1187 out->audio_state = AUDIO_A2DP_STATE_SUSPENDED;
1190 if (exit_suspend && out->audio_state == AUDIO_A2DP_STATE_SUSPENDED)
1191 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1196 static char *out_get_parameters(const struct audio_stream *stream,
1203 static uint32_t out_get_latency(const struct audio_stream_out *stream)
1205 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1206 struct audio_endpoint *ep = out->ep;
1207 size_t pkt_duration;
1211 pkt_duration = ep->codec->get_mediapacket_duration(ep->codec_data);
1213 return FIXED_A2DP_PLAYBACK_LATENCY_MS + pkt_duration / 1000;
1216 static int out_set_volume(struct audio_stream_out *stream, float left,
1220 /* volume controlled in audioflinger mixer (digital) */
1224 static int out_get_render_position(const struct audio_stream_out *stream,
1225 uint32_t *dsp_frames)
1231 static int out_add_audio_effect(const struct audio_stream *stream,
1232 effect_handle_t effect)
1238 static int out_remove_audio_effect(const struct audio_stream *stream,
1239 effect_handle_t effect)
1245 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1251 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1257 static size_t in_get_buffer_size(const struct audio_stream *stream)
1263 static uint32_t in_get_channels(const struct audio_stream *stream)
1269 static audio_format_t in_get_format(const struct audio_stream *stream)
1275 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1281 static int in_standby(struct audio_stream *stream)
1287 static int in_dump(const struct audio_stream *stream, int fd)
1293 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1299 static char *in_get_parameters(const struct audio_stream *stream,
1306 static int in_set_gain(struct audio_stream_in *stream, float gain)
1312 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
1319 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1325 static int in_add_audio_effect(const struct audio_stream *stream,
1326 effect_handle_t effect)
1332 static int in_remove_audio_effect(const struct audio_stream *stream,
1333 effect_handle_t effect)
1339 static int audio_open_output_stream(struct audio_hw_device *dev,
1340 audio_io_handle_t handle,
1341 audio_devices_t devices,
1342 audio_output_flags_t flags,
1343 struct audio_config *config,
1344 struct audio_stream_out **stream_out)
1347 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1348 struct a2dp_stream_out *out;
1350 out = calloc(1, sizeof(struct a2dp_stream_out));
1356 out->stream.common.get_sample_rate = out_get_sample_rate;
1357 out->stream.common.set_sample_rate = out_set_sample_rate;
1358 out->stream.common.get_buffer_size = out_get_buffer_size;
1359 out->stream.common.get_channels = out_get_channels;
1360 out->stream.common.get_format = out_get_format;
1361 out->stream.common.set_format = out_set_format;
1362 out->stream.common.standby = out_standby;
1363 out->stream.common.dump = out_dump;
1364 out->stream.common.set_parameters = out_set_parameters;
1365 out->stream.common.get_parameters = out_get_parameters;
1366 out->stream.common.add_audio_effect = out_add_audio_effect;
1367 out->stream.common.remove_audio_effect = out_remove_audio_effect;
1368 out->stream.get_latency = out_get_latency;
1369 out->stream.set_volume = out_set_volume;
1370 out->stream.write = out_write;
1371 out->stream.get_render_position = out_get_render_position;
1373 /* TODO: for now we always use endpoint 0 */
1374 out->ep = &audio_endpoints[0];
1376 if (!open_endpoint(out->ep, &out->cfg))
1379 DBG("rate=%d channels=%d format=%d", out->cfg.rate,
1380 out->cfg.channels, out->cfg.format);
1382 if (out->cfg.channels == AUDIO_CHANNEL_OUT_MONO) {
1383 out->downmix_buf = malloc(FIXED_BUFFER_SIZE / 2);
1384 if (!out->downmix_buf)
1388 *stream_out = &out->stream;
1389 a2dp_dev->out = out;
1391 out->audio_state = AUDIO_A2DP_STATE_STANDBY;
1396 error("audio: cannot open output stream");
1402 static void audio_close_output_stream(struct audio_hw_device *dev,
1403 struct audio_stream_out *stream)
1405 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1406 struct a2dp_stream_out *out = (struct a2dp_stream_out *) stream;
1410 close_endpoint(a2dp_dev->out->ep);
1412 free(out->downmix_buf);
1415 a2dp_dev->out = NULL;
1418 static int audio_set_parameters(struct audio_hw_device *dev,
1419 const char *kvpairs)
1421 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *) dev;
1422 struct a2dp_stream_out *out = a2dp_dev->out;
1429 return out->stream.common.set_parameters((struct audio_stream *) out,
1433 static char *audio_get_parameters(const struct audio_hw_device *dev,
1440 static int audio_init_check(const struct audio_hw_device *dev)
1446 static int audio_set_voice_volume(struct audio_hw_device *dev, float volume)
1452 static int audio_set_master_volume(struct audio_hw_device *dev, float volume)
1458 static int audio_set_mode(struct audio_hw_device *dev, int mode)
1464 static int audio_set_mic_mute(struct audio_hw_device *dev, bool state)
1470 static int audio_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1476 static size_t audio_get_input_buffer_size(const struct audio_hw_device *dev,
1477 const struct audio_config *config)
1483 static int audio_open_input_stream(struct audio_hw_device *dev,
1484 audio_io_handle_t handle,
1485 audio_devices_t devices,
1486 struct audio_config *config,
1487 struct audio_stream_in **stream_in)
1489 struct audio_stream_in *in;
1493 in = calloc(1, sizeof(struct audio_stream_in));
1497 in->common.get_sample_rate = in_get_sample_rate;
1498 in->common.set_sample_rate = in_set_sample_rate;
1499 in->common.get_buffer_size = in_get_buffer_size;
1500 in->common.get_channels = in_get_channels;
1501 in->common.get_format = in_get_format;
1502 in->common.set_format = in_set_format;
1503 in->common.standby = in_standby;
1504 in->common.dump = in_dump;
1505 in->common.set_parameters = in_set_parameters;
1506 in->common.get_parameters = in_get_parameters;
1507 in->common.add_audio_effect = in_add_audio_effect;
1508 in->common.remove_audio_effect = in_remove_audio_effect;
1509 in->set_gain = in_set_gain;
1511 in->get_input_frames_lost = in_get_input_frames_lost;
1518 static void audio_close_input_stream(struct audio_hw_device *dev,
1519 struct audio_stream_in *stream_in)
1525 static int audio_dump(const audio_hw_device_t *device, int fd)
1531 static int audio_close(hw_device_t *device)
1533 struct a2dp_audio_dev *a2dp_dev = (struct a2dp_audio_dev *)device;
1537 unregister_endpoints();
1539 shutdown(listen_sk, SHUT_RDWR);
1540 shutdown(audio_sk, SHUT_RDWR);
1542 pthread_join(ipc_th, NULL);
1551 static void *ipc_handler(void *data)
1560 DBG("Waiting for connection ...");
1562 sk = accept(listen_sk, NULL, NULL);
1569 if (err != ECONNABORTED && err != EINVAL)
1570 error("audio: Failed to accept socket: %d (%s)",
1571 err, strerror(err));
1576 pthread_mutex_lock(&sk_mutex);
1578 pthread_mutex_unlock(&sk_mutex);
1580 DBG("Audio IPC: Connected");
1582 if (register_endpoints() != AUDIO_STATUS_SUCCESS) {
1583 error("audio: Failed to register endpoints");
1585 unregister_endpoints();
1587 pthread_mutex_lock(&sk_mutex);
1588 shutdown(audio_sk, SHUT_RDWR);
1591 pthread_mutex_unlock(&sk_mutex);
1596 memset(&pfd, 0, sizeof(pfd));
1598 pfd.events = POLLHUP | POLLERR | POLLNVAL;
1600 /* Check if socket is still alive. Empty while loop.*/
1601 while (poll(&pfd, 1, -1) < 0 && errno == EINTR);
1603 if (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)) {
1604 info("Audio HAL: Socket closed");
1606 pthread_mutex_lock(&sk_mutex);
1609 pthread_mutex_unlock(&sk_mutex);
1613 /* audio_sk is closed at this point, just cleanup endpoints states */
1614 memset(audio_endpoints, 0, sizeof(audio_endpoints));
1616 info("Closing Audio IPC thread");
1620 static int audio_ipc_init(void)
1622 struct sockaddr_un addr;
1628 sk = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
1631 error("audio: Failed to create socket: %d (%s)", -err,
1636 memset(&addr, 0, sizeof(addr));
1637 addr.sun_family = AF_UNIX;
1639 memcpy(addr.sun_path, BLUEZ_AUDIO_SK_PATH,
1640 sizeof(BLUEZ_AUDIO_SK_PATH));
1642 if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1644 error("audio: Failed to bind socket: %d (%s)", -err,
1649 if (listen(sk, 1) < 0) {
1651 error("audio: Failed to listen on the socket: %d (%s)", -err,
1658 err = pthread_create(&ipc_th, NULL, ipc_handler, NULL);
1662 error("audio: Failed to start Audio IPC thread: %d (%s)",
1663 -err, strerror(-err));
1674 static int audio_open(const hw_module_t *module, const char *name,
1675 hw_device_t **device)
1677 struct a2dp_audio_dev *a2dp_dev;
1682 if (strcmp(name, AUDIO_HARDWARE_INTERFACE)) {
1683 error("audio: interface %s not matching [%s]", name,
1684 AUDIO_HARDWARE_INTERFACE);
1688 err = audio_ipc_init();
1692 a2dp_dev = calloc(1, sizeof(struct a2dp_audio_dev));
1696 a2dp_dev->dev.common.tag = HARDWARE_DEVICE_TAG;
1697 a2dp_dev->dev.common.version = AUDIO_DEVICE_API_VERSION_CURRENT;
1698 a2dp_dev->dev.common.module = (struct hw_module_t *) module;
1699 a2dp_dev->dev.common.close = audio_close;
1701 a2dp_dev->dev.init_check = audio_init_check;
1702 a2dp_dev->dev.set_voice_volume = audio_set_voice_volume;
1703 a2dp_dev->dev.set_master_volume = audio_set_master_volume;
1704 a2dp_dev->dev.set_mode = audio_set_mode;
1705 a2dp_dev->dev.set_mic_mute = audio_set_mic_mute;
1706 a2dp_dev->dev.get_mic_mute = audio_get_mic_mute;
1707 a2dp_dev->dev.set_parameters = audio_set_parameters;
1708 a2dp_dev->dev.get_parameters = audio_get_parameters;
1709 a2dp_dev->dev.get_input_buffer_size = audio_get_input_buffer_size;
1710 a2dp_dev->dev.open_output_stream = audio_open_output_stream;
1711 a2dp_dev->dev.close_output_stream = audio_close_output_stream;
1712 a2dp_dev->dev.open_input_stream = audio_open_input_stream;
1713 a2dp_dev->dev.close_input_stream = audio_close_input_stream;
1714 a2dp_dev->dev.dump = audio_dump;
1716 /* Note that &a2dp_dev->dev.common is the same pointer as a2dp_dev.
1717 * This results from the structure of following structs:a2dp_audio_dev,
1718 * audio_hw_device. We will rely on this later in the code.*/
1719 *device = &a2dp_dev->dev.common;
1724 static struct hw_module_methods_t hal_module_methods = {
1728 struct audio_module HAL_MODULE_INFO_SYM = {
1730 .tag = HARDWARE_MODULE_TAG,
1733 .id = AUDIO_HARDWARE_MODULE_ID,
1734 .name = "A2DP Bluez HW HAL",
1735 .author = "Intel Corporation",
1736 .methods = &hal_module_methods,