]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - android-sdk/platform-external-tinyalsa.git/blob - pcm.c
d841bd9719b251af6fff4e50d07c358c98587b35
[android-sdk/platform-external-tinyalsa.git] / pcm.c
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 */
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>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/time.h>
41 #include <limits.h>
43 #include <linux/ioctl.h>
44 #define __force
45 #define __bitwise
46 #define __user
47 #include <sound/asound.h>
49 #include <tinyalsa/asoundlib.h>
51 #define PARAM_MAX SNDRV_PCM_HW_PARAM_LAST_INTERVAL
52 #define SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP (1<<2)
54 static inline int param_is_mask(int p)
55 {
56     return (p >= SNDRV_PCM_HW_PARAM_FIRST_MASK) &&
57         (p <= SNDRV_PCM_HW_PARAM_LAST_MASK);
58 }
60 static inline int param_is_interval(int p)
61 {
62     return (p >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL) &&
63         (p <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL);
64 }
66 static inline struct snd_interval *param_to_interval(struct snd_pcm_hw_params *p, int n)
67 {
68     return &(p->intervals[n - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]);
69 }
71 static inline struct snd_mask *param_to_mask(struct snd_pcm_hw_params *p, int n)
72 {
73     return &(p->masks[n - SNDRV_PCM_HW_PARAM_FIRST_MASK]);
74 }
76 static void param_set_mask(struct snd_pcm_hw_params *p, int n, unsigned int bit)
77 {
78     if (bit >= SNDRV_MASK_MAX)
79         return;
80     if (param_is_mask(n)) {
81         struct snd_mask *m = param_to_mask(p, n);
82         m->bits[0] = 0;
83         m->bits[1] = 0;
84         m->bits[bit >> 5] |= (1 << (bit & 31));
85     }
86 }
88 static void param_set_min(struct snd_pcm_hw_params *p, int n, unsigned int val)
89 {
90     if (param_is_interval(n)) {
91         struct snd_interval *i = param_to_interval(p, n);
92         i->min = val;
93     }
94 }
96 static void param_set_int(struct snd_pcm_hw_params *p, int n, unsigned int val)
97 {
98     if (param_is_interval(n)) {
99         struct snd_interval *i = param_to_interval(p, n);
100         i->min = val;
101         i->max = val;
102         i->integer = 1;
103     }
106 static unsigned int param_get_int(struct snd_pcm_hw_params *p, int n)
108     if (param_is_interval(n)) {
109         struct snd_interval *i = param_to_interval(p, n);
110         if (i->integer)
111             return i->max;
112     }
113     return 0;
116 static void param_init(struct snd_pcm_hw_params *p)
118     int n;
120     memset(p, 0, sizeof(*p));
121     for (n = SNDRV_PCM_HW_PARAM_FIRST_MASK;
122          n <= SNDRV_PCM_HW_PARAM_LAST_MASK; n++) {
123             struct snd_mask *m = param_to_mask(p, n);
124             m->bits[0] = ~0;
125             m->bits[1] = ~0;
126     }
127     for (n = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
128          n <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; n++) {
129             struct snd_interval *i = param_to_interval(p, n);
130             i->min = 0;
131             i->max = ~0;
132     }
135 #define PCM_ERROR_MAX 128
137 struct pcm {
138     int fd;
139     unsigned int flags;
140     int running:1;
141     int underruns;
142     unsigned int buffer_size;
143     unsigned int boundary;
144     char error[PCM_ERROR_MAX];
145     struct pcm_config config;
146     struct snd_pcm_mmap_status *mmap_status;
147     struct snd_pcm_mmap_control *mmap_control;
148     struct snd_pcm_sync_ptr *sync_ptr;
149     void *mmap_buffer;
150     unsigned int noirq_frames_per_msec;
151     int wait_for_avail_min;
152 };
154 unsigned int pcm_get_buffer_size(struct pcm *pcm)
156     return pcm->buffer_size;
159 const char* pcm_get_error(struct pcm *pcm)
161     return pcm->error;
164 static int oops(struct pcm *pcm, int e, const char *fmt, ...)
166     va_list ap;
167     int sz;
169     va_start(ap, fmt);
170     vsnprintf(pcm->error, PCM_ERROR_MAX, fmt, ap);
171     va_end(ap);
172     sz = strlen(pcm->error);
174     if (errno)
175         snprintf(pcm->error + sz, PCM_ERROR_MAX - sz,
176                  ": %s", strerror(e));
177     return -1;
180 static unsigned int pcm_format_to_alsa(enum pcm_format format)
182     switch (format) {
183     case PCM_FORMAT_S32_LE:
184         return SNDRV_PCM_FORMAT_S32_LE;
185     case PCM_FORMAT_S8:
186         return SNDRV_PCM_FORMAT_S8;
187     case PCM_FORMAT_S24_LE:
188         return SNDRV_PCM_FORMAT_S24_LE;
189     default:
190     case PCM_FORMAT_S16_LE:
191         return SNDRV_PCM_FORMAT_S16_LE;
192     };
195 static unsigned int pcm_format_to_bits(enum pcm_format format)
197     switch (format) {
198     case PCM_FORMAT_S32_LE:
199         return 32;
200     default:
201     case PCM_FORMAT_S16_LE:
202         return 16;
203     };
206 unsigned int pcm_bytes_to_frames(struct pcm *pcm, unsigned int bytes)
208     return bytes / (pcm->config.channels *
209         (pcm_format_to_bits(pcm->config.format) >> 3));
212 unsigned int pcm_frames_to_bytes(struct pcm *pcm, unsigned int frames)
214     return frames * pcm->config.channels *
215         (pcm_format_to_bits(pcm->config.format) >> 3);
218 static int pcm_sync_ptr(struct pcm *pcm, int flags) {
219     if (pcm->sync_ptr) {
220         pcm->sync_ptr->flags = flags;
221         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SYNC_PTR, pcm->sync_ptr) < 0)
222             return -1;
223     }
224     return 0;
227 static int pcm_hw_mmap_status(struct pcm *pcm) {
229     if (pcm->sync_ptr)
230         return 0;
232     int page_size = sysconf(_SC_PAGE_SIZE);
233     pcm->mmap_status = mmap(NULL, page_size, PROT_READ, MAP_FILE | MAP_SHARED,
234                             pcm->fd, SNDRV_PCM_MMAP_OFFSET_STATUS);
235     if (pcm->mmap_status == MAP_FAILED)
236         pcm->mmap_status = NULL;
237     if (!pcm->mmap_status)
238         goto mmap_error;
240     pcm->mmap_control = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
241                              MAP_FILE | MAP_SHARED, pcm->fd, SNDRV_PCM_MMAP_OFFSET_CONTROL);
242     if (pcm->mmap_control == MAP_FAILED)
243         pcm->mmap_control = NULL;
244     if (!pcm->mmap_control) {
245         munmap(pcm->mmap_status, page_size);
246         pcm->mmap_status = NULL;
247         goto mmap_error;
248     }
249     if (pcm->flags & PCM_MMAP)
250         pcm->mmap_control->avail_min = pcm->config.avail_min;
251     else
252         pcm->mmap_control->avail_min = 1;
254     return 0;
256 mmap_error:
258     pcm->sync_ptr = calloc(1, sizeof(*pcm->sync_ptr));
259     if (!pcm->sync_ptr)
260         return -ENOMEM;
261     pcm->mmap_status = &pcm->sync_ptr->s.status;
262     pcm->mmap_control = &pcm->sync_ptr->c.control;
263     if (pcm->flags & PCM_MMAP)
264         pcm->mmap_control->avail_min = pcm->config.avail_min;
265     else
266         pcm->mmap_control->avail_min = 1;
268     pcm_sync_ptr(pcm, 0);
270     return 0;
273 static void pcm_hw_munmap_status(struct pcm *pcm) {
274     if (pcm->sync_ptr) {
275         free(pcm->sync_ptr);
276         pcm->sync_ptr = NULL;
277     } else {
278         int page_size = sysconf(_SC_PAGE_SIZE);
279         if (pcm->mmap_status)
280             munmap(pcm->mmap_status, page_size);
281         if (pcm->mmap_control)
282             munmap(pcm->mmap_control, page_size);
283     }
284     pcm->mmap_status = NULL;
285     pcm->mmap_control = NULL;
288 static int pcm_areas_copy(struct pcm *pcm, unsigned int pcm_offset,
289                           const char *src, unsigned int src_offset,
290                           unsigned int frames)
292     int size_bytes = pcm_frames_to_bytes(pcm, frames);
293     int pcm_offset_bytes = pcm_frames_to_bytes(pcm, pcm_offset);
294     int src_offset_bytes = pcm_frames_to_bytes(pcm, src_offset);
296     /* interleaved only atm */
297     memcpy((char*)pcm->mmap_buffer + pcm_offset_bytes,
298            src + src_offset_bytes, size_bytes);
299     return 0;
302 static int pcm_mmap_write_areas(struct pcm *pcm, const char *src,
303                                 unsigned int offset, unsigned int size)
305     void *pcm_areas;
306     int commit;
307     unsigned int pcm_offset, frames, count = 0;
309     while (size > 0) {
310         frames = size;
311         pcm_mmap_begin(pcm, &pcm_areas, &pcm_offset, &frames);
312         pcm_areas_copy(pcm, pcm_offset, src, offset, frames);
313         commit = pcm_mmap_commit(pcm, pcm_offset, frames);
314         if (commit < 0) {
315             oops(pcm, commit, "failed to commit %d frames\n", frames);
316             return commit;
317         }
319         offset += commit;
320         count += commit;
321         size -= commit;
322     }
323     return count;
326 int pcm_get_htimestamp(struct pcm *pcm, unsigned int *avail,
327                        struct timespec *tstamp)
329     int frames;
330     int rc;
331     snd_pcm_uframes_t hw_ptr;
333     if (!pcm_is_ready(pcm))
334         return -1;
336     rc = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_HWSYNC);
337     if (rc < 0)
338         return -1;
340     if ((pcm->mmap_status->state != PCM_STATE_RUNNING) &&
341             (pcm->mmap_status->state != PCM_STATE_DRAINING))
342         return -1;
344     *tstamp = pcm->mmap_status->tstamp;
345     if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
346         return -1;
348     hw_ptr = pcm->mmap_status->hw_ptr;
349     if (pcm->flags & PCM_IN)
350         frames = hw_ptr - pcm->mmap_control->appl_ptr;
351     else
352         frames = hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
354     if (frames < 0)
355         frames += pcm->boundary;
356     else if (frames > (int)pcm->boundary)
357         frames -= pcm->boundary;
359     *avail = (unsigned int)frames;
361     return 0;
364 int pcm_write(struct pcm *pcm, const void *data, unsigned int count)
366     struct snd_xferi x;
368     if (pcm->flags & PCM_IN)
369         return -EINVAL;
371     x.buf = (void*)data;
372     x.frames = count / (pcm->config.channels *
373                         pcm_format_to_bits(pcm->config.format) / 8);
375     for (;;) {
376         if (!pcm->running) {
377             if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE))
378                 return oops(pcm, errno, "cannot prepare channel");
379             if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x))
380                 return oops(pcm, errno, "cannot write initial data");
381             pcm->running = 1;
382             return 0;
383         }
384         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x)) {
385             pcm->running = 0;
386             if (errno == EPIPE) {
387                 /* we failed to make our window -- try to restart if we are
388                  * allowed to do so.  Otherwise, simply allow the EPIPE error to
389                  * propagate up to the app level */
390                 pcm->underruns++;
391                 if (pcm->flags & PCM_NORESTART)
392                     return -EPIPE;
393                 continue;
394             }
395             return oops(pcm, errno, "cannot write stream data");
396         }
397         return 0;
398     }
401 int pcm_read(struct pcm *pcm, void *data, unsigned int count)
403     struct snd_xferi x;
405     if (!(pcm->flags & PCM_IN))
406         return -EINVAL;
408     x.buf = data;
409     x.frames = count / (pcm->config.channels *
410                         pcm_format_to_bits(pcm->config.format) / 8);
412     for (;;) {
413         if (!pcm->running) {
414             if (pcm_start(pcm) < 0) {
415                 fprintf(stderr, "start error");
416                 return -errno;
417             }
418         }
419         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_READI_FRAMES, &x)) {
420             pcm->running = 0;
421             if (errno == EPIPE) {
422                     /* we failed to make our window -- try to restart */
423                 pcm->underruns++;
424                 continue;
425             }
426             return oops(pcm, errno, "cannot read stream data");
427         }
428         return 0;
429     }
432 static struct pcm bad_pcm = {
433     .fd = -1,
434 };
436 int pcm_close(struct pcm *pcm)
438     if (pcm == &bad_pcm)
439         return 0;
441     pcm_hw_munmap_status(pcm);
443     if (pcm->flags & PCM_MMAP) {
444         pcm_stop(pcm);
445         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
446     }
448     if (pcm->fd >= 0)
449         close(pcm->fd);
450     pcm->running = 0;
451     pcm->buffer_size = 0;
452     pcm->fd = -1;
453     free(pcm);
454     return 0;
457 struct pcm *pcm_open(unsigned int card, unsigned int device,
458                      unsigned int flags, struct pcm_config *config)
460     struct pcm *pcm;
461     struct snd_pcm_info info;
462     struct snd_pcm_hw_params params;
463     struct snd_pcm_sw_params sparams;
464     char fn[256];
465     int rc;
467     pcm = calloc(1, sizeof(struct pcm));
468     if (!pcm || !config)
469         return &bad_pcm; /* TODO: could support default config here */
471     pcm->config = *config;
473     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
474              flags & PCM_IN ? 'c' : 'p');
476     pcm->flags = flags;
477     pcm->fd = open(fn, O_RDWR);
478     if (pcm->fd < 0) {
479         oops(pcm, errno, "cannot open device '%s'", fn);
480         return pcm;
481     }
483     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_INFO, &info)) {
484         oops(pcm, errno, "cannot get info");
485         goto fail_close;
486     }
488     param_init(&params);
489     param_set_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT,
490                    pcm_format_to_alsa(config->format));
491     param_set_mask(&params, SNDRV_PCM_HW_PARAM_SUBFORMAT,
492                    SNDRV_PCM_SUBFORMAT_STD);
493     param_set_min(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, config->period_size);
494     param_set_int(&params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
495                   pcm_format_to_bits(config->format));
496     param_set_int(&params, SNDRV_PCM_HW_PARAM_FRAME_BITS,
497                   pcm_format_to_bits(config->format) * config->channels);
498     param_set_int(&params, SNDRV_PCM_HW_PARAM_CHANNELS,
499                   config->channels);
500     param_set_int(&params, SNDRV_PCM_HW_PARAM_PERIODS, config->period_count);
501     param_set_int(&params, SNDRV_PCM_HW_PARAM_RATE, config->rate);
503     if (flags & PCM_NOIRQ) {
505         if (!(flags & PCM_MMAP)) {
506             oops(pcm, -EINVAL, "noirq only currently supported with mmap().");
507             goto fail;
508         }
510         params.flags |= SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP;
511         pcm->noirq_frames_per_msec = config->rate / 1000;
512     }
514     if (flags & PCM_MMAP)
515         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
516                    SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
517     else
518         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
519                    SNDRV_PCM_ACCESS_RW_INTERLEAVED);
521     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_HW_PARAMS, &params)) {
522         oops(pcm, errno, "cannot set hw params");
523         goto fail_close;
524     }
526     /* get our refined hw_params */
527     config->period_size = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
528     config->period_count = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIODS);
529     pcm->buffer_size = config->period_count * config->period_size;
531     if (flags & PCM_MMAP) {
532         pcm->mmap_buffer = mmap(NULL, pcm_frames_to_bytes(pcm, pcm->buffer_size),
533                                 PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, pcm->fd, 0);
534         if (pcm->mmap_buffer == MAP_FAILED) {
535             oops(pcm, -errno, "failed to mmap buffer %d bytes\n",
536                  pcm_frames_to_bytes(pcm, pcm->buffer_size));
537             goto fail_close;
538         }
539     }
542     memset(&sparams, 0, sizeof(sparams));
543     sparams.tstamp_mode = SNDRV_PCM_TSTAMP_ENABLE;
544     sparams.period_step = 1;
546     if (!config->start_threshold) {
547         if (pcm->flags & PCM_IN)
548             pcm->config.start_threshold = sparams.start_threshold = 1;
549         else
550             pcm->config.start_threshold = sparams.start_threshold =
551                 config->period_count * config->period_size / 2;
552     } else
553         sparams.start_threshold = config->start_threshold;
555     /* pick a high stop threshold - todo: does this need further tuning */
556     if (!config->stop_threshold) {
557         if (pcm->flags & PCM_IN)
558             pcm->config.stop_threshold = sparams.stop_threshold =
559                 config->period_count * config->period_size * 10;
560         else
561             pcm->config.stop_threshold = sparams.stop_threshold =
562                 config->period_count * config->period_size;
563     }
564     else
565         sparams.stop_threshold = config->stop_threshold;
567     if (!pcm->config.avail_min) {
568         if (pcm->flags & PCM_MMAP)
569             pcm->config.avail_min = sparams.avail_min = pcm->config.period_size;
570         else
571             pcm->config.avail_min = sparams.avail_min = 1;
572     } else
573         sparams.avail_min = config->avail_min;
575     sparams.xfer_align = config->period_size / 2; /* needed for old kernels */
576     sparams.silence_size = 0;
577     sparams.silence_threshold = config->silence_threshold;
578     pcm->boundary = sparams.boundary = pcm->buffer_size;
580     while (pcm->boundary * 2 <= INT_MAX - pcm->buffer_size)
581                 pcm->boundary *= 2;
583     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
584         oops(pcm, errno, "cannot set sw params");
585         goto fail;
586     }
588     rc = pcm_hw_mmap_status(pcm);
589     if (rc < 0) {
590         oops(pcm, rc, "mmap status failed");
591         goto fail;
592     }
594     pcm->underruns = 0;
595     return pcm;
597 fail:
598     if (flags & PCM_MMAP)
599         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
600 fail_close:
601     close(pcm->fd);
602     pcm->fd = -1;
603     return pcm;
606 int pcm_is_ready(struct pcm *pcm)
608     return pcm->fd >= 0;
611 int pcm_start(struct pcm *pcm)
613     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE) < 0)
614         return oops(pcm, errno, "cannot prepare channel");
616     if (pcm->flags & PCM_MMAP)
617             pcm_sync_ptr(pcm, 0);
619     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_START) < 0)
620         return oops(pcm, errno, "cannot start channel");
622     pcm->running = 1;
623     return 0;
626 int pcm_stop(struct pcm *pcm)
628     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DROP) < 0)
629         return oops(pcm, errno, "cannot stop channel");
631     pcm->running = 0;
632     return 0;
635 static inline int pcm_mmap_playback_avail(struct pcm *pcm)
637     int avail;
639     avail = pcm->mmap_status->hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
641     if (avail < 0)
642         avail += pcm->boundary;
643     else if (avail > (int)pcm->boundary)
644         avail -= pcm->boundary;
646     return avail;
649 static inline int pcm_mmap_capture_avail(struct pcm *pcm)
651     int avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
652     if (avail < 0)
653         avail += pcm->boundary;
654     return avail;
657 static inline int pcm_mmap_avail(struct pcm *pcm)
659     pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
660     if (pcm->flags & PCM_IN)
661         return pcm_mmap_capture_avail(pcm);
662     else
663         return pcm_mmap_playback_avail(pcm);
666 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
668     unsigned int appl_ptr = pcm->mmap_control->appl_ptr;
669     appl_ptr += frames;
671     /* check for boundary wrap */
672     if (appl_ptr > pcm->boundary)
673          appl_ptr -= pcm->boundary;
674     pcm->mmap_control->appl_ptr = appl_ptr;
677 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
678                    unsigned int *frames)
680     unsigned int continuous, copy_frames, avail;
682     /* return the mmap buffer */
683     *areas = pcm->mmap_buffer;
685     /* and the application offset in frames */
686     *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
688     avail = pcm_mmap_avail(pcm);
689     if (avail > pcm->buffer_size)
690         avail = pcm->buffer_size;
691     continuous = pcm->buffer_size - *offset;
693     /* we can only copy frames if the are availabale and continuos */
694     copy_frames = *frames;
695     if (copy_frames > avail)
696         copy_frames = avail;
697     if (copy_frames > continuous)
698         copy_frames = continuous;
699     *frames = copy_frames;
701     return 0;
704 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset, unsigned int frames)
706     /* update the application pointer in userspace and kernel */
707     pcm_mmap_appl_forward(pcm, frames);
708     pcm_sync_ptr(pcm, 0);
710     return frames;
713 int pcm_avail_update(struct pcm *pcm)
715     pcm_sync_ptr(pcm, 0);
716     return pcm_mmap_avail(pcm);
719 int pcm_state(struct pcm *pcm)
721     int err = pcm_sync_ptr(pcm, 0);
722     if (err < 0)
723         return err;
725     return pcm->mmap_status->state;
728 int pcm_set_avail_min(struct pcm *pcm, int avail_min)
730     if ((~pcm->flags) & (PCM_MMAP | PCM_NOIRQ))
731         return -ENOSYS;
733     pcm->config.avail_min = avail_min;
734     return 0;
737 int pcm_wait(struct pcm *pcm, int timeout)
739     struct pollfd pfd;
740     int err;
742     pfd.fd = pcm->fd;
743     pfd.events = POLLOUT | POLLERR | POLLNVAL;
745     do {
746         /* let's wait for avail or timeout */
747         err = poll(&pfd, 1, timeout);
748         if (err < 0)
749             return -errno;
751         /* timeout ? */
752         if (err == 0)
753             return 0;
755         /* have we been interrupted ? */
756         if (errno == -EINTR)
757             continue;
759         /* check for any errors */
760         if (pfd.revents & (POLLERR | POLLNVAL)) {
761             switch (pcm_state(pcm)) {
762             case PCM_STATE_XRUN:
763                 return -EPIPE;
764             case PCM_STATE_SUSPENDED:
765                 return -ESTRPIPE;
766             case PCM_STATE_DISCONNECTED:
767                 return -ENODEV;
768             default:
769                 return -EIO;
770             }
771         }
772     /* poll again if fd not ready for IO */
773     } while (!(pfd.revents & (POLLIN | POLLOUT)));
775     return 1;
778 int pcm_mmap_write(struct pcm *pcm, const void *buffer, unsigned int bytes)
780     int err = 0, frames, avail;
781     unsigned int offset = 0, count;
783     if (bytes == 0)
784         return 0;
786     count = pcm_bytes_to_frames(pcm, bytes);
788     while (count > 0) {
790         /* get the available space for writing new frames */
791         avail = pcm_avail_update(pcm);
792         if (avail < 0) {
793             fprintf(stderr, "cannot determine available mmap frames");
794             return err;
795         }
797         /* start the audio if we reach the threshold */
798             if (!pcm->running &&
799             (pcm->buffer_size - avail) >= pcm->config.start_threshold) {
800             if (pcm_start(pcm) < 0) {
801                fprintf(stderr, "start error: hw 0x%x app 0x%x avail 0x%x\n",
802                     (unsigned int)pcm->mmap_status->hw_ptr,
803                     (unsigned int)pcm->mmap_control->appl_ptr,
804                     avail);
805                 return -errno;
806             }
807             pcm->wait_for_avail_min = 0;
808         }
810         /* sleep until we have space to write new frames */
811         if (pcm->running) {
812             /* enable waiting for avail_min threshold when less frames than we have to write
813              * are available. */
814             if (!pcm->wait_for_avail_min && (count > (unsigned int)avail))
815                 pcm->wait_for_avail_min = 1;
817             if (pcm->wait_for_avail_min && (avail < pcm->config.avail_min)) {
818                 int time = -1;
820                 /* disable waiting for avail_min threshold to allow small amounts of data to be
821                  * written without waiting as long as there is enough room in buffer. */
822                 pcm->wait_for_avail_min = 0;
824                 if (pcm->flags & PCM_NOIRQ)
825                     time = (pcm->config.avail_min - avail) / pcm->noirq_frames_per_msec;
827                 err = pcm_wait(pcm, time);
828                 if (err < 0) {
829                     pcm->running = 0;
830                     oops(pcm, err, "wait error: hw 0x%x app 0x%x avail 0x%x\n",
831                         (unsigned int)pcm->mmap_status->hw_ptr,
832                         (unsigned int)pcm->mmap_control->appl_ptr,
833                         avail);
834                     pcm->mmap_control->appl_ptr = 0;
835                     return err;
836                 }
837                 continue;
838             }
839         }
841         frames = count;
842         if (frames > avail)
843             frames = avail;
845         if (!frames)
846             break;
848         /* copy frames from buffer */
849         frames = pcm_mmap_write_areas(pcm, buffer, offset, frames);
850         if (frames < 0) {
851             fprintf(stderr, "write error: hw 0x%x app 0x%x avail 0x%x\n",
852                     (unsigned int)pcm->mmap_status->hw_ptr,
853                     (unsigned int)pcm->mmap_control->appl_ptr,
854                     avail);
855             return frames;
856         }
858         offset += frames;
859         count -= frames;
860     }
862     return 0;