Home | History | Annotate | Download | only in tinyalsa
      1 /* pcm.c
      2 **
      3 ** Copyright 2011, The Android Open Source Project
      4 **
      5 ** Redistribution and use in source and binary forms, with or without
      6 ** modification, are permitted provided that the following conditions are met:
      7 **     * Redistributions of source code must retain the above copyright
      8 **       notice, this list of conditions and the following disclaimer.
      9 **     * Redistributions in binary form must reproduce the above copyright
     10 **       notice, this list of conditions and the following disclaimer in the
     11 **       documentation and/or other materials provided with the distribution.
     12 **     * Neither the name of The Android Open Source Project nor the names of
     13 **       its contributors may be used to endorse or promote products derived
     14 **       from this software without specific prior written permission.
     15 **
     16 ** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND
     17 ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18 ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19 ** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE
     20 ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21 ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     22 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     23 ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24 ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25 ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
     26 ** DAMAGE.
     27 */
     28 
     29 #include <stdio.h>
     30 #include <stdlib.h>
     31 #include <fcntl.h>
     32 #include <stdarg.h>
     33 #include <string.h>
     34 #include <errno.h>
     35 #include <unistd.h>
     36 #include <poll.h>
     37 
     38 #include <sys/ioctl.h>
     39 #include <sys/mman.h>
     40 #include <sys/time.h>
     41 #include <limits.h>
     42 
     43 #include <linux/ioctl.h>
     44 #define __force
     45 #define __bitwise
     46 #define __user
     47 #include <sound/asound.h>
     48 
     49 #include <tinyalsa/asoundlib.h>
     50 
     51 #define PARAM_MAX SNDRV_PCM_HW_PARAM_LAST_INTERVAL
     52 
     53 /* Logs information into a string; follows snprintf() in that
     54  * offset may be greater than size, and though no characters are copied
     55  * into string, characters are still counted into offset. */
     56 #define STRLOG(string, offset, size, ...) \
     57     do { int temp, clipoffset = offset > size ? size : offset; \
     58          temp = snprintf(string + clipoffset, size - clipoffset, __VA_ARGS__); \
     59          if (temp > 0) offset += temp; } while (0)
     60 
     61 #ifndef ARRAY_SIZE
     62 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
     63 #endif
     64 
     65 /* refer to SNDRV_PCM_ACCESS_##index in sound/asound.h. */
     66 static const char * const access_lookup[] = {
     67         "MMAP_INTERLEAVED",
     68         "MMAP_NONINTERLEAVED",
     69         "MMAP_COMPLEX",
     70         "RW_INTERLEAVED",
     71         "RW_NONINTERLEAVED",
     72 };
     73 
     74 /* refer to SNDRV_PCM_FORMAT_##index in sound/asound.h. */
     75 static const char * const format_lookup[] = {
     76         /*[0] =*/ "S8",
     77         "U8",
     78         "S16_LE",
     79         "S16_BE",
     80         "U16_LE",
     81         "U16_BE",
     82         "S24_LE",
     83         "S24_BE",
     84         "U24_LE",
     85         "U24_BE",
     86         "S32_LE",
     87         "S32_BE",
     88         "U32_LE",
     89         "U32_BE",
     90         "FLOAT_LE",
     91         "FLOAT_BE",
     92         "FLOAT64_LE",
     93         "FLOAT64_BE",
     94         "IEC958_SUBFRAME_LE",
     95         "IEC958_SUBFRAME_BE",
     96         "MU_LAW",
     97         "A_LAW",
     98         "IMA_ADPCM",
     99         "MPEG",
    100         /*[24] =*/ "GSM",
    101         /* gap */
    102         [31] = "SPECIAL",
    103         "S24_3LE",
    104         "S24_3BE",
    105         "U24_3LE",
    106         "U24_3BE",
    107         "S20_3LE",
    108         "S20_3BE",
    109         "U20_3LE",
    110         "U20_3BE",
    111         "S18_3LE",
    112         "S18_3BE",
    113         "U18_3LE",
    114         /*[43] =*/ "U18_3BE",
    115 #if 0
    116         /* recent additions, may not be present on local asound.h */
    117         "G723_24",
    118         "G723_24_1B",
    119         "G723_40",
    120         "G723_40_1B",
    121         "DSD_U8",
    122         "DSD_U16_LE",
    123 #endif
    124 };
    125 
    126 /* refer to SNDRV_PCM_SUBFORMAT_##index in sound/asound.h. */
    127 static const char * const subformat_lookup[] = {
    128         "STD",
    129 };
    130 
    131 static inline int param_is_mask(int p)
    132 {
    133     return (p >= SNDRV_PCM_HW_PARAM_FIRST_MASK) &&
    134         (p <= SNDRV_PCM_HW_PARAM_LAST_MASK);
    135 }
    136 
    137 static inline int param_is_interval(int p)
    138 {
    139     return (p >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL) &&
    140         (p <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL);
    141 }
    142 
    143 static inline struct snd_interval *param_to_interval(struct snd_pcm_hw_params *p, int n)
    144 {
    145     return &(p->intervals[n - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]);
    146 }
    147 
    148 static inline struct snd_mask *param_to_mask(struct snd_pcm_hw_params *p, int n)
    149 {
    150     return &(p->masks[n - SNDRV_PCM_HW_PARAM_FIRST_MASK]);
    151 }
    152 
    153 static void param_set_mask(struct snd_pcm_hw_params *p, int n, unsigned int bit)
    154 {
    155     if (bit >= SNDRV_MASK_MAX)
    156         return;
    157     if (param_is_mask(n)) {
    158         struct snd_mask *m = param_to_mask(p, n);
    159         m->bits[0] = 0;
    160         m->bits[1] = 0;
    161         m->bits[bit >> 5] |= (1 << (bit & 31));
    162     }
    163 }
    164 
    165 static void param_set_min(struct snd_pcm_hw_params *p, int n, unsigned int val)
    166 {
    167     if (param_is_interval(n)) {
    168         struct snd_interval *i = param_to_interval(p, n);
    169         i->min = val;
    170     }
    171 }
    172 
    173 static unsigned int param_get_min(struct snd_pcm_hw_params *p, int n)
    174 {
    175     if (param_is_interval(n)) {
    176         struct snd_interval *i = param_to_interval(p, n);
    177         return i->min;
    178     }
    179     return 0;
    180 }
    181 
    182 static void param_set_max(struct snd_pcm_hw_params *p, int n, unsigned int val)
    183 {
    184     if (param_is_interval(n)) {
    185         struct snd_interval *i = param_to_interval(p, n);
    186         i->max = val;
    187     }
    188 }
    189 
    190 static unsigned int param_get_max(struct snd_pcm_hw_params *p, int n)
    191 {
    192     if (param_is_interval(n)) {
    193         struct snd_interval *i = param_to_interval(p, n);
    194         return i->max;
    195     }
    196     return 0;
    197 }
    198 
    199 static void param_set_int(struct snd_pcm_hw_params *p, int n, unsigned int val)
    200 {
    201     if (param_is_interval(n)) {
    202         struct snd_interval *i = param_to_interval(p, n);
    203         i->min = val;
    204         i->max = val;
    205         i->integer = 1;
    206     }
    207 }
    208 
    209 static unsigned int param_get_int(struct snd_pcm_hw_params *p, int n)
    210 {
    211     if (param_is_interval(n)) {
    212         struct snd_interval *i = param_to_interval(p, n);
    213         if (i->integer)
    214             return i->max;
    215     }
    216     return 0;
    217 }
    218 
    219 static void param_init(struct snd_pcm_hw_params *p)
    220 {
    221     int n;
    222 
    223     memset(p, 0, sizeof(*p));
    224     for (n = SNDRV_PCM_HW_PARAM_FIRST_MASK;
    225          n <= SNDRV_PCM_HW_PARAM_LAST_MASK; n++) {
    226             struct snd_mask *m = param_to_mask(p, n);
    227             m->bits[0] = ~0;
    228             m->bits[1] = ~0;
    229     }
    230     for (n = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
    231          n <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; n++) {
    232             struct snd_interval *i = param_to_interval(p, n);
    233             i->min = 0;
    234             i->max = ~0;
    235     }
    236     p->rmask = ~0U;
    237     p->cmask = 0;
    238     p->info = ~0U;
    239 }
    240 
    241 #define PCM_ERROR_MAX 128
    242 
    243 struct pcm {
    244     int fd;
    245     unsigned int flags;
    246     int running:1;
    247     int prepared:1;
    248     int underruns;
    249     unsigned int buffer_size;
    250     unsigned int boundary;
    251     char error[PCM_ERROR_MAX];
    252     struct pcm_config config;
    253     struct snd_pcm_mmap_status *mmap_status;
    254     struct snd_pcm_mmap_control *mmap_control;
    255     struct snd_pcm_sync_ptr *sync_ptr;
    256     void *mmap_buffer;
    257     unsigned int noirq_frames_per_msec;
    258     int wait_for_avail_min;
    259     unsigned int subdevice;
    260 };
    261 
    262 unsigned int pcm_get_buffer_size(struct pcm *pcm)
    263 {
    264     return pcm->buffer_size;
    265 }
    266 
    267 const char* pcm_get_error(struct pcm *pcm)
    268 {
    269     return pcm->error;
    270 }
    271 
    272 unsigned int pcm_get_subdevice(struct pcm *pcm)
    273 {
    274     return pcm->subdevice;
    275 }
    276 
    277 static int oops(struct pcm *pcm, int e, const char *fmt, ...)
    278 {
    279     va_list ap;
    280     int sz;
    281 
    282     va_start(ap, fmt);
    283     vsnprintf(pcm->error, PCM_ERROR_MAX, fmt, ap);
    284     va_end(ap);
    285     sz = strlen(pcm->error);
    286 
    287     if (e)
    288         snprintf(pcm->error + sz, PCM_ERROR_MAX - sz,
    289                  ": %s", strerror(e));
    290     return -1;
    291 }
    292 
    293 static unsigned int pcm_format_to_alsa(enum pcm_format format)
    294 {
    295     switch (format) {
    296     case PCM_FORMAT_S32_LE:
    297         return SNDRV_PCM_FORMAT_S32_LE;
    298     case PCM_FORMAT_S8:
    299         return SNDRV_PCM_FORMAT_S8;
    300     case PCM_FORMAT_S24_3LE:
    301         return SNDRV_PCM_FORMAT_S24_3LE;
    302     case PCM_FORMAT_S24_LE:
    303         return SNDRV_PCM_FORMAT_S24_LE;
    304     default:
    305     case PCM_FORMAT_S16_LE:
    306         return SNDRV_PCM_FORMAT_S16_LE;
    307     };
    308 }
    309 
    310 unsigned int pcm_format_to_bits(enum pcm_format format)
    311 {
    312     switch (format) {
    313     case PCM_FORMAT_S32_LE:
    314     case PCM_FORMAT_S24_LE:
    315         return 32;
    316     case PCM_FORMAT_S24_3LE:
    317         return 24;
    318     default:
    319     case PCM_FORMAT_S16_LE:
    320         return 16;
    321     };
    322 }
    323 
    324 unsigned int pcm_bytes_to_frames(struct pcm *pcm, unsigned int bytes)
    325 {
    326     return bytes / (pcm->config.channels *
    327         (pcm_format_to_bits(pcm->config.format) >> 3));
    328 }
    329 
    330 unsigned int pcm_frames_to_bytes(struct pcm *pcm, unsigned int frames)
    331 {
    332     return frames * pcm->config.channels *
    333         (pcm_format_to_bits(pcm->config.format) >> 3);
    334 }
    335 
    336 static int pcm_sync_ptr(struct pcm *pcm, int flags) {
    337     if (pcm->sync_ptr) {
    338         pcm->sync_ptr->flags = flags;
    339         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SYNC_PTR, pcm->sync_ptr) < 0)
    340             return -1;
    341     }
    342     return 0;
    343 }
    344 
    345 static int pcm_hw_mmap_status(struct pcm *pcm) {
    346 
    347     if (pcm->sync_ptr)
    348         return 0;
    349 
    350     int page_size = sysconf(_SC_PAGE_SIZE);
    351     pcm->mmap_status = mmap(NULL, page_size, PROT_READ, MAP_FILE | MAP_SHARED,
    352                             pcm->fd, SNDRV_PCM_MMAP_OFFSET_STATUS);
    353     if (pcm->mmap_status == MAP_FAILED)
    354         pcm->mmap_status = NULL;
    355     if (!pcm->mmap_status)
    356         goto mmap_error;
    357 
    358     pcm->mmap_control = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
    359                              MAP_FILE | MAP_SHARED, pcm->fd, SNDRV_PCM_MMAP_OFFSET_CONTROL);
    360     if (pcm->mmap_control == MAP_FAILED)
    361         pcm->mmap_control = NULL;
    362     if (!pcm->mmap_control) {
    363         munmap(pcm->mmap_status, page_size);
    364         pcm->mmap_status = NULL;
    365         goto mmap_error;
    366     }
    367     if (pcm->flags & PCM_MMAP)
    368         pcm->mmap_control->avail_min = pcm->config.avail_min;
    369     else
    370         pcm->mmap_control->avail_min = 1;
    371 
    372     return 0;
    373 
    374 mmap_error:
    375 
    376     pcm->sync_ptr = calloc(1, sizeof(*pcm->sync_ptr));
    377     if (!pcm->sync_ptr)
    378         return -ENOMEM;
    379     pcm->mmap_status = &pcm->sync_ptr->s.status;
    380     pcm->mmap_control = &pcm->sync_ptr->c.control;
    381     if (pcm->flags & PCM_MMAP)
    382         pcm->mmap_control->avail_min = pcm->config.avail_min;
    383     else
    384         pcm->mmap_control->avail_min = 1;
    385 
    386     pcm_sync_ptr(pcm, 0);
    387 
    388     return 0;
    389 }
    390 
    391 static void pcm_hw_munmap_status(struct pcm *pcm) {
    392     if (pcm->sync_ptr) {
    393         free(pcm->sync_ptr);
    394         pcm->sync_ptr = NULL;
    395     } else {
    396         int page_size = sysconf(_SC_PAGE_SIZE);
    397         if (pcm->mmap_status)
    398             munmap(pcm->mmap_status, page_size);
    399         if (pcm->mmap_control)
    400             munmap(pcm->mmap_control, page_size);
    401     }
    402     pcm->mmap_status = NULL;
    403     pcm->mmap_control = NULL;
    404 }
    405 
    406 static int pcm_areas_copy(struct pcm *pcm, unsigned int pcm_offset,
    407                           char *buf, unsigned int src_offset,
    408                           unsigned int frames)
    409 {
    410     int size_bytes = pcm_frames_to_bytes(pcm, frames);
    411     int pcm_offset_bytes = pcm_frames_to_bytes(pcm, pcm_offset);
    412     int src_offset_bytes = pcm_frames_to_bytes(pcm, src_offset);
    413 
    414     /* interleaved only atm */
    415     if (pcm->flags & PCM_IN)
    416         memcpy(buf + src_offset_bytes,
    417                (char*)pcm->mmap_buffer + pcm_offset_bytes,
    418                size_bytes);
    419     else
    420         memcpy((char*)pcm->mmap_buffer + pcm_offset_bytes,
    421                buf + src_offset_bytes,
    422                size_bytes);
    423     return 0;
    424 }
    425 
    426 static int pcm_mmap_transfer_areas(struct pcm *pcm, char *buf,
    427                                 unsigned int offset, unsigned int size)
    428 {
    429     void *pcm_areas;
    430     int commit;
    431     unsigned int pcm_offset, frames, count = 0;
    432 
    433     while (size > 0) {
    434         frames = size;
    435         pcm_mmap_begin(pcm, &pcm_areas, &pcm_offset, &frames);
    436         pcm_areas_copy(pcm, pcm_offset, buf, offset, frames);
    437         commit = pcm_mmap_commit(pcm, pcm_offset, frames);
    438         if (commit < 0) {
    439             oops(pcm, errno, "failed to commit %d frames\n", frames);
    440             return commit;
    441         }
    442 
    443         offset += commit;
    444         count += commit;
    445         size -= commit;
    446     }
    447     return count;
    448 }
    449 
    450 int pcm_get_htimestamp(struct pcm *pcm, unsigned int *avail,
    451                        struct timespec *tstamp)
    452 {
    453     int frames;
    454     int rc;
    455     snd_pcm_uframes_t hw_ptr;
    456 
    457     if (!pcm_is_ready(pcm))
    458         return -1;
    459 
    460     rc = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_HWSYNC);
    461     if (rc < 0)
    462         return -1;
    463 
    464     if ((pcm->mmap_status->state != PCM_STATE_RUNNING) &&
    465             (pcm->mmap_status->state != PCM_STATE_DRAINING))
    466         return -1;
    467 
    468     *tstamp = pcm->mmap_status->tstamp;
    469     if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
    470         return -1;
    471 
    472     hw_ptr = pcm->mmap_status->hw_ptr;
    473     if (pcm->flags & PCM_IN)
    474         frames = hw_ptr - pcm->mmap_control->appl_ptr;
    475     else
    476         frames = hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
    477 
    478     if (frames < 0)
    479         frames += pcm->boundary;
    480     else if (frames > (int)pcm->boundary)
    481         frames -= pcm->boundary;
    482 
    483     *avail = (unsigned int)frames;
    484 
    485     return 0;
    486 }
    487 
    488 int pcm_mmap_get_hw_ptr(struct pcm* pcm, unsigned int *hw_ptr, struct timespec *tstamp)
    489 {
    490     int frames;
    491     int rc;
    492 
    493     if (pcm == NULL || hw_ptr == NULL || tstamp == NULL)
    494         return oops(pcm, EINVAL, "pcm %p, hw_ptr %p, tstamp %p", pcm, hw_ptr, tstamp);
    495 
    496     if (!pcm_is_ready(pcm))
    497         return oops(pcm, errno, "pcm_is_ready failed");
    498 
    499     rc = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
    500     if (rc < 0)
    501         return oops(pcm, errno, "pcm_sync_ptr failed");
    502 
    503     if (pcm->mmap_status == NULL)
    504         return oops(pcm, EINVAL, "pcm %p, mmap_status is NULL", pcm);
    505 
    506     if ((pcm->mmap_status->state != PCM_STATE_RUNNING) &&
    507             (pcm->mmap_status->state != PCM_STATE_DRAINING))
    508         return oops(pcm, ENOSYS, "invalid stream state %d", pcm->mmap_status->state);
    509 
    510     *tstamp = pcm->mmap_status->tstamp;
    511     if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
    512         return oops(pcm, errno, "invalid time stamp");
    513 
    514     *hw_ptr = pcm->mmap_status->hw_ptr;
    515 
    516     return 0;
    517 }
    518 
    519 int pcm_write(struct pcm *pcm, const void *data, unsigned int count)
    520 {
    521     struct snd_xferi x;
    522 
    523     if (pcm->flags & PCM_IN)
    524         return -EINVAL;
    525 
    526     x.buf = (void*)data;
    527     x.frames = count / (pcm->config.channels *
    528                         pcm_format_to_bits(pcm->config.format) / 8);
    529 
    530     for (;;) {
    531         if (!pcm->running) {
    532             int prepare_error = pcm_prepare(pcm);
    533             if (prepare_error)
    534                 return prepare_error;
    535             if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x))
    536                 return oops(pcm, errno, "cannot write initial data");
    537             pcm->running = 1;
    538             return 0;
    539         }
    540         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x)) {
    541             pcm->prepared = 0;
    542             pcm->running = 0;
    543             if (errno == EPIPE) {
    544                 /* we failed to make our window -- try to restart if we are
    545                  * allowed to do so.  Otherwise, simply allow the EPIPE error to
    546                  * propagate up to the app level */
    547                 pcm->underruns++;
    548                 if (pcm->flags & PCM_NORESTART)
    549                     return -EPIPE;
    550                 continue;
    551             }
    552             return oops(pcm, errno, "cannot write stream data");
    553         }
    554         return 0;
    555     }
    556 }
    557 
    558 int pcm_read(struct pcm *pcm, void *data, unsigned int count)
    559 {
    560     struct snd_xferi x;
    561 
    562     if (!(pcm->flags & PCM_IN))
    563         return -EINVAL;
    564 
    565     x.buf = data;
    566     x.frames = count / (pcm->config.channels *
    567                         pcm_format_to_bits(pcm->config.format) / 8);
    568 
    569     for (;;) {
    570         if (!pcm->running) {
    571             if (pcm_start(pcm) < 0) {
    572                 fprintf(stderr, "start error");
    573                 return -errno;
    574             }
    575         }
    576         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_READI_FRAMES, &x)) {
    577             pcm->prepared = 0;
    578             pcm->running = 0;
    579             if (errno == EPIPE) {
    580                     /* we failed to make our window -- try to restart */
    581                 pcm->underruns++;
    582                 continue;
    583             }
    584             return oops(pcm, errno, "cannot read stream data");
    585         }
    586         return 0;
    587     }
    588 }
    589 
    590 static struct pcm bad_pcm = {
    591     .fd = -1,
    592 };
    593 
    594 struct pcm_params *pcm_params_get(unsigned int card, unsigned int device,
    595                                   unsigned int flags)
    596 {
    597     struct snd_pcm_hw_params *params;
    598     char fn[256];
    599     int fd;
    600 
    601     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
    602              flags & PCM_IN ? 'c' : 'p');
    603 
    604     fd = open(fn, O_RDWR);
    605     if (fd < 0) {
    606         fprintf(stderr, "cannot open device '%s'\n", fn);
    607         goto err_open;
    608     }
    609 
    610     params = calloc(1, sizeof(struct snd_pcm_hw_params));
    611     if (!params)
    612         goto err_calloc;
    613 
    614     param_init(params);
    615     if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, params)) {
    616         fprintf(stderr, "SNDRV_PCM_IOCTL_HW_REFINE error (%d)\n", errno);
    617         goto err_hw_refine;
    618     }
    619 
    620     close(fd);
    621 
    622     return (struct pcm_params *)params;
    623 
    624 err_hw_refine:
    625     free(params);
    626 err_calloc:
    627     close(fd);
    628 err_open:
    629     return NULL;
    630 }
    631 
    632 void pcm_params_free(struct pcm_params *pcm_params)
    633 {
    634     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
    635 
    636     if (params)
    637         free(params);
    638 }
    639 
    640 static int pcm_param_to_alsa(enum pcm_param param)
    641 {
    642     switch (param) {
    643     case PCM_PARAM_ACCESS:
    644         return SNDRV_PCM_HW_PARAM_ACCESS;
    645     case PCM_PARAM_FORMAT:
    646         return SNDRV_PCM_HW_PARAM_FORMAT;
    647     case PCM_PARAM_SUBFORMAT:
    648         return SNDRV_PCM_HW_PARAM_SUBFORMAT;
    649     case PCM_PARAM_SAMPLE_BITS:
    650         return SNDRV_PCM_HW_PARAM_SAMPLE_BITS;
    651         break;
    652     case PCM_PARAM_FRAME_BITS:
    653         return SNDRV_PCM_HW_PARAM_FRAME_BITS;
    654         break;
    655     case PCM_PARAM_CHANNELS:
    656         return SNDRV_PCM_HW_PARAM_CHANNELS;
    657         break;
    658     case PCM_PARAM_RATE:
    659         return SNDRV_PCM_HW_PARAM_RATE;
    660         break;
    661     case PCM_PARAM_PERIOD_TIME:
    662         return SNDRV_PCM_HW_PARAM_PERIOD_TIME;
    663         break;
    664     case PCM_PARAM_PERIOD_SIZE:
    665         return SNDRV_PCM_HW_PARAM_PERIOD_SIZE;
    666         break;
    667     case PCM_PARAM_PERIOD_BYTES:
    668         return SNDRV_PCM_HW_PARAM_PERIOD_BYTES;
    669         break;
    670     case PCM_PARAM_PERIODS:
    671         return SNDRV_PCM_HW_PARAM_PERIODS;
    672         break;
    673     case PCM_PARAM_BUFFER_TIME:
    674         return SNDRV_PCM_HW_PARAM_BUFFER_TIME;
    675         break;
    676     case PCM_PARAM_BUFFER_SIZE:
    677         return SNDRV_PCM_HW_PARAM_BUFFER_SIZE;
    678         break;
    679     case PCM_PARAM_BUFFER_BYTES:
    680         return SNDRV_PCM_HW_PARAM_BUFFER_BYTES;
    681         break;
    682     case PCM_PARAM_TICK_TIME:
    683         return SNDRV_PCM_HW_PARAM_TICK_TIME;
    684         break;
    685 
    686     default:
    687         return -1;
    688     }
    689 }
    690 
    691 struct pcm_mask *pcm_params_get_mask(struct pcm_params *pcm_params,
    692                                      enum pcm_param param)
    693 {
    694     int p;
    695     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
    696     if (params == NULL) {
    697         return NULL;
    698     }
    699 
    700     p = pcm_param_to_alsa(param);
    701     if (p < 0 || !param_is_mask(p)) {
    702         return NULL;
    703     }
    704 
    705     return (struct pcm_mask *)param_to_mask(params, p);
    706 }
    707 
    708 unsigned int pcm_params_get_min(struct pcm_params *pcm_params,
    709                                 enum pcm_param param)
    710 {
    711     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
    712     int p;
    713 
    714     if (!params)
    715         return 0;
    716 
    717     p = pcm_param_to_alsa(param);
    718     if (p < 0)
    719         return 0;
    720 
    721     return param_get_min(params, p);
    722 }
    723 
    724 void pcm_params_set_min(struct pcm_params *pcm_params,
    725                                 enum pcm_param param, unsigned int val)
    726 {
    727     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
    728     int p;
    729 
    730     if (!params)
    731         return;
    732 
    733     p = pcm_param_to_alsa(param);
    734     if (p < 0)
    735         return;
    736 
    737     param_set_min(params, p, val);
    738 }
    739 
    740 unsigned int pcm_params_get_max(struct pcm_params *pcm_params,
    741                                 enum pcm_param param)
    742 {
    743     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
    744     int p;
    745 
    746     if (!params)
    747         return 0;
    748 
    749     p = pcm_param_to_alsa(param);
    750     if (p < 0)
    751         return 0;
    752 
    753     return param_get_max(params, p);
    754 }
    755 
    756 void pcm_params_set_max(struct pcm_params *pcm_params,
    757                                 enum pcm_param param, unsigned int val)
    758 {
    759     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
    760     int p;
    761 
    762     if (!params)
    763         return;
    764 
    765     p = pcm_param_to_alsa(param);
    766     if (p < 0)
    767         return;
    768 
    769     param_set_max(params, p, val);
    770 }
    771 
    772 static int pcm_mask_test(struct pcm_mask *m, unsigned int index)
    773 {
    774     const unsigned int bitshift = 5; /* for 32 bit integer */
    775     const unsigned int bitmask = (1 << bitshift) - 1;
    776     unsigned int element;
    777 
    778     element = index >> bitshift;
    779     if (element >= ARRAY_SIZE(m->bits))
    780         return 0; /* for safety, but should never occur */
    781     return (m->bits[element] >> (index & bitmask)) & 1;
    782 }
    783 
    784 static int pcm_mask_to_string(struct pcm_mask *m, char *string, unsigned int size,
    785                               char *mask_name,
    786                               const char * const *bit_array_name, size_t bit_array_size)
    787 {
    788     unsigned int i;
    789     unsigned int offset = 0;
    790 
    791     if (m == NULL)
    792         return 0;
    793     if (bit_array_size < 32) {
    794         STRLOG(string, offset, size, "%12s:\t%#08x\n", mask_name, m->bits[0]);
    795     } else { /* spans two or more bitfields, print with an array index */
    796         for (i = 0; i < (bit_array_size + 31) >> 5; ++i) {
    797             STRLOG(string, offset, size, "%9s[%d]:\t%#08x\n",
    798                    mask_name, i, m->bits[i]);
    799         }
    800     }
    801     for (i = 0; i < bit_array_size; ++i) {
    802         if (pcm_mask_test(m, i)) {
    803             STRLOG(string, offset, size, "%12s \t%s\n", "", bit_array_name[i]);
    804         }
    805     }
    806     return offset;
    807 }
    808 
    809 int pcm_params_to_string(struct pcm_params *params, char *string, unsigned int size)
    810 {
    811     struct pcm_mask *m;
    812     unsigned int min, max;
    813     unsigned int clipoffset, offset;
    814 
    815     m = pcm_params_get_mask(params, PCM_PARAM_ACCESS);
    816     offset = pcm_mask_to_string(m, string, size,
    817                                  "Access", access_lookup, ARRAY_SIZE(access_lookup));
    818     m = pcm_params_get_mask(params, PCM_PARAM_FORMAT);
    819     clipoffset = offset > size ? size : offset;
    820     offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
    821                                  "Format", format_lookup, ARRAY_SIZE(format_lookup));
    822     m = pcm_params_get_mask(params, PCM_PARAM_SUBFORMAT);
    823     clipoffset = offset > size ? size : offset;
    824     offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
    825                                  "Subformat", subformat_lookup, ARRAY_SIZE(subformat_lookup));
    826     min = pcm_params_get_min(params, PCM_PARAM_RATE);
    827     max = pcm_params_get_max(params, PCM_PARAM_RATE);
    828     STRLOG(string, offset, size, "        Rate:\tmin=%uHz\tmax=%uHz\n", min, max);
    829     min = pcm_params_get_min(params, PCM_PARAM_CHANNELS);
    830     max = pcm_params_get_max(params, PCM_PARAM_CHANNELS);
    831     STRLOG(string, offset, size, "    Channels:\tmin=%u\t\tmax=%u\n", min, max);
    832     min = pcm_params_get_min(params, PCM_PARAM_SAMPLE_BITS);
    833     max = pcm_params_get_max(params, PCM_PARAM_SAMPLE_BITS);
    834     STRLOG(string, offset, size, " Sample bits:\tmin=%u\t\tmax=%u\n", min, max);
    835     min = pcm_params_get_min(params, PCM_PARAM_PERIOD_SIZE);
    836     max = pcm_params_get_max(params, PCM_PARAM_PERIOD_SIZE);
    837     STRLOG(string, offset, size, " Period size:\tmin=%u\t\tmax=%u\n", min, max);
    838     min = pcm_params_get_min(params, PCM_PARAM_PERIODS);
    839     max = pcm_params_get_max(params, PCM_PARAM_PERIODS);
    840     STRLOG(string, offset, size, "Period count:\tmin=%u\t\tmax=%u\n", min, max);
    841     return offset;
    842 }
    843 
    844 int pcm_params_format_test(struct pcm_params *params, enum pcm_format format)
    845 {
    846     unsigned int alsa_format = pcm_format_to_alsa(format);
    847 
    848     if (alsa_format == SNDRV_PCM_FORMAT_S16_LE && format != PCM_FORMAT_S16_LE)
    849         return 0; /* caution: format not recognized is equivalent to S16_LE */
    850     return pcm_mask_test(pcm_params_get_mask(params, PCM_PARAM_FORMAT), alsa_format);
    851 }
    852 
    853 int pcm_close(struct pcm *pcm)
    854 {
    855     if (pcm == &bad_pcm)
    856         return 0;
    857 
    858     pcm_hw_munmap_status(pcm);
    859 
    860     if (pcm->flags & PCM_MMAP) {
    861         pcm_stop(pcm);
    862         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
    863     }
    864 
    865     if (pcm->fd >= 0)
    866         close(pcm->fd);
    867     pcm->prepared = 0;
    868     pcm->running = 0;
    869     pcm->buffer_size = 0;
    870     pcm->fd = -1;
    871     free(pcm);
    872     return 0;
    873 }
    874 
    875 struct pcm *pcm_open(unsigned int card, unsigned int device,
    876                      unsigned int flags, struct pcm_config *config)
    877 {
    878     struct pcm *pcm;
    879     struct snd_pcm_info info;
    880     struct snd_pcm_hw_params params;
    881     struct snd_pcm_sw_params sparams;
    882     char fn[256];
    883     int rc;
    884 
    885     if (!config) {
    886         return &bad_pcm; /* TODO: could support default config here */
    887     }
    888     pcm = calloc(1, sizeof(struct pcm));
    889     if (!pcm)
    890         return &bad_pcm; /* TODO: could support default config here */
    891 
    892     pcm->config = *config;
    893 
    894     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
    895              flags & PCM_IN ? 'c' : 'p');
    896 
    897     pcm->flags = flags;
    898     pcm->fd = open(fn, O_RDWR|O_NONBLOCK);
    899     if (pcm->fd < 0) {
    900         oops(pcm, errno, "cannot open device '%s'", fn);
    901         return pcm;
    902     }
    903 
    904     if (fcntl(pcm->fd, F_SETFL, fcntl(pcm->fd, F_GETFL) &
    905               ~O_NONBLOCK) < 0) {
    906         oops(pcm, errno, "failed to reset blocking mode '%s'", fn);
    907         goto fail_close;
    908     }
    909 
    910     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_INFO, &info)) {
    911         oops(pcm, errno, "cannot get info");
    912         goto fail_close;
    913     }
    914     pcm->subdevice = info.subdevice;
    915 
    916     param_init(&params);
    917     param_set_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT,
    918                    pcm_format_to_alsa(config->format));
    919     param_set_mask(&params, SNDRV_PCM_HW_PARAM_SUBFORMAT,
    920                    SNDRV_PCM_SUBFORMAT_STD);
    921     param_set_min(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, config->period_size);
    922     param_set_int(&params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
    923                   pcm_format_to_bits(config->format));
    924     param_set_int(&params, SNDRV_PCM_HW_PARAM_FRAME_BITS,
    925                   pcm_format_to_bits(config->format) * config->channels);
    926     param_set_int(&params, SNDRV_PCM_HW_PARAM_CHANNELS,
    927                   config->channels);
    928     param_set_int(&params, SNDRV_PCM_HW_PARAM_PERIODS, config->period_count);
    929     param_set_int(&params, SNDRV_PCM_HW_PARAM_RATE, config->rate);
    930 
    931     if (flags & PCM_NOIRQ) {
    932         if (!(flags & PCM_MMAP)) {
    933             oops(pcm, EINVAL, "noirq only currently supported with mmap().");
    934             goto fail_close;
    935         }
    936 
    937         params.flags |= SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP;
    938         pcm->noirq_frames_per_msec = config->rate / 1000;
    939     }
    940 
    941     if (flags & PCM_MMAP)
    942         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
    943                        SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
    944     else
    945         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
    946                        SNDRV_PCM_ACCESS_RW_INTERLEAVED);
    947 
    948     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_HW_PARAMS, &params)) {
    949         oops(pcm, errno, "cannot set hw params");
    950         goto fail_close;
    951     }
    952 
    953     /* get our refined hw_params */
    954     config->period_size = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
    955     config->period_count = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIODS);
    956     pcm->buffer_size = config->period_count * config->period_size;
    957 
    958     if (flags & PCM_MMAP) {
    959         pcm->mmap_buffer = mmap(NULL, pcm_frames_to_bytes(pcm, pcm->buffer_size),
    960                                 PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, pcm->fd, 0);
    961         if (pcm->mmap_buffer == MAP_FAILED) {
    962             oops(pcm, errno, "failed to mmap buffer %d bytes\n",
    963                  pcm_frames_to_bytes(pcm, pcm->buffer_size));
    964             goto fail_close;
    965         }
    966     }
    967 
    968     memset(&sparams, 0, sizeof(sparams));
    969     sparams.tstamp_mode = SNDRV_PCM_TSTAMP_ENABLE;
    970     sparams.period_step = 1;
    971 
    972     if (!config->start_threshold) {
    973         if (pcm->flags & PCM_IN)
    974             pcm->config.start_threshold = sparams.start_threshold = 1;
    975         else
    976             pcm->config.start_threshold = sparams.start_threshold =
    977                 config->period_count * config->period_size / 2;
    978     } else
    979         sparams.start_threshold = config->start_threshold;
    980 
    981     /* pick a high stop threshold - todo: does this need further tuning */
    982     if (!config->stop_threshold) {
    983         if (pcm->flags & PCM_IN)
    984             pcm->config.stop_threshold = sparams.stop_threshold =
    985                 config->period_count * config->period_size * 10;
    986         else
    987             pcm->config.stop_threshold = sparams.stop_threshold =
    988                 config->period_count * config->period_size;
    989     }
    990     else
    991         sparams.stop_threshold = config->stop_threshold;
    992 
    993     if (!pcm->config.avail_min) {
    994         if (pcm->flags & PCM_MMAP)
    995             pcm->config.avail_min = sparams.avail_min = pcm->config.period_size;
    996         else
    997             pcm->config.avail_min = sparams.avail_min = 1;
    998     } else
    999         sparams.avail_min = config->avail_min;
   1000 
   1001     sparams.xfer_align = config->period_size / 2; /* needed for old kernels */
   1002     sparams.silence_threshold = config->silence_threshold;
   1003     sparams.silence_size = config->silence_size;
   1004     pcm->boundary = sparams.boundary = pcm->buffer_size;
   1005 
   1006     while (pcm->boundary * 2 <= INT_MAX - pcm->buffer_size)
   1007         pcm->boundary *= 2;
   1008 
   1009     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
   1010         oops(pcm, errno, "cannot set sw params");
   1011         goto fail;
   1012     }
   1013 
   1014     rc = pcm_hw_mmap_status(pcm);
   1015     if (rc < 0) {
   1016         oops(pcm, errno, "mmap status failed");
   1017         goto fail;
   1018     }
   1019 
   1020 #ifdef SNDRV_PCM_IOCTL_TTSTAMP
   1021     if (pcm->flags & PCM_MONOTONIC) {
   1022         int arg = SNDRV_PCM_TSTAMP_TYPE_MONOTONIC;
   1023         rc = ioctl(pcm->fd, SNDRV_PCM_IOCTL_TTSTAMP, &arg);
   1024         if (rc < 0) {
   1025             oops(pcm, errno, "cannot set timestamp type");
   1026             goto fail;
   1027         }
   1028     }
   1029 #endif
   1030 
   1031     pcm->underruns = 0;
   1032     return pcm;
   1033 
   1034 fail:
   1035     if (flags & PCM_MMAP)
   1036         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
   1037 fail_close:
   1038     close(pcm->fd);
   1039     pcm->fd = -1;
   1040     return pcm;
   1041 }
   1042 
   1043 int pcm_is_ready(struct pcm *pcm)
   1044 {
   1045     return pcm->fd >= 0;
   1046 }
   1047 
   1048 int pcm_prepare(struct pcm *pcm)
   1049 {
   1050     if (pcm->prepared)
   1051         return 0;
   1052 
   1053     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE) < 0)
   1054         return oops(pcm, errno, "cannot prepare channel");
   1055 
   1056     pcm->prepared = 1;
   1057     return 0;
   1058 }
   1059 
   1060 int pcm_start(struct pcm *pcm)
   1061 {
   1062     int prepare_error = pcm_prepare(pcm);
   1063     if (prepare_error)
   1064         return prepare_error;
   1065 
   1066     if (pcm->flags & PCM_MMAP)
   1067 	    pcm_sync_ptr(pcm, 0);
   1068 
   1069     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_START) < 0)
   1070         return oops(pcm, errno, "cannot start channel");
   1071 
   1072     pcm->running = 1;
   1073     return 0;
   1074 }
   1075 
   1076 int pcm_stop(struct pcm *pcm)
   1077 {
   1078     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DROP) < 0)
   1079         return oops(pcm, errno, "cannot stop channel");
   1080 
   1081     pcm->prepared = 0;
   1082     pcm->running = 0;
   1083     return 0;
   1084 }
   1085 
   1086 static inline int pcm_mmap_playback_avail(struct pcm *pcm)
   1087 {
   1088     int avail;
   1089 
   1090     avail = pcm->mmap_status->hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
   1091 
   1092     if (avail < 0)
   1093         avail += pcm->boundary;
   1094     else if (avail > (int)pcm->boundary)
   1095         avail -= pcm->boundary;
   1096 
   1097     return avail;
   1098 }
   1099 
   1100 static inline int pcm_mmap_capture_avail(struct pcm *pcm)
   1101 {
   1102     int avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
   1103     if (avail < 0)
   1104         avail += pcm->boundary;
   1105     return avail;
   1106 }
   1107 
   1108 int pcm_mmap_avail(struct pcm *pcm)
   1109 {
   1110     pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
   1111     if (pcm->flags & PCM_IN)
   1112         return pcm_mmap_capture_avail(pcm);
   1113     else
   1114         return pcm_mmap_playback_avail(pcm);
   1115 }
   1116 
   1117 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
   1118 {
   1119     unsigned int appl_ptr = pcm->mmap_control->appl_ptr;
   1120     appl_ptr += frames;
   1121 
   1122     /* check for boundary wrap */
   1123     if (appl_ptr > pcm->boundary)
   1124          appl_ptr -= pcm->boundary;
   1125     pcm->mmap_control->appl_ptr = appl_ptr;
   1126 }
   1127 
   1128 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
   1129                    unsigned int *frames)
   1130 {
   1131     unsigned int continuous, copy_frames, avail;
   1132 
   1133     /* return the mmap buffer */
   1134     *areas = pcm->mmap_buffer;
   1135 
   1136     /* and the application offset in frames */
   1137     *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
   1138 
   1139     avail = pcm_mmap_avail(pcm);
   1140     if (avail > pcm->buffer_size)
   1141         avail = pcm->buffer_size;
   1142     continuous = pcm->buffer_size - *offset;
   1143 
   1144     /* we can only copy frames if the are availabale and continuos */
   1145     copy_frames = *frames;
   1146     if (copy_frames > avail)
   1147         copy_frames = avail;
   1148     if (copy_frames > continuous)
   1149         copy_frames = continuous;
   1150     *frames = copy_frames;
   1151 
   1152     return 0;
   1153 }
   1154 
   1155 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset __attribute__((unused)), unsigned int frames)
   1156 {
   1157     /* update the application pointer in userspace and kernel */
   1158     pcm_mmap_appl_forward(pcm, frames);
   1159     pcm_sync_ptr(pcm, 0);
   1160 
   1161     return frames;
   1162 }
   1163 
   1164 int pcm_avail_update(struct pcm *pcm)
   1165 {
   1166     pcm_sync_ptr(pcm, 0);
   1167     return pcm_mmap_avail(pcm);
   1168 }
   1169 
   1170 int pcm_state(struct pcm *pcm)
   1171 {
   1172     int err = pcm_sync_ptr(pcm, 0);
   1173     if (err < 0)
   1174         return err;
   1175 
   1176     return pcm->mmap_status->state;
   1177 }
   1178 
   1179 int pcm_set_avail_min(struct pcm *pcm, int avail_min)
   1180 {
   1181     if ((~pcm->flags) & (PCM_MMAP | PCM_NOIRQ))
   1182         return -ENOSYS;
   1183 
   1184     pcm->config.avail_min = avail_min;
   1185     return 0;
   1186 }
   1187 
   1188 int pcm_wait(struct pcm *pcm, int timeout)
   1189 {
   1190     struct pollfd pfd;
   1191     int err;
   1192 
   1193     pfd.fd = pcm->fd;
   1194     pfd.events = POLLOUT | POLLERR | POLLNVAL;
   1195 
   1196     do {
   1197         /* let's wait for avail or timeout */
   1198         err = poll(&pfd, 1, timeout);
   1199         if (err < 0)
   1200             return -errno;
   1201 
   1202         /* timeout ? */
   1203         if (err == 0)
   1204             return 0;
   1205 
   1206         /* have we been interrupted ? */
   1207         if (errno == -EINTR)
   1208             continue;
   1209 
   1210         /* check for any errors */
   1211         if (pfd.revents & (POLLERR | POLLNVAL)) {
   1212             switch (pcm_state(pcm)) {
   1213             case PCM_STATE_XRUN:
   1214                 return -EPIPE;
   1215             case PCM_STATE_SUSPENDED:
   1216                 return -ESTRPIPE;
   1217             case PCM_STATE_DISCONNECTED:
   1218                 return -ENODEV;
   1219             default:
   1220                 return -EIO;
   1221             }
   1222         }
   1223     /* poll again if fd not ready for IO */
   1224     } while (!(pfd.revents & (POLLIN | POLLOUT)));
   1225 
   1226     return 1;
   1227 }
   1228 
   1229 int pcm_get_poll_fd(struct pcm *pcm)
   1230 {
   1231     return pcm->fd;
   1232 }
   1233 
   1234 int pcm_mmap_transfer(struct pcm *pcm, const void *buffer, unsigned int bytes)
   1235 {
   1236     int err = 0, frames, avail;
   1237     unsigned int offset = 0, count;
   1238 
   1239     if (bytes == 0)
   1240         return 0;
   1241 
   1242     count = pcm_bytes_to_frames(pcm, bytes);
   1243 
   1244     while (count > 0) {
   1245 
   1246         /* get the available space for writing new frames */
   1247         avail = pcm_avail_update(pcm);
   1248         if (avail < 0) {
   1249             fprintf(stderr, "cannot determine available mmap frames");
   1250             return err;
   1251         }
   1252 
   1253         /* start the audio if we reach the threshold */
   1254 	    if (!pcm->running &&
   1255             (pcm->buffer_size - avail) >= pcm->config.start_threshold) {
   1256             if (pcm_start(pcm) < 0) {
   1257                fprintf(stderr, "start error: hw 0x%x app 0x%x avail 0x%x\n",
   1258                     (unsigned int)pcm->mmap_status->hw_ptr,
   1259                     (unsigned int)pcm->mmap_control->appl_ptr,
   1260                     avail);
   1261                 return -errno;
   1262             }
   1263             pcm->wait_for_avail_min = 0;
   1264         }
   1265 
   1266         /* sleep until we have space to write new frames */
   1267         if (pcm->running) {
   1268             /* enable waiting for avail_min threshold when less frames than we have to write
   1269              * are available. */
   1270             if (!pcm->wait_for_avail_min && (count > (unsigned int)avail))
   1271                 pcm->wait_for_avail_min = 1;
   1272 
   1273             if (pcm->wait_for_avail_min && (avail < pcm->config.avail_min)) {
   1274                 int time = -1;
   1275 
   1276                 /* disable waiting for avail_min threshold to allow small amounts of data to be
   1277                  * written without waiting as long as there is enough room in buffer. */
   1278                 pcm->wait_for_avail_min = 0;
   1279 
   1280                 if (pcm->flags & PCM_NOIRQ)
   1281                     time = (pcm->config.avail_min - avail) / pcm->noirq_frames_per_msec;
   1282 
   1283                 err = pcm_wait(pcm, time);
   1284                 if (err < 0) {
   1285                     pcm->prepared = 0;
   1286                     pcm->running = 0;
   1287                     oops(pcm, errno, "wait error: hw 0x%x app 0x%x avail 0x%x\n",
   1288                         (unsigned int)pcm->mmap_status->hw_ptr,
   1289                         (unsigned int)pcm->mmap_control->appl_ptr,
   1290                         avail);
   1291                     pcm->mmap_control->appl_ptr = 0;
   1292                     return err;
   1293                 }
   1294                 continue;
   1295             }
   1296         }
   1297 
   1298         frames = count;
   1299         if (frames > avail)
   1300             frames = avail;
   1301 
   1302         if (!frames)
   1303             break;
   1304 
   1305         /* copy frames from buffer */
   1306         frames = pcm_mmap_transfer_areas(pcm, (void *)buffer, offset, frames);
   1307         if (frames < 0) {
   1308             fprintf(stderr, "write error: hw 0x%x app 0x%x avail 0x%x\n",
   1309                     (unsigned int)pcm->mmap_status->hw_ptr,
   1310                     (unsigned int)pcm->mmap_control->appl_ptr,
   1311                     avail);
   1312             return frames;
   1313         }
   1314 
   1315         offset += frames;
   1316         count -= frames;
   1317     }
   1318 
   1319     return 0;
   1320 }
   1321 
   1322 int pcm_mmap_write(struct pcm *pcm, const void *data, unsigned int count)
   1323 {
   1324     if ((~pcm->flags) & (PCM_OUT | PCM_MMAP))
   1325         return -ENOSYS;
   1326 
   1327     return pcm_mmap_transfer(pcm, (void *)data, count);
   1328 }
   1329 
   1330 int pcm_mmap_read(struct pcm *pcm, void *data, unsigned int count)
   1331 {
   1332     if ((~pcm->flags) & (PCM_IN | PCM_MMAP))
   1333         return -ENOSYS;
   1334 
   1335     return pcm_mmap_transfer(pcm, data, count);
   1336 }
   1337 
   1338 int pcm_ioctl(struct pcm *pcm, int request, ...)
   1339 {
   1340     va_list ap;
   1341     void * arg;
   1342 
   1343     if (!pcm_is_ready(pcm))
   1344         return -1;
   1345 
   1346     va_start(ap, request);
   1347     arg = va_arg(ap, void *);
   1348     va_end(ap);
   1349 
   1350     return ioctl(pcm->fd, request, arg);
   1351 }
   1352