• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
param_is_mask(int p)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 
param_is_interval(int p)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 
param_to_interval(struct snd_pcm_hw_params * p,int n)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 
param_to_mask(struct snd_pcm_hw_params * p,int n)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 
param_set_mask(struct snd_pcm_hw_params * p,int n,unsigned int bit)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 
param_set_min(struct snd_pcm_hw_params * p,int n,unsigned int val)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 
param_get_min(struct snd_pcm_hw_params * p,int n)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 
param_set_max(struct snd_pcm_hw_params * p,int n,unsigned int val)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 
param_get_max(struct snd_pcm_hw_params * p,int n)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 
param_set_int(struct snd_pcm_hw_params * p,int n,unsigned int val)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 
param_get_int(struct snd_pcm_hw_params * p,int n)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 
param_init(struct snd_pcm_hw_params * p)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 
pcm_get_buffer_size(struct pcm * pcm)262 unsigned int pcm_get_buffer_size(struct pcm *pcm)
263 {
264     return pcm->buffer_size;
265 }
266 
pcm_get_error(struct pcm * pcm)267 const char* pcm_get_error(struct pcm *pcm)
268 {
269     return pcm->error;
270 }
271 
pcm_get_subdevice(struct pcm * pcm)272 unsigned int pcm_get_subdevice(struct pcm *pcm)
273 {
274     return pcm->subdevice;
275 }
276 
oops(struct pcm * pcm,int e,const char * fmt,...)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 
pcm_format_to_alsa(enum pcm_format format)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 
pcm_format_to_bits(enum pcm_format format)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 
pcm_bytes_to_frames(struct pcm * pcm,unsigned int bytes)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 
pcm_frames_to_bytes(struct pcm * pcm,unsigned int frames)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 
pcm_sync_ptr(struct pcm * pcm,int flags)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 
pcm_hw_mmap_status(struct pcm * pcm)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 
pcm_hw_munmap_status(struct pcm * pcm)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 
pcm_areas_copy(struct pcm * pcm,unsigned int pcm_offset,char * buf,unsigned int src_offset,unsigned int frames)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 
pcm_mmap_transfer_areas(struct pcm * pcm,char * buf,unsigned int offset,unsigned int size)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 
pcm_get_htimestamp(struct pcm * pcm,unsigned int * avail,struct timespec * tstamp)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 
pcm_mmap_get_hw_ptr(struct pcm * pcm,unsigned int * hw_ptr,struct timespec * tstamp)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 
pcm_write(struct pcm * pcm,const void * data,unsigned int count)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 
pcm_read(struct pcm * pcm,void * data,unsigned int count)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 
pcm_params_get(unsigned int card,unsigned int device,unsigned int flags)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 
pcm_params_free(struct pcm_params * pcm_params)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 
pcm_param_to_alsa(enum pcm_param param)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 
pcm_params_get_mask(struct pcm_params * pcm_params,enum pcm_param param)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 
pcm_params_get_min(struct pcm_params * pcm_params,enum pcm_param param)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 
pcm_params_set_min(struct pcm_params * pcm_params,enum pcm_param param,unsigned int val)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 
pcm_params_get_max(struct pcm_params * pcm_params,enum pcm_param param)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 
pcm_params_set_max(struct pcm_params * pcm_params,enum pcm_param param,unsigned int val)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 
pcm_mask_test(struct pcm_mask * m,unsigned int index)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 
pcm_mask_to_string(struct pcm_mask * m,char * string,unsigned int size,char * mask_name,const char * const * bit_array_name,size_t bit_array_size)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 
pcm_params_to_string(struct pcm_params * params,char * string,unsigned int size)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 
pcm_params_format_test(struct pcm_params * params,enum pcm_format format)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 
pcm_close(struct pcm * pcm)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 
pcm_open(unsigned int card,unsigned int device,unsigned int flags,struct pcm_config * config)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     pcm = calloc(1, sizeof(struct pcm));
886     if (!pcm || !config)
887         return &bad_pcm; /* TODO: could support default config here */
888 
889     pcm->config = *config;
890 
891     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
892              flags & PCM_IN ? 'c' : 'p');
893 
894     pcm->flags = flags;
895     pcm->fd = open(fn, O_RDWR|O_NONBLOCK);
896     if (pcm->fd < 0) {
897         oops(pcm, errno, "cannot open device '%s'", fn);
898         return pcm;
899     }
900 
901     if (fcntl(pcm->fd, F_SETFL, fcntl(pcm->fd, F_GETFL) &
902               ~O_NONBLOCK) < 0) {
903         oops(pcm, errno, "failed to reset blocking mode '%s'", fn);
904         goto fail_close;
905     }
906 
907     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_INFO, &info)) {
908         oops(pcm, errno, "cannot get info");
909         goto fail_close;
910     }
911     pcm->subdevice = info.subdevice;
912 
913     param_init(&params);
914     param_set_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT,
915                    pcm_format_to_alsa(config->format));
916     param_set_mask(&params, SNDRV_PCM_HW_PARAM_SUBFORMAT,
917                    SNDRV_PCM_SUBFORMAT_STD);
918     param_set_min(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, config->period_size);
919     param_set_int(&params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
920                   pcm_format_to_bits(config->format));
921     param_set_int(&params, SNDRV_PCM_HW_PARAM_FRAME_BITS,
922                   pcm_format_to_bits(config->format) * config->channels);
923     param_set_int(&params, SNDRV_PCM_HW_PARAM_CHANNELS,
924                   config->channels);
925     param_set_int(&params, SNDRV_PCM_HW_PARAM_PERIODS, config->period_count);
926     param_set_int(&params, SNDRV_PCM_HW_PARAM_RATE, config->rate);
927 
928     if (flags & PCM_NOIRQ) {
929         if (!(flags & PCM_MMAP)) {
930             oops(pcm, EINVAL, "noirq only currently supported with mmap().");
931             goto fail_close;
932         }
933 
934         params.flags |= SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP;
935         pcm->noirq_frames_per_msec = config->rate / 1000;
936     }
937 
938     if (flags & PCM_MMAP)
939         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
940                        SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
941     else
942         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
943                        SNDRV_PCM_ACCESS_RW_INTERLEAVED);
944 
945     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_HW_PARAMS, &params)) {
946         oops(pcm, errno, "cannot set hw params");
947         goto fail_close;
948     }
949 
950     /* get our refined hw_params */
951     config->period_size = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
952     config->period_count = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIODS);
953     pcm->buffer_size = config->period_count * config->period_size;
954 
955     if (flags & PCM_MMAP) {
956         pcm->mmap_buffer = mmap(NULL, pcm_frames_to_bytes(pcm, pcm->buffer_size),
957                                 PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, pcm->fd, 0);
958         if (pcm->mmap_buffer == MAP_FAILED) {
959             oops(pcm, errno, "failed to mmap buffer %d bytes\n",
960                  pcm_frames_to_bytes(pcm, pcm->buffer_size));
961             goto fail_close;
962         }
963     }
964 
965     memset(&sparams, 0, sizeof(sparams));
966     sparams.tstamp_mode = SNDRV_PCM_TSTAMP_ENABLE;
967     sparams.period_step = 1;
968 
969     if (!config->start_threshold) {
970         if (pcm->flags & PCM_IN)
971             pcm->config.start_threshold = sparams.start_threshold = 1;
972         else
973             pcm->config.start_threshold = sparams.start_threshold =
974                 config->period_count * config->period_size / 2;
975     } else
976         sparams.start_threshold = config->start_threshold;
977 
978     /* pick a high stop threshold - todo: does this need further tuning */
979     if (!config->stop_threshold) {
980         if (pcm->flags & PCM_IN)
981             pcm->config.stop_threshold = sparams.stop_threshold =
982                 config->period_count * config->period_size * 10;
983         else
984             pcm->config.stop_threshold = sparams.stop_threshold =
985                 config->period_count * config->period_size;
986     }
987     else
988         sparams.stop_threshold = config->stop_threshold;
989 
990     if (!pcm->config.avail_min) {
991         if (pcm->flags & PCM_MMAP)
992             pcm->config.avail_min = sparams.avail_min = pcm->config.period_size;
993         else
994             pcm->config.avail_min = sparams.avail_min = 1;
995     } else
996         sparams.avail_min = config->avail_min;
997 
998     sparams.xfer_align = config->period_size / 2; /* needed for old kernels */
999     sparams.silence_threshold = config->silence_threshold;
1000     sparams.silence_size = config->silence_size;
1001     pcm->boundary = sparams.boundary = pcm->buffer_size;
1002 
1003     while (pcm->boundary * 2 <= INT_MAX - pcm->buffer_size)
1004         pcm->boundary *= 2;
1005 
1006     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
1007         oops(pcm, errno, "cannot set sw params");
1008         goto fail;
1009     }
1010 
1011     rc = pcm_hw_mmap_status(pcm);
1012     if (rc < 0) {
1013         oops(pcm, errno, "mmap status failed");
1014         goto fail;
1015     }
1016 
1017 #ifdef SNDRV_PCM_IOCTL_TTSTAMP
1018     if (pcm->flags & PCM_MONOTONIC) {
1019         int arg = SNDRV_PCM_TSTAMP_TYPE_MONOTONIC;
1020         rc = ioctl(pcm->fd, SNDRV_PCM_IOCTL_TTSTAMP, &arg);
1021         if (rc < 0) {
1022             oops(pcm, errno, "cannot set timestamp type");
1023             goto fail;
1024         }
1025     }
1026 #endif
1027 
1028     pcm->underruns = 0;
1029     return pcm;
1030 
1031 fail:
1032     if (flags & PCM_MMAP)
1033         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
1034 fail_close:
1035     close(pcm->fd);
1036     pcm->fd = -1;
1037     return pcm;
1038 }
1039 
pcm_is_ready(struct pcm * pcm)1040 int pcm_is_ready(struct pcm *pcm)
1041 {
1042     return pcm->fd >= 0;
1043 }
1044 
pcm_prepare(struct pcm * pcm)1045 int pcm_prepare(struct pcm *pcm)
1046 {
1047     if (pcm->prepared)
1048         return 0;
1049 
1050     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE) < 0)
1051         return oops(pcm, errno, "cannot prepare channel");
1052 
1053     pcm->prepared = 1;
1054     return 0;
1055 }
1056 
pcm_start(struct pcm * pcm)1057 int pcm_start(struct pcm *pcm)
1058 {
1059     int prepare_error = pcm_prepare(pcm);
1060     if (prepare_error)
1061         return prepare_error;
1062 
1063     if (pcm->flags & PCM_MMAP)
1064 	    pcm_sync_ptr(pcm, 0);
1065 
1066     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_START) < 0)
1067         return oops(pcm, errno, "cannot start channel");
1068 
1069     pcm->running = 1;
1070     return 0;
1071 }
1072 
pcm_stop(struct pcm * pcm)1073 int pcm_stop(struct pcm *pcm)
1074 {
1075     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DROP) < 0)
1076         return oops(pcm, errno, "cannot stop channel");
1077 
1078     pcm->prepared = 0;
1079     pcm->running = 0;
1080     return 0;
1081 }
1082 
pcm_mmap_playback_avail(struct pcm * pcm)1083 static inline int pcm_mmap_playback_avail(struct pcm *pcm)
1084 {
1085     int avail;
1086 
1087     avail = pcm->mmap_status->hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
1088 
1089     if (avail < 0)
1090         avail += pcm->boundary;
1091     else if (avail > (int)pcm->boundary)
1092         avail -= pcm->boundary;
1093 
1094     return avail;
1095 }
1096 
pcm_mmap_capture_avail(struct pcm * pcm)1097 static inline int pcm_mmap_capture_avail(struct pcm *pcm)
1098 {
1099     int avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
1100     if (avail < 0)
1101         avail += pcm->boundary;
1102     return avail;
1103 }
1104 
pcm_mmap_avail(struct pcm * pcm)1105 int pcm_mmap_avail(struct pcm *pcm)
1106 {
1107     pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
1108     if (pcm->flags & PCM_IN)
1109         return pcm_mmap_capture_avail(pcm);
1110     else
1111         return pcm_mmap_playback_avail(pcm);
1112 }
1113 
pcm_mmap_appl_forward(struct pcm * pcm,int frames)1114 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
1115 {
1116     unsigned int appl_ptr = pcm->mmap_control->appl_ptr;
1117     appl_ptr += frames;
1118 
1119     /* check for boundary wrap */
1120     if (appl_ptr > pcm->boundary)
1121          appl_ptr -= pcm->boundary;
1122     pcm->mmap_control->appl_ptr = appl_ptr;
1123 }
1124 
pcm_mmap_begin(struct pcm * pcm,void ** areas,unsigned int * offset,unsigned int * frames)1125 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
1126                    unsigned int *frames)
1127 {
1128     unsigned int continuous, copy_frames, avail;
1129 
1130     /* return the mmap buffer */
1131     *areas = pcm->mmap_buffer;
1132 
1133     /* and the application offset in frames */
1134     *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
1135 
1136     avail = pcm_mmap_avail(pcm);
1137     if (avail > pcm->buffer_size)
1138         avail = pcm->buffer_size;
1139     continuous = pcm->buffer_size - *offset;
1140 
1141     /* we can only copy frames if the are availabale and continuos */
1142     copy_frames = *frames;
1143     if (copy_frames > avail)
1144         copy_frames = avail;
1145     if (copy_frames > continuous)
1146         copy_frames = continuous;
1147     *frames = copy_frames;
1148 
1149     return 0;
1150 }
1151 
pcm_mmap_commit(struct pcm * pcm,unsigned int offset,unsigned int frames)1152 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset __attribute__((unused)), unsigned int frames)
1153 {
1154     /* update the application pointer in userspace and kernel */
1155     pcm_mmap_appl_forward(pcm, frames);
1156     pcm_sync_ptr(pcm, 0);
1157 
1158     return frames;
1159 }
1160 
pcm_avail_update(struct pcm * pcm)1161 int pcm_avail_update(struct pcm *pcm)
1162 {
1163     pcm_sync_ptr(pcm, 0);
1164     return pcm_mmap_avail(pcm);
1165 }
1166 
pcm_state(struct pcm * pcm)1167 int pcm_state(struct pcm *pcm)
1168 {
1169     int err = pcm_sync_ptr(pcm, 0);
1170     if (err < 0)
1171         return err;
1172 
1173     return pcm->mmap_status->state;
1174 }
1175 
pcm_set_avail_min(struct pcm * pcm,int avail_min)1176 int pcm_set_avail_min(struct pcm *pcm, int avail_min)
1177 {
1178     if ((~pcm->flags) & (PCM_MMAP | PCM_NOIRQ))
1179         return -ENOSYS;
1180 
1181     pcm->config.avail_min = avail_min;
1182     return 0;
1183 }
1184 
pcm_wait(struct pcm * pcm,int timeout)1185 int pcm_wait(struct pcm *pcm, int timeout)
1186 {
1187     struct pollfd pfd;
1188     int err;
1189 
1190     pfd.fd = pcm->fd;
1191     pfd.events = POLLOUT | POLLERR | POLLNVAL;
1192 
1193     do {
1194         /* let's wait for avail or timeout */
1195         err = poll(&pfd, 1, timeout);
1196         if (err < 0)
1197             return -errno;
1198 
1199         /* timeout ? */
1200         if (err == 0)
1201             return 0;
1202 
1203         /* have we been interrupted ? */
1204         if (errno == -EINTR)
1205             continue;
1206 
1207         /* check for any errors */
1208         if (pfd.revents & (POLLERR | POLLNVAL)) {
1209             switch (pcm_state(pcm)) {
1210             case PCM_STATE_XRUN:
1211                 return -EPIPE;
1212             case PCM_STATE_SUSPENDED:
1213                 return -ESTRPIPE;
1214             case PCM_STATE_DISCONNECTED:
1215                 return -ENODEV;
1216             default:
1217                 return -EIO;
1218             }
1219         }
1220     /* poll again if fd not ready for IO */
1221     } while (!(pfd.revents & (POLLIN | POLLOUT)));
1222 
1223     return 1;
1224 }
1225 
pcm_get_poll_fd(struct pcm * pcm)1226 int pcm_get_poll_fd(struct pcm *pcm)
1227 {
1228     return pcm->fd;
1229 }
1230 
pcm_mmap_transfer(struct pcm * pcm,const void * buffer,unsigned int bytes)1231 int pcm_mmap_transfer(struct pcm *pcm, const void *buffer, unsigned int bytes)
1232 {
1233     int err = 0, frames, avail;
1234     unsigned int offset = 0, count;
1235 
1236     if (bytes == 0)
1237         return 0;
1238 
1239     count = pcm_bytes_to_frames(pcm, bytes);
1240 
1241     while (count > 0) {
1242 
1243         /* get the available space for writing new frames */
1244         avail = pcm_avail_update(pcm);
1245         if (avail < 0) {
1246             fprintf(stderr, "cannot determine available mmap frames");
1247             return err;
1248         }
1249 
1250         /* start the audio if we reach the threshold */
1251 	    if (!pcm->running &&
1252             (pcm->buffer_size - avail) >= pcm->config.start_threshold) {
1253             if (pcm_start(pcm) < 0) {
1254                fprintf(stderr, "start error: hw 0x%x app 0x%x avail 0x%x\n",
1255                     (unsigned int)pcm->mmap_status->hw_ptr,
1256                     (unsigned int)pcm->mmap_control->appl_ptr,
1257                     avail);
1258                 return -errno;
1259             }
1260             pcm->wait_for_avail_min = 0;
1261         }
1262 
1263         /* sleep until we have space to write new frames */
1264         if (pcm->running) {
1265             /* enable waiting for avail_min threshold when less frames than we have to write
1266              * are available. */
1267             if (!pcm->wait_for_avail_min && (count > (unsigned int)avail))
1268                 pcm->wait_for_avail_min = 1;
1269 
1270             if (pcm->wait_for_avail_min && (avail < pcm->config.avail_min)) {
1271                 int time = -1;
1272 
1273                 /* disable waiting for avail_min threshold to allow small amounts of data to be
1274                  * written without waiting as long as there is enough room in buffer. */
1275                 pcm->wait_for_avail_min = 0;
1276 
1277                 if (pcm->flags & PCM_NOIRQ)
1278                     time = (pcm->config.avail_min - avail) / pcm->noirq_frames_per_msec;
1279 
1280                 err = pcm_wait(pcm, time);
1281                 if (err < 0) {
1282                     pcm->prepared = 0;
1283                     pcm->running = 0;
1284                     oops(pcm, errno, "wait error: hw 0x%x app 0x%x avail 0x%x\n",
1285                         (unsigned int)pcm->mmap_status->hw_ptr,
1286                         (unsigned int)pcm->mmap_control->appl_ptr,
1287                         avail);
1288                     pcm->mmap_control->appl_ptr = 0;
1289                     return err;
1290                 }
1291                 continue;
1292             }
1293         }
1294 
1295         frames = count;
1296         if (frames > avail)
1297             frames = avail;
1298 
1299         if (!frames)
1300             break;
1301 
1302         /* copy frames from buffer */
1303         frames = pcm_mmap_transfer_areas(pcm, (void *)buffer, offset, frames);
1304         if (frames < 0) {
1305             fprintf(stderr, "write error: hw 0x%x app 0x%x avail 0x%x\n",
1306                     (unsigned int)pcm->mmap_status->hw_ptr,
1307                     (unsigned int)pcm->mmap_control->appl_ptr,
1308                     avail);
1309             return frames;
1310         }
1311 
1312         offset += frames;
1313         count -= frames;
1314     }
1315 
1316     return 0;
1317 }
1318 
pcm_mmap_write(struct pcm * pcm,const void * data,unsigned int count)1319 int pcm_mmap_write(struct pcm *pcm, const void *data, unsigned int count)
1320 {
1321     if ((~pcm->flags) & (PCM_OUT | PCM_MMAP))
1322         return -ENOSYS;
1323 
1324     return pcm_mmap_transfer(pcm, (void *)data, count);
1325 }
1326 
pcm_mmap_read(struct pcm * pcm,void * data,unsigned int count)1327 int pcm_mmap_read(struct pcm *pcm, void *data, unsigned int count)
1328 {
1329     if ((~pcm->flags) & (PCM_IN | PCM_MMAP))
1330         return -ENOSYS;
1331 
1332     return pcm_mmap_transfer(pcm, data, count);
1333 }
1334 
pcm_ioctl(struct pcm * pcm,int request,...)1335 int pcm_ioctl(struct pcm *pcm, int request, ...)
1336 {
1337     va_list ap;
1338     void * arg;
1339 
1340     if (!pcm_is_ready(pcm))
1341         return -1;
1342 
1343     va_start(ap, request);
1344     arg = va_arg(ap, void *);
1345     va_end(ap);
1346 
1347     return ioctl(pcm->fd, request, arg);
1348 }
1349