Home | History | Annotate | Download | only in audio
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "audio_hw_primary"
     18 /*#define LOG_NDEBUG 0*/
     19 
     20 #include <errno.h>
     21 #include <pthread.h>
     22 #include <stdint.h>
     23 #include <stdlib.h>
     24 #include <sys/time.h>
     25 
     26 #include <cutils/log.h>
     27 #include <cutils/properties.h>
     28 #include <cutils/str_parms.h>
     29 
     30 #include <hardware/audio.h>
     31 #include <hardware/hardware.h>
     32 
     33 #include <system/audio.h>
     34 
     35 #include <tinyalsa/asoundlib.h>
     36 
     37 #include <audio_utils/resampler.h>
     38 
     39 #include "audio_route.h"
     40 
     41 #define PCM_CARD 1
     42 #define PCM_DEVICE 0
     43 #define PCM_DEVICE_SCO 2
     44 
     45 #define OUT_PERIOD_SIZE 880
     46 #define OUT_SHORT_PERIOD_COUNT 2
     47 #define OUT_LONG_PERIOD_COUNT 8
     48 #define OUT_SAMPLING_RATE 44100
     49 
     50 #define IN_PERIOD_SIZE 1024
     51 #define IN_PERIOD_COUNT 4
     52 #define IN_SAMPLING_RATE 44100
     53 
     54 #define SCO_PERIOD_SIZE 256
     55 #define SCO_PERIOD_COUNT 4
     56 #define SCO_SAMPLING_RATE 8000
     57 
     58 /* minimum sleep time in out_write() when write threshold is not reached */
     59 #define MIN_WRITE_SLEEP_US 2000
     60 #define MAX_WRITE_SLEEP_US ((OUT_PERIOD_SIZE * OUT_SHORT_PERIOD_COUNT * 1000000) \
     61                                 / OUT_SAMPLING_RATE)
     62 
     63 enum {
     64     OUT_BUFFER_TYPE_UNKNOWN,
     65     OUT_BUFFER_TYPE_SHORT,
     66     OUT_BUFFER_TYPE_LONG,
     67 };
     68 
     69 struct pcm_config pcm_config_out = {
     70     .channels = 2,
     71     .rate = OUT_SAMPLING_RATE,
     72     .period_size = OUT_PERIOD_SIZE,
     73     .period_count = OUT_LONG_PERIOD_COUNT,
     74     .format = PCM_FORMAT_S16_LE,
     75     .start_threshold = OUT_PERIOD_SIZE * OUT_SHORT_PERIOD_COUNT,
     76 };
     77 
     78 struct pcm_config pcm_config_in = {
     79     .channels = 2,
     80     .rate = IN_SAMPLING_RATE,
     81     .period_size = IN_PERIOD_SIZE,
     82     .period_count = IN_PERIOD_COUNT,
     83     .format = PCM_FORMAT_S16_LE,
     84     .start_threshold = 1,
     85     .stop_threshold = (IN_PERIOD_SIZE * IN_PERIOD_COUNT),
     86 };
     87 
     88 struct pcm_config pcm_config_sco = {
     89     .channels = 1,
     90     .rate = SCO_SAMPLING_RATE,
     91     .period_size = SCO_PERIOD_SIZE,
     92     .period_count = SCO_PERIOD_COUNT,
     93     .format = PCM_FORMAT_S16_LE,
     94 };
     95 
     96 struct audio_device {
     97     struct audio_hw_device hw_device;
     98 
     99     pthread_mutex_t lock; /* see note below on mutex acquisition order */
    100     unsigned int devices;
    101     bool standby;
    102     bool mic_mute;
    103     struct audio_route *ar;
    104     int orientation;
    105     bool screen_off;
    106 
    107     struct stream_out *active_out;
    108     struct stream_in *active_in;
    109 };
    110 
    111 struct stream_out {
    112     struct audio_stream_out stream;
    113 
    114     pthread_mutex_t lock; /* see note below on mutex acquisition order */
    115     struct pcm *pcm;
    116     struct pcm_config *pcm_config;
    117     bool standby;
    118 
    119     struct resampler_itfe *resampler;
    120     int16_t *buffer;
    121     size_t buffer_frames;
    122 
    123     int write_threshold;
    124     int cur_write_threshold;
    125     int buffer_type;
    126 
    127     struct audio_device *dev;
    128 };
    129 
    130 struct stream_in {
    131     struct audio_stream_in stream;
    132 
    133     pthread_mutex_t lock; /* see note below on mutex acquisition order */
    134     struct pcm *pcm;
    135     struct pcm_config *pcm_config;
    136     bool standby;
    137 
    138     unsigned int requested_rate;
    139     struct resampler_itfe *resampler;
    140     struct resampler_buffer_provider buf_provider;
    141     int16_t *buffer;
    142     size_t buffer_size;
    143     size_t frames_in;
    144     int read_status;
    145 
    146     struct audio_device *dev;
    147 };
    148 
    149 enum {
    150     ORIENTATION_LANDSCAPE,
    151     ORIENTATION_PORTRAIT,
    152     ORIENTATION_SQUARE,
    153     ORIENTATION_UNDEFINED,
    154 };
    155 
    156 static uint32_t out_get_sample_rate(const struct audio_stream *stream);
    157 static size_t out_get_buffer_size(const struct audio_stream *stream);
    158 static audio_format_t out_get_format(const struct audio_stream *stream);
    159 static uint32_t in_get_sample_rate(const struct audio_stream *stream);
    160 static size_t in_get_buffer_size(const struct audio_stream *stream);
    161 static audio_format_t in_get_format(const struct audio_stream *stream);
    162 static int get_next_buffer(struct resampler_buffer_provider *buffer_provider,
    163                                    struct resampler_buffer* buffer);
    164 static void release_buffer(struct resampler_buffer_provider *buffer_provider,
    165                                   struct resampler_buffer* buffer);
    166 
    167 /*
    168  * NOTE: when multiple mutexes have to be acquired, always take the
    169  * audio_device mutex first, followed by the stream_in and/or
    170  * stream_out mutexes.
    171  */
    172 
    173 /* Helper functions */
    174 
    175 static void select_devices(struct audio_device *adev)
    176 {
    177     int headphone_on;
    178     int speaker_on;
    179     int main_mic_on;
    180 
    181     headphone_on = adev->devices & (AUDIO_DEVICE_OUT_WIRED_HEADSET |
    182                                     AUDIO_DEVICE_OUT_WIRED_HEADPHONE);
    183     speaker_on = adev->devices & AUDIO_DEVICE_OUT_SPEAKER;
    184     main_mic_on = adev->devices & AUDIO_DEVICE_IN_BUILTIN_MIC;
    185 
    186     reset_mixer_state(adev->ar);
    187 
    188     if (speaker_on)
    189         audio_route_apply_path(adev->ar, "speaker");
    190     if (headphone_on)
    191         audio_route_apply_path(adev->ar, "headphone");
    192     if (main_mic_on) {
    193         if (adev->orientation == ORIENTATION_LANDSCAPE)
    194             audio_route_apply_path(adev->ar, "main-mic-left");
    195         else
    196             audio_route_apply_path(adev->ar, "main-mic-top");
    197     }
    198 
    199     update_mixer_state(adev->ar);
    200 
    201     ALOGV("hp=%c speaker=%c main-mic=%c", headphone_on ? 'y' : 'n',
    202           speaker_on ? 'y' : 'n', main_mic_on ? 'y' : 'n');
    203 }
    204 
    205 /* must be called with hw device and output stream mutexes locked */
    206 static void do_out_standby(struct stream_out *out)
    207 {
    208     struct audio_device *adev = out->dev;
    209 
    210     if (!out->standby) {
    211         pcm_close(out->pcm);
    212         out->pcm = NULL;
    213         adev->active_out = NULL;
    214         if (out->resampler) {
    215             release_resampler(out->resampler);
    216             out->resampler = NULL;
    217         }
    218         if (out->buffer) {
    219             free(out->buffer);
    220             out->buffer = NULL;
    221         }
    222         out->standby = true;
    223     }
    224 }
    225 
    226 /* must be called with hw device and input stream mutexes locked */
    227 static void do_in_standby(struct stream_in *in)
    228 {
    229     struct audio_device *adev = in->dev;
    230 
    231     if (!in->standby) {
    232         pcm_close(in->pcm);
    233         in->pcm = NULL;
    234         adev->active_in = NULL;
    235         if (in->resampler) {
    236             release_resampler(in->resampler);
    237             in->resampler = NULL;
    238         }
    239         if (in->buffer) {
    240             free(in->buffer);
    241             in->buffer = NULL;
    242         }
    243         in->standby = true;
    244     }
    245 }
    246 
    247 /* must be called with hw device and output stream mutexes locked */
    248 static int start_output_stream(struct stream_out *out)
    249 {
    250     struct audio_device *adev = out->dev;
    251     unsigned int device;
    252     int ret;
    253 
    254     /*
    255      * Due to the lack of sample rate converters in the SoC,
    256      * it greatly simplifies things to have only the main
    257      * (speaker/headphone) PCM or the BC SCO PCM open at
    258      * the same time.
    259      */
    260     if (adev->devices & AUDIO_DEVICE_OUT_ALL_SCO) {
    261         device = PCM_DEVICE_SCO;
    262         out->pcm_config = &pcm_config_sco;
    263     } else {
    264         device = PCM_DEVICE;
    265         out->pcm_config = &pcm_config_out;
    266         out->buffer_type = OUT_BUFFER_TYPE_UNKNOWN;
    267     }
    268 
    269     /*
    270      * All open PCMs can only use a single group of rates at once:
    271      * Group 1: 11.025, 22.05, 44.1
    272      * Group 2: 8, 16, 32, 48
    273      * Group 1 is used for digital audio playback since 44.1 is
    274      * the most common rate, but group 2 is required for SCO.
    275      */
    276     if (adev->active_in) {
    277         pthread_mutex_lock(&adev->active_in->lock);
    278         if (((out->pcm_config->rate % 8000 == 0) &&
    279                  (adev->active_in->pcm_config->rate % 8000) != 0) ||
    280                  ((out->pcm_config->rate % 11025 == 0) &&
    281                  (adev->active_in->pcm_config->rate % 11025) != 0))
    282             do_in_standby(adev->active_in);
    283         pthread_mutex_unlock(&adev->active_in->lock);
    284     }
    285 
    286     out->pcm = pcm_open(PCM_CARD, device, PCM_OUT | PCM_NORESTART, out->pcm_config);
    287 
    288     if (out->pcm && !pcm_is_ready(out->pcm)) {
    289         ALOGE("pcm_open(out) failed: %s", pcm_get_error(out->pcm));
    290         pcm_close(out->pcm);
    291         return -ENOMEM;
    292     }
    293 
    294     /*
    295      * If the stream rate differs from the PCM rate, we need to
    296      * create a resampler.
    297      */
    298     if (out_get_sample_rate(&out->stream.common) != out->pcm_config->rate) {
    299         ret = create_resampler(out_get_sample_rate(&out->stream.common),
    300                                out->pcm_config->rate,
    301                                out->pcm_config->channels,
    302                                RESAMPLER_QUALITY_DEFAULT,
    303                                NULL,
    304                                &out->resampler);
    305         out->buffer_frames = (pcm_config_out.period_size * out->pcm_config->rate) /
    306                 out_get_sample_rate(&out->stream.common) + 1;
    307 
    308         out->buffer = malloc(pcm_frames_to_bytes(out->pcm, out->buffer_frames));
    309     }
    310 
    311     adev->active_out = out;
    312 
    313     return 0;
    314 }
    315 
    316 /* must be called with hw device and input stream mutexes locked */
    317 static int start_input_stream(struct stream_in *in)
    318 {
    319     struct audio_device *adev = in->dev;
    320     unsigned int device;
    321     int ret;
    322 
    323     /*
    324      * Due to the lack of sample rate converters in the SoC,
    325      * it greatly simplifies things to have only the main
    326      * mic PCM or the BC SCO PCM open at the same time.
    327      */
    328     if (adev->devices & AUDIO_DEVICE_IN_ALL_SCO) {
    329         device = PCM_DEVICE_SCO;
    330         in->pcm_config = &pcm_config_sco;
    331     } else {
    332         device = PCM_DEVICE;
    333         in->pcm_config = &pcm_config_in;
    334     }
    335 
    336     /*
    337      * All open PCMs can only use a single group of rates at once:
    338      * Group 1: 11.025, 22.05, 44.1
    339      * Group 2: 8, 16, 32, 48
    340      * Group 1 is used for digital audio playback since 44.1 is
    341      * the most common rate, but group 2 is required for SCO.
    342      */
    343     if (adev->active_out) {
    344         pthread_mutex_lock(&adev->active_out->lock);
    345         if (((in->pcm_config->rate % 8000 == 0) &&
    346                  (adev->active_out->pcm_config->rate % 8000) != 0) ||
    347                  ((in->pcm_config->rate % 11025 == 0) &&
    348                  (adev->active_out->pcm_config->rate % 11025) != 0))
    349             do_out_standby(adev->active_out);
    350         pthread_mutex_unlock(&adev->active_out->lock);
    351     }
    352 
    353     in->pcm = pcm_open(PCM_CARD, device, PCM_IN, in->pcm_config);
    354 
    355     if (in->pcm && !pcm_is_ready(in->pcm)) {
    356         ALOGE("pcm_open(in) failed: %s", pcm_get_error(in->pcm));
    357         pcm_close(in->pcm);
    358         return -ENOMEM;
    359     }
    360 
    361     /*
    362      * If the stream rate differs from the PCM rate, we need to
    363      * create a resampler.
    364      */
    365     if (in_get_sample_rate(&in->stream.common) != in->pcm_config->rate) {
    366         in->buf_provider.get_next_buffer = get_next_buffer;
    367         in->buf_provider.release_buffer = release_buffer;
    368 
    369         ret = create_resampler(in->pcm_config->rate,
    370                                in_get_sample_rate(&in->stream.common),
    371                                1,
    372                                RESAMPLER_QUALITY_DEFAULT,
    373                                &in->buf_provider,
    374                                &in->resampler);
    375     }
    376     in->buffer_size = pcm_frames_to_bytes(in->pcm,
    377                                           in->pcm_config->period_size);
    378     in->buffer = malloc(in->buffer_size);
    379 
    380     adev->active_in = in;
    381 
    382     return 0;
    383 }
    384 
    385 static int get_next_buffer(struct resampler_buffer_provider *buffer_provider,
    386                                    struct resampler_buffer* buffer)
    387 {
    388     struct stream_in *in;
    389 
    390     if (buffer_provider == NULL || buffer == NULL)
    391         return -EINVAL;
    392 
    393     in = (struct stream_in *)((char *)buffer_provider -
    394                                    offsetof(struct stream_in, buf_provider));
    395 
    396     if (in->pcm == NULL) {
    397         buffer->raw = NULL;
    398         buffer->frame_count = 0;
    399         in->read_status = -ENODEV;
    400         return -ENODEV;
    401     }
    402 
    403     if (in->frames_in == 0) {
    404         in->read_status = pcm_read(in->pcm,
    405                                    (void*)in->buffer,
    406                                    in->buffer_size);
    407         if (in->read_status != 0) {
    408             ALOGE("get_next_buffer() pcm_read error %d", in->read_status);
    409             buffer->raw = NULL;
    410             buffer->frame_count = 0;
    411             return in->read_status;
    412         }
    413         in->frames_in = in->pcm_config->period_size;
    414         if (in->pcm_config->channels == 2) {
    415             unsigned int i;
    416 
    417             /* Discard right channel */
    418             for (i = 1; i < in->frames_in; i++)
    419                 in->buffer[i] = in->buffer[i * 2];
    420         }
    421     }
    422 
    423     buffer->frame_count = (buffer->frame_count > in->frames_in) ?
    424                                 in->frames_in : buffer->frame_count;
    425     buffer->i16 = in->buffer + (in->pcm_config->period_size - in->frames_in);
    426 
    427     return in->read_status;
    428 
    429 }
    430 
    431 static void release_buffer(struct resampler_buffer_provider *buffer_provider,
    432                                   struct resampler_buffer* buffer)
    433 {
    434     struct stream_in *in;
    435 
    436     if (buffer_provider == NULL || buffer == NULL)
    437         return;
    438 
    439     in = (struct stream_in *)((char *)buffer_provider -
    440                                    offsetof(struct stream_in, buf_provider));
    441 
    442     in->frames_in -= buffer->frame_count;
    443 }
    444 
    445 /* read_frames() reads frames from kernel driver, down samples to capture rate
    446  * if necessary and output the number of frames requested to the buffer specified */
    447 static ssize_t read_frames(struct stream_in *in, void *buffer, ssize_t frames)
    448 {
    449     ssize_t frames_wr = 0;
    450 
    451     while (frames_wr < frames) {
    452         size_t frames_rd = frames - frames_wr;
    453         if (in->resampler != NULL) {
    454             in->resampler->resample_from_provider(in->resampler,
    455                     (int16_t *)((char *)buffer +
    456                             frames_wr * audio_stream_frame_size(&in->stream.common)),
    457                     &frames_rd);
    458         } else {
    459             struct resampler_buffer buf = {
    460                     { raw : NULL, },
    461                     frame_count : frames_rd,
    462             };
    463             get_next_buffer(&in->buf_provider, &buf);
    464             if (buf.raw != NULL) {
    465                 memcpy((char *)buffer +
    466                            frames_wr * audio_stream_frame_size(&in->stream.common),
    467                         buf.raw,
    468                         buf.frame_count * audio_stream_frame_size(&in->stream.common));
    469                 frames_rd = buf.frame_count;
    470             }
    471             release_buffer(&in->buf_provider, &buf);
    472         }
    473         /* in->read_status is updated by getNextBuffer() also called by
    474          * in->resampler->resample_from_provider() */
    475         if (in->read_status != 0)
    476             return in->read_status;
    477 
    478         frames_wr += frames_rd;
    479     }
    480     return frames_wr;
    481 }
    482 
    483 /* API functions */
    484 
    485 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
    486 {
    487     return pcm_config_out.rate;
    488 }
    489 
    490 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
    491 {
    492     return -ENOSYS;
    493 }
    494 
    495 static size_t out_get_buffer_size(const struct audio_stream *stream)
    496 {
    497     return pcm_config_out.period_size *
    498                audio_stream_frame_size((struct audio_stream *)stream);
    499 }
    500 
    501 static uint32_t out_get_channels(const struct audio_stream *stream)
    502 {
    503     return AUDIO_CHANNEL_OUT_STEREO;
    504 }
    505 
    506 static audio_format_t out_get_format(const struct audio_stream *stream)
    507 {
    508     return AUDIO_FORMAT_PCM_16_BIT;
    509 }
    510 
    511 static int out_set_format(struct audio_stream *stream, audio_format_t format)
    512 {
    513     return -ENOSYS;
    514 }
    515 
    516 static int out_standby(struct audio_stream *stream)
    517 {
    518     struct stream_out *out = (struct stream_out *)stream;
    519 
    520     pthread_mutex_lock(&out->dev->lock);
    521     pthread_mutex_lock(&out->lock);
    522     do_out_standby(out);
    523     pthread_mutex_unlock(&out->lock);
    524     pthread_mutex_unlock(&out->dev->lock);
    525 
    526     return 0;
    527 }
    528 
    529 static int out_dump(const struct audio_stream *stream, int fd)
    530 {
    531     return 0;
    532 }
    533 
    534 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
    535 {
    536     struct stream_out *out = (struct stream_out *)stream;
    537     struct audio_device *adev = out->dev;
    538     struct str_parms *parms;
    539     char value[32];
    540     int ret;
    541     unsigned int val;
    542 
    543     parms = str_parms_create_str(kvpairs);
    544 
    545     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING,
    546                             value, sizeof(value));
    547     pthread_mutex_lock(&adev->lock);
    548     if (ret >= 0) {
    549         val = atoi(value);
    550         if (((adev->devices & AUDIO_DEVICE_OUT_ALL) != val) && (val != 0)) {
    551             /*
    552              * If SCO is turned on/off, we need to put audio into standby
    553              * because SCO uses a different PCM.
    554              */
    555             if ((val & AUDIO_DEVICE_OUT_ALL_SCO) ^
    556                     (adev->devices & AUDIO_DEVICE_OUT_ALL_SCO)) {
    557                 pthread_mutex_lock(&out->lock);
    558                 do_out_standby(out);
    559                 pthread_mutex_unlock(&out->lock);
    560             }
    561 
    562             adev->devices &= ~AUDIO_DEVICE_OUT_ALL;
    563             adev->devices |= val;
    564             select_devices(adev);
    565         }
    566     }
    567     pthread_mutex_unlock(&adev->lock);
    568 
    569     str_parms_destroy(parms);
    570     return ret;
    571 }
    572 
    573 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
    574 {
    575     return strdup("");
    576 }
    577 
    578 static uint32_t out_get_latency(const struct audio_stream_out *stream)
    579 {
    580     struct stream_out *out = (struct stream_out *)stream;
    581     struct audio_device *adev = out->dev;
    582     size_t period_count;
    583 
    584     pthread_mutex_lock(&adev->lock);
    585 
    586     if (adev->screen_off && !adev->active_in && !(adev->devices & AUDIO_DEVICE_OUT_ALL_SCO))
    587         period_count = OUT_LONG_PERIOD_COUNT;
    588     else
    589         period_count = OUT_SHORT_PERIOD_COUNT;
    590 
    591     pthread_mutex_unlock(&adev->lock);
    592 
    593     return (pcm_config_out.period_size * period_count * 1000) / pcm_config_out.rate;
    594 }
    595 
    596 static int out_set_volume(struct audio_stream_out *stream, float left,
    597                           float right)
    598 {
    599     return -ENOSYS;
    600 }
    601 
    602 static ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
    603                          size_t bytes)
    604 {
    605     int ret = 0;
    606     struct stream_out *out = (struct stream_out *)stream;
    607     struct audio_device *adev = out->dev;
    608     size_t frame_size = audio_stream_frame_size(&out->stream.common);
    609     int16_t *in_buffer = (int16_t *)buffer;
    610     size_t in_frames = bytes / frame_size;
    611     size_t out_frames;
    612     int buffer_type;
    613     int kernel_frames;
    614     bool sco_on;
    615 
    616     /*
    617      * acquiring hw device mutex systematically is useful if a low
    618      * priority thread is waiting on the output stream mutex - e.g.
    619      * executing out_set_parameters() while holding the hw device
    620      * mutex
    621      */
    622     pthread_mutex_lock(&adev->lock);
    623     pthread_mutex_lock(&out->lock);
    624     if (out->standby) {
    625         ret = start_output_stream(out);
    626         if (ret != 0) {
    627             pthread_mutex_unlock(&adev->lock);
    628             goto exit;
    629         }
    630         out->standby = false;
    631     }
    632     buffer_type = (adev->screen_off && !adev->active_in) ?
    633             OUT_BUFFER_TYPE_LONG : OUT_BUFFER_TYPE_SHORT;
    634     sco_on = (adev->devices & AUDIO_DEVICE_OUT_ALL_SCO);
    635     pthread_mutex_unlock(&adev->lock);
    636 
    637     /* detect changes in screen ON/OFF state and adapt buffer size
    638      * if needed. Do not change buffer size when routed to SCO device. */
    639     if (!sco_on && (buffer_type != out->buffer_type)) {
    640         size_t period_count;
    641 
    642         if (buffer_type == OUT_BUFFER_TYPE_LONG)
    643             period_count = OUT_LONG_PERIOD_COUNT;
    644         else
    645             period_count = OUT_SHORT_PERIOD_COUNT;
    646 
    647         out->write_threshold = out->pcm_config->period_size * period_count;
    648         /* reset current threshold if exiting standby */
    649         if (out->buffer_type == OUT_BUFFER_TYPE_UNKNOWN)
    650             out->cur_write_threshold = out->write_threshold;
    651         out->buffer_type = buffer_type;
    652     }
    653 
    654     /* Reduce number of channels, if necessary */
    655     if (popcount(out_get_channels(&stream->common)) >
    656                  (int)out->pcm_config->channels) {
    657         unsigned int i;
    658 
    659         /* Discard right channel */
    660         for (i = 1; i < in_frames; i++)
    661             in_buffer[i] = in_buffer[i * 2];
    662 
    663         /* The frame size is now half */
    664         frame_size /= 2;
    665     }
    666 
    667     /* Change sample rate, if necessary */
    668     if (out_get_sample_rate(&stream->common) != out->pcm_config->rate) {
    669         out_frames = out->buffer_frames;
    670         out->resampler->resample_from_input(out->resampler,
    671                                             in_buffer, &in_frames,
    672                                             out->buffer, &out_frames);
    673         in_buffer = out->buffer;
    674     } else {
    675         out_frames = in_frames;
    676     }
    677 
    678     if (!sco_on) {
    679         int total_sleep_time_us = 0;
    680         size_t period_size = out->pcm_config->period_size;
    681 
    682         /* do not allow more than out->cur_write_threshold frames in kernel
    683          * pcm driver buffer */
    684         do {
    685             struct timespec time_stamp;
    686             if (pcm_get_htimestamp(out->pcm,
    687                                    (unsigned int *)&kernel_frames,
    688                                    &time_stamp) < 0)
    689                 break;
    690             kernel_frames = pcm_get_buffer_size(out->pcm) - kernel_frames;
    691 
    692             if (kernel_frames > out->cur_write_threshold) {
    693                 int sleep_time_us =
    694                     (int)(((int64_t)(kernel_frames - out->cur_write_threshold)
    695                                     * 1000000) / out->pcm_config->rate);
    696                 if (sleep_time_us < MIN_WRITE_SLEEP_US)
    697                     break;
    698                 total_sleep_time_us += sleep_time_us;
    699                 if (total_sleep_time_us > MAX_WRITE_SLEEP_US) {
    700                     ALOGW("out_write() limiting sleep time %d to %d",
    701                           total_sleep_time_us, MAX_WRITE_SLEEP_US);
    702                     sleep_time_us = MAX_WRITE_SLEEP_US -
    703                                         (total_sleep_time_us - sleep_time_us);
    704                 }
    705                 usleep(sleep_time_us);
    706             }
    707 
    708         } while ((kernel_frames > out->cur_write_threshold) &&
    709                 (total_sleep_time_us <= MAX_WRITE_SLEEP_US));
    710 
    711         /* do not allow abrupt changes on buffer size. Increasing/decreasing
    712          * the threshold by steps of 1/4th of the buffer size keeps the write
    713          * time within a reasonable range during transitions.
    714          * Also reset current threshold just above current filling status when
    715          * kernel buffer is really depleted to allow for smooth catching up with
    716          * target threshold.
    717          */
    718         if (out->cur_write_threshold > out->write_threshold) {
    719             out->cur_write_threshold -= period_size / 4;
    720             if (out->cur_write_threshold < out->write_threshold) {
    721                 out->cur_write_threshold = out->write_threshold;
    722             }
    723         } else if (out->cur_write_threshold < out->write_threshold) {
    724             out->cur_write_threshold += period_size / 4;
    725             if (out->cur_write_threshold > out->write_threshold) {
    726                 out->cur_write_threshold = out->write_threshold;
    727             }
    728         } else if ((kernel_frames < out->write_threshold) &&
    729             ((out->write_threshold - kernel_frames) >
    730                 (int)(period_size * OUT_SHORT_PERIOD_COUNT))) {
    731             out->cur_write_threshold = (kernel_frames / period_size + 1) * period_size;
    732             out->cur_write_threshold += period_size / 4;
    733         }
    734     }
    735 
    736     ret = pcm_write(out->pcm, in_buffer, out_frames * frame_size);
    737     if (ret == -EPIPE) {
    738         /* In case of underrun, don't sleep since we want to catch up asap */
    739         pthread_mutex_unlock(&out->lock);
    740         return ret;
    741     }
    742 
    743 exit:
    744     pthread_mutex_unlock(&out->lock);
    745 
    746     if (ret != 0) {
    747         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
    748                out_get_sample_rate(&stream->common));
    749     }
    750 
    751     return bytes;
    752 }
    753 
    754 static int out_get_render_position(const struct audio_stream_out *stream,
    755                                    uint32_t *dsp_frames)
    756 {
    757     return -EINVAL;
    758 }
    759 
    760 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
    761 {
    762     return 0;
    763 }
    764 
    765 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
    766 {
    767     return 0;
    768 }
    769 
    770 static int out_get_next_write_timestamp(const struct audio_stream_out *stream,
    771                                         int64_t *timestamp)
    772 {
    773     return -EINVAL;
    774 }
    775 
    776 /** audio_stream_in implementation **/
    777 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
    778 {
    779     struct stream_in *in = (struct stream_in *)stream;
    780 
    781     return in->requested_rate;
    782 }
    783 
    784 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
    785 {
    786     return 0;
    787 }
    788 
    789 static size_t in_get_buffer_size(const struct audio_stream *stream)
    790 {
    791     struct stream_in *in = (struct stream_in *)stream;
    792     size_t size;
    793 
    794     /*
    795      * take resampling into account and return the closest majoring
    796      * multiple of 16 frames, as audioflinger expects audio buffers to
    797      * be a multiple of 16 frames
    798      */
    799     size = (in->pcm_config->period_size * in_get_sample_rate(stream)) /
    800             in->pcm_config->rate;
    801     size = ((size + 15) / 16) * 16;
    802 
    803     return size * audio_stream_frame_size((struct audio_stream *)stream);
    804 }
    805 
    806 static uint32_t in_get_channels(const struct audio_stream *stream)
    807 {
    808     return AUDIO_CHANNEL_IN_MONO;
    809 }
    810 
    811 static audio_format_t in_get_format(const struct audio_stream *stream)
    812 {
    813     return AUDIO_FORMAT_PCM_16_BIT;
    814 }
    815 
    816 static int in_set_format(struct audio_stream *stream, audio_format_t format)
    817 {
    818     return -ENOSYS;
    819 }
    820 
    821 static int in_standby(struct audio_stream *stream)
    822 {
    823     struct stream_in *in = (struct stream_in *)stream;
    824 
    825     pthread_mutex_lock(&in->dev->lock);
    826     pthread_mutex_lock(&in->lock);
    827     do_in_standby(in);
    828     pthread_mutex_unlock(&in->lock);
    829     pthread_mutex_unlock(&in->dev->lock);
    830 
    831     return 0;
    832 }
    833 
    834 static int in_dump(const struct audio_stream *stream, int fd)
    835 {
    836     return 0;
    837 }
    838 
    839 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
    840 {
    841     struct stream_in *in = (struct stream_in *)stream;
    842     struct audio_device *adev = in->dev;
    843     struct str_parms *parms;
    844     char value[32];
    845     int ret;
    846     unsigned int val;
    847 
    848     parms = str_parms_create_str(kvpairs);
    849 
    850     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING,
    851                             value, sizeof(value));
    852     pthread_mutex_lock(&adev->lock);
    853     if (ret >= 0) {
    854         val = atoi(value);
    855         if (((adev->devices & AUDIO_DEVICE_IN_ALL) != val) && (val != 0)) {
    856             /*
    857              * If SCO is turned on/off, we need to put audio into standby
    858              * because SCO uses a different PCM.
    859              */
    860             if ((val & AUDIO_DEVICE_IN_ALL_SCO) ^
    861                     (adev->devices & AUDIO_DEVICE_IN_ALL_SCO)) {
    862                 pthread_mutex_lock(&in->lock);
    863                 do_in_standby(in);
    864                 pthread_mutex_unlock(&in->lock);
    865             }
    866 
    867             adev->devices &= ~AUDIO_DEVICE_IN_ALL;
    868             adev->devices |= val;
    869             select_devices(adev);
    870         }
    871     }
    872     pthread_mutex_unlock(&adev->lock);
    873 
    874     str_parms_destroy(parms);
    875     return ret;
    876 }
    877 
    878 static char * in_get_parameters(const struct audio_stream *stream,
    879                                 const char *keys)
    880 {
    881     return strdup("");
    882 }
    883 
    884 static int in_set_gain(struct audio_stream_in *stream, float gain)
    885 {
    886     return 0;
    887 }
    888 
    889 static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
    890                        size_t bytes)
    891 {
    892     int ret = 0;
    893     struct stream_in *in = (struct stream_in *)stream;
    894     struct audio_device *adev = in->dev;
    895     size_t frames_rq = bytes / audio_stream_frame_size(&stream->common);
    896 
    897     /*
    898      * acquiring hw device mutex systematically is useful if a low
    899      * priority thread is waiting on the input stream mutex - e.g.
    900      * executing in_set_parameters() while holding the hw device
    901      * mutex
    902      */
    903     pthread_mutex_lock(&adev->lock);
    904     pthread_mutex_lock(&in->lock);
    905     if (in->standby) {
    906         ret = start_input_stream(in);
    907         if (ret == 0)
    908             in->standby = 0;
    909     }
    910     pthread_mutex_unlock(&adev->lock);
    911 
    912     if (ret < 0)
    913         goto exit;
    914 
    915     /*if (in->num_preprocessors != 0) {
    916         ret = process_frames(in, buffer, frames_rq);
    917     } else */if (in->resampler != NULL) {
    918         ret = read_frames(in, buffer, frames_rq);
    919     } else if (in->pcm_config->channels == 2) {
    920         /*
    921          * If the PCM is stereo, capture twice as many frames and
    922          * discard the right channel.
    923          */
    924         unsigned int i;
    925         int16_t *in_buffer = (int16_t *)buffer;
    926 
    927         ret = pcm_read(in->pcm, in->buffer, bytes * 2);
    928 
    929         /* Discard right channel */
    930         for (i = 0; i < frames_rq; i++)
    931             in_buffer[i] = in->buffer[i * 2];
    932     } else {
    933         ret = pcm_read(in->pcm, buffer, bytes);
    934     }
    935 
    936     if (ret > 0)
    937         ret = 0;
    938 
    939     /*
    940      * Instead of writing zeroes here, we could trust the hardware
    941      * to always provide zeroes when muted.
    942      */
    943     if (ret == 0 && adev->mic_mute)
    944         memset(buffer, 0, bytes);
    945 
    946 exit:
    947     if (ret < 0)
    948         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
    949                in_get_sample_rate(&stream->common));
    950 
    951     pthread_mutex_unlock(&in->lock);
    952     return bytes;
    953 }
    954 
    955 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
    956 {
    957     return 0;
    958 }
    959 
    960 static int in_add_audio_effect(const struct audio_stream *stream,
    961                                effect_handle_t effect)
    962 {
    963     return 0;
    964 }
    965 
    966 static int in_remove_audio_effect(const struct audio_stream *stream,
    967                                   effect_handle_t effect)
    968 {
    969     return 0;
    970 }
    971 
    972 
    973 static int adev_open_output_stream(struct audio_hw_device *dev,
    974                                    audio_io_handle_t handle,
    975                                    audio_devices_t devices,
    976                                    audio_output_flags_t flags,
    977                                    struct audio_config *config,
    978                                    struct audio_stream_out **stream_out)
    979 {
    980     struct audio_device *adev = (struct audio_device *)dev;
    981     struct stream_out *out;
    982     int ret;
    983 
    984     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
    985     if (!out)
    986         return -ENOMEM;
    987 
    988     out->stream.common.get_sample_rate = out_get_sample_rate;
    989     out->stream.common.set_sample_rate = out_set_sample_rate;
    990     out->stream.common.get_buffer_size = out_get_buffer_size;
    991     out->stream.common.get_channels = out_get_channels;
    992     out->stream.common.get_format = out_get_format;
    993     out->stream.common.set_format = out_set_format;
    994     out->stream.common.standby = out_standby;
    995     out->stream.common.dump = out_dump;
    996     out->stream.common.set_parameters = out_set_parameters;
    997     out->stream.common.get_parameters = out_get_parameters;
    998     out->stream.common.add_audio_effect = out_add_audio_effect;
    999     out->stream.common.remove_audio_effect = out_remove_audio_effect;
   1000     out->stream.get_latency = out_get_latency;
   1001     out->stream.set_volume = out_set_volume;
   1002     out->stream.write = out_write;
   1003     out->stream.get_render_position = out_get_render_position;
   1004     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
   1005 
   1006     out->dev = adev;
   1007 
   1008     config->format = out_get_format(&out->stream.common);
   1009     config->channel_mask = out_get_channels(&out->stream.common);
   1010     config->sample_rate = out_get_sample_rate(&out->stream.common);
   1011 
   1012     out->standby = true;
   1013 
   1014     *stream_out = &out->stream;
   1015     return 0;
   1016 
   1017 err_open:
   1018     free(out);
   1019     *stream_out = NULL;
   1020     return ret;
   1021 }
   1022 
   1023 static void adev_close_output_stream(struct audio_hw_device *dev,
   1024                                      struct audio_stream_out *stream)
   1025 {
   1026     out_standby(&stream->common);
   1027     free(stream);
   1028 }
   1029 
   1030 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
   1031 {
   1032     struct audio_device *adev = (struct audio_device *)dev;
   1033     struct str_parms *parms;
   1034     char *str;
   1035     char value[32];
   1036     int ret;
   1037 
   1038     parms = str_parms_create_str(kvpairs);
   1039     ret = str_parms_get_str(parms, "orientation", value, sizeof(value));
   1040     if (ret >= 0) {
   1041         int orientation;
   1042 
   1043         if (strcmp(value, "landscape") == 0)
   1044             orientation = ORIENTATION_LANDSCAPE;
   1045         else if (strcmp(value, "portrait") == 0)
   1046             orientation = ORIENTATION_PORTRAIT;
   1047         else if (strcmp(value, "square") == 0)
   1048             orientation = ORIENTATION_SQUARE;
   1049         else
   1050             orientation = ORIENTATION_UNDEFINED;
   1051 
   1052         pthread_mutex_lock(&adev->lock);
   1053         if (orientation != adev->orientation) {
   1054             adev->orientation = orientation;
   1055             /*
   1056              * Orientation changes can occur with the input device
   1057              * closed so we must call select_devices() here to set
   1058              * up the mixer. This is because select_devices() will
   1059              * not be called when the input device is opened if no
   1060              * other input parameter is changed.
   1061              */
   1062             select_devices(adev);
   1063         }
   1064         pthread_mutex_unlock(&adev->lock);
   1065     }
   1066 
   1067     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
   1068     if (ret >= 0) {
   1069         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   1070             adev->screen_off = false;
   1071         else
   1072             adev->screen_off = true;
   1073     }
   1074 
   1075     str_parms_destroy(parms);
   1076     return ret;
   1077 }
   1078 
   1079 static char * adev_get_parameters(const struct audio_hw_device *dev,
   1080                                   const char *keys)
   1081 {
   1082     return strdup("");
   1083 }
   1084 
   1085 static int adev_init_check(const struct audio_hw_device *dev)
   1086 {
   1087     return 0;
   1088 }
   1089 
   1090 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
   1091 {
   1092     return -ENOSYS;
   1093 }
   1094 
   1095 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
   1096 {
   1097     return -ENOSYS;
   1098 }
   1099 
   1100 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
   1101 {
   1102     return 0;
   1103 }
   1104 
   1105 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
   1106 {
   1107     struct audio_device *adev = (struct audio_device *)dev;
   1108 
   1109     adev->mic_mute = state;
   1110 
   1111     return 0;
   1112 }
   1113 
   1114 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
   1115 {
   1116     struct audio_device *adev = (struct audio_device *)dev;
   1117 
   1118     *state = adev->mic_mute;
   1119 
   1120     return 0;
   1121 }
   1122 
   1123 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
   1124                                          const struct audio_config *config)
   1125 {
   1126     size_t size;
   1127 
   1128     /*
   1129      * take resampling into account and return the closest majoring
   1130      * multiple of 16 frames, as audioflinger expects audio buffers to
   1131      * be a multiple of 16 frames
   1132      */
   1133     size = (pcm_config_in.period_size * config->sample_rate) / pcm_config_in.rate;
   1134     size = ((size + 15) / 16) * 16;
   1135 
   1136     return (size * popcount(config->channel_mask) *
   1137                 audio_bytes_per_sample(config->format));
   1138 }
   1139 
   1140 static int adev_open_input_stream(struct audio_hw_device *dev,
   1141                                   audio_io_handle_t handle,
   1142                                   audio_devices_t devices,
   1143                                   struct audio_config *config,
   1144                                   struct audio_stream_in **stream_in)
   1145 {
   1146     struct audio_device *adev = (struct audio_device *)dev;
   1147     struct stream_in *in;
   1148     int ret;
   1149 
   1150     *stream_in = NULL;
   1151 
   1152     /* Respond with a request for mono if a different format is given. */
   1153     if (config->channel_mask != AUDIO_CHANNEL_IN_MONO) {
   1154         config->channel_mask = AUDIO_CHANNEL_IN_MONO;
   1155         return -EINVAL;
   1156     }
   1157 
   1158     in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
   1159     if (!in)
   1160         return -ENOMEM;
   1161 
   1162     in->stream.common.get_sample_rate = in_get_sample_rate;
   1163     in->stream.common.set_sample_rate = in_set_sample_rate;
   1164     in->stream.common.get_buffer_size = in_get_buffer_size;
   1165     in->stream.common.get_channels = in_get_channels;
   1166     in->stream.common.get_format = in_get_format;
   1167     in->stream.common.set_format = in_set_format;
   1168     in->stream.common.standby = in_standby;
   1169     in->stream.common.dump = in_dump;
   1170     in->stream.common.set_parameters = in_set_parameters;
   1171     in->stream.common.get_parameters = in_get_parameters;
   1172     in->stream.common.add_audio_effect = in_add_audio_effect;
   1173     in->stream.common.remove_audio_effect = in_remove_audio_effect;
   1174     in->stream.set_gain = in_set_gain;
   1175     in->stream.read = in_read;
   1176     in->stream.get_input_frames_lost = in_get_input_frames_lost;
   1177 
   1178     in->dev = adev;
   1179     in->standby = true;
   1180     in->requested_rate = config->sample_rate;
   1181     in->pcm_config = &pcm_config_in; /* default PCM config */
   1182 
   1183     *stream_in = &in->stream;
   1184     return 0;
   1185 }
   1186 
   1187 static void adev_close_input_stream(struct audio_hw_device *dev,
   1188                                    struct audio_stream_in *stream)
   1189 {
   1190     struct stream_in *in = (struct stream_in *)stream;
   1191 
   1192     in_standby(&stream->common);
   1193     free(stream);
   1194 }
   1195 
   1196 static int adev_dump(const audio_hw_device_t *device, int fd)
   1197 {
   1198     return 0;
   1199 }
   1200 
   1201 static int adev_close(hw_device_t *device)
   1202 {
   1203     struct audio_device *adev = (struct audio_device *)device;
   1204 
   1205     audio_route_free(adev->ar);
   1206 
   1207     free(device);
   1208     return 0;
   1209 }
   1210 
   1211 static uint32_t adev_get_supported_devices(const struct audio_hw_device *dev)
   1212 {
   1213     return (/* OUT */
   1214             AUDIO_DEVICE_OUT_SPEAKER |
   1215             AUDIO_DEVICE_OUT_WIRED_HEADSET |
   1216             AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
   1217             AUDIO_DEVICE_OUT_ALL_SCO |
   1218             AUDIO_DEVICE_OUT_DEFAULT |
   1219             /* IN */
   1220             AUDIO_DEVICE_IN_BUILTIN_MIC |
   1221             AUDIO_DEVICE_IN_WIRED_HEADSET |
   1222             AUDIO_DEVICE_IN_BACK_MIC |
   1223             AUDIO_DEVICE_IN_ALL_SCO |
   1224             AUDIO_DEVICE_IN_DEFAULT);
   1225 }
   1226 
   1227 static int adev_open(const hw_module_t* module, const char* name,
   1228                      hw_device_t** device)
   1229 {
   1230     struct audio_device *adev;
   1231     int ret;
   1232 
   1233     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
   1234         return -EINVAL;
   1235 
   1236     adev = calloc(1, sizeof(struct audio_device));
   1237     if (!adev)
   1238         return -ENOMEM;
   1239 
   1240     adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
   1241     adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_1_0;
   1242     adev->hw_device.common.module = (struct hw_module_t *) module;
   1243     adev->hw_device.common.close = adev_close;
   1244 
   1245     adev->hw_device.get_supported_devices = adev_get_supported_devices;
   1246     adev->hw_device.init_check = adev_init_check;
   1247     adev->hw_device.set_voice_volume = adev_set_voice_volume;
   1248     adev->hw_device.set_master_volume = adev_set_master_volume;
   1249     adev->hw_device.set_mode = adev_set_mode;
   1250     adev->hw_device.set_mic_mute = adev_set_mic_mute;
   1251     adev->hw_device.get_mic_mute = adev_get_mic_mute;
   1252     adev->hw_device.set_parameters = adev_set_parameters;
   1253     adev->hw_device.get_parameters = adev_get_parameters;
   1254     adev->hw_device.get_input_buffer_size = adev_get_input_buffer_size;
   1255     adev->hw_device.open_output_stream = adev_open_output_stream;
   1256     adev->hw_device.close_output_stream = adev_close_output_stream;
   1257     adev->hw_device.open_input_stream = adev_open_input_stream;
   1258     adev->hw_device.close_input_stream = adev_close_input_stream;
   1259     adev->hw_device.dump = adev_dump;
   1260 
   1261     adev->ar = audio_route_init();
   1262     adev->orientation = ORIENTATION_UNDEFINED;
   1263 
   1264     *device = &adev->hw_device.common;
   1265 
   1266     return 0;
   1267 }
   1268 
   1269 static struct hw_module_methods_t hal_module_methods = {
   1270     .open = adev_open,
   1271 };
   1272 
   1273 struct audio_module HAL_MODULE_INFO_SYM = {
   1274     .common = {
   1275         .tag = HARDWARE_MODULE_TAG,
   1276         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
   1277         .hal_api_version = HARDWARE_HAL_API_VERSION,
   1278         .id = AUDIO_HARDWARE_MODULE_ID,
   1279         .name = "Grouper audio HW HAL",
   1280         .author = "The Android Open Source Project",
   1281         .methods = &hal_module_methods,
   1282     },
   1283 };
   1284