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 (errno)
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, commit, "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->state != PCM_STATE_RUNNING) &&
504             (pcm->mmap_status->state != PCM_STATE_DRAINING))
505         return oops(pcm, ENOSYS, "invalid stream state %d", pcm->mmap_status->state);
506 
507     *tstamp = pcm->mmap_status->tstamp;
508     if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
509         return oops(pcm, errno, "invalid time stamp");
510 
511     *hw_ptr = pcm->mmap_status->hw_ptr;
512 
513     return 0;
514 }
515 
pcm_write(struct pcm * pcm,const void * data,unsigned int count)516 int pcm_write(struct pcm *pcm, const void *data, unsigned int count)
517 {
518     struct snd_xferi x;
519 
520     if (pcm->flags & PCM_IN)
521         return -EINVAL;
522 
523     x.buf = (void*)data;
524     x.frames = count / (pcm->config.channels *
525                         pcm_format_to_bits(pcm->config.format) / 8);
526 
527     for (;;) {
528         if (!pcm->running) {
529             int prepare_error = pcm_prepare(pcm);
530             if (prepare_error)
531                 return prepare_error;
532             if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x))
533                 return oops(pcm, errno, "cannot write initial data");
534             pcm->running = 1;
535             return 0;
536         }
537         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x)) {
538             pcm->prepared = 0;
539             pcm->running = 0;
540             if (errno == EPIPE) {
541                 /* we failed to make our window -- try to restart if we are
542                  * allowed to do so.  Otherwise, simply allow the EPIPE error to
543                  * propagate up to the app level */
544                 pcm->underruns++;
545                 if (pcm->flags & PCM_NORESTART)
546                     return -EPIPE;
547                 continue;
548             }
549             return oops(pcm, errno, "cannot write stream data");
550         }
551         return 0;
552     }
553 }
554 
pcm_read(struct pcm * pcm,void * data,unsigned int count)555 int pcm_read(struct pcm *pcm, void *data, unsigned int count)
556 {
557     struct snd_xferi x;
558 
559     if (!(pcm->flags & PCM_IN))
560         return -EINVAL;
561 
562     x.buf = data;
563     x.frames = count / (pcm->config.channels *
564                         pcm_format_to_bits(pcm->config.format) / 8);
565 
566     for (;;) {
567         if (!pcm->running) {
568             if (pcm_start(pcm) < 0) {
569                 fprintf(stderr, "start error");
570                 return -errno;
571             }
572         }
573         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_READI_FRAMES, &x)) {
574             pcm->prepared = 0;
575             pcm->running = 0;
576             if (errno == EPIPE) {
577                     /* we failed to make our window -- try to restart */
578                 pcm->underruns++;
579                 continue;
580             }
581             return oops(pcm, errno, "cannot read stream data");
582         }
583         return 0;
584     }
585 }
586 
587 static struct pcm bad_pcm = {
588     .fd = -1,
589 };
590 
pcm_params_get(unsigned int card,unsigned int device,unsigned int flags)591 struct pcm_params *pcm_params_get(unsigned int card, unsigned int device,
592                                   unsigned int flags)
593 {
594     struct snd_pcm_hw_params *params;
595     char fn[256];
596     int fd;
597 
598     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
599              flags & PCM_IN ? 'c' : 'p');
600 
601     fd = open(fn, O_RDWR);
602     if (fd < 0) {
603         fprintf(stderr, "cannot open device '%s'\n", fn);
604         goto err_open;
605     }
606 
607     params = calloc(1, sizeof(struct snd_pcm_hw_params));
608     if (!params)
609         goto err_calloc;
610 
611     param_init(params);
612     if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, params)) {
613         fprintf(stderr, "SNDRV_PCM_IOCTL_HW_REFINE error (%d)\n", errno);
614         goto err_hw_refine;
615     }
616 
617     close(fd);
618 
619     return (struct pcm_params *)params;
620 
621 err_hw_refine:
622     free(params);
623 err_calloc:
624     close(fd);
625 err_open:
626     return NULL;
627 }
628 
pcm_params_free(struct pcm_params * pcm_params)629 void pcm_params_free(struct pcm_params *pcm_params)
630 {
631     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
632 
633     if (params)
634         free(params);
635 }
636 
pcm_param_to_alsa(enum pcm_param param)637 static int pcm_param_to_alsa(enum pcm_param param)
638 {
639     switch (param) {
640     case PCM_PARAM_ACCESS:
641         return SNDRV_PCM_HW_PARAM_ACCESS;
642     case PCM_PARAM_FORMAT:
643         return SNDRV_PCM_HW_PARAM_FORMAT;
644     case PCM_PARAM_SUBFORMAT:
645         return SNDRV_PCM_HW_PARAM_SUBFORMAT;
646     case PCM_PARAM_SAMPLE_BITS:
647         return SNDRV_PCM_HW_PARAM_SAMPLE_BITS;
648         break;
649     case PCM_PARAM_FRAME_BITS:
650         return SNDRV_PCM_HW_PARAM_FRAME_BITS;
651         break;
652     case PCM_PARAM_CHANNELS:
653         return SNDRV_PCM_HW_PARAM_CHANNELS;
654         break;
655     case PCM_PARAM_RATE:
656         return SNDRV_PCM_HW_PARAM_RATE;
657         break;
658     case PCM_PARAM_PERIOD_TIME:
659         return SNDRV_PCM_HW_PARAM_PERIOD_TIME;
660         break;
661     case PCM_PARAM_PERIOD_SIZE:
662         return SNDRV_PCM_HW_PARAM_PERIOD_SIZE;
663         break;
664     case PCM_PARAM_PERIOD_BYTES:
665         return SNDRV_PCM_HW_PARAM_PERIOD_BYTES;
666         break;
667     case PCM_PARAM_PERIODS:
668         return SNDRV_PCM_HW_PARAM_PERIODS;
669         break;
670     case PCM_PARAM_BUFFER_TIME:
671         return SNDRV_PCM_HW_PARAM_BUFFER_TIME;
672         break;
673     case PCM_PARAM_BUFFER_SIZE:
674         return SNDRV_PCM_HW_PARAM_BUFFER_SIZE;
675         break;
676     case PCM_PARAM_BUFFER_BYTES:
677         return SNDRV_PCM_HW_PARAM_BUFFER_BYTES;
678         break;
679     case PCM_PARAM_TICK_TIME:
680         return SNDRV_PCM_HW_PARAM_TICK_TIME;
681         break;
682 
683     default:
684         return -1;
685     }
686 }
687 
pcm_params_get_mask(struct pcm_params * pcm_params,enum pcm_param param)688 struct pcm_mask *pcm_params_get_mask(struct pcm_params *pcm_params,
689                                      enum pcm_param param)
690 {
691     int p;
692     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
693     if (params == NULL) {
694         return NULL;
695     }
696 
697     p = pcm_param_to_alsa(param);
698     if (p < 0 || !param_is_mask(p)) {
699         return NULL;
700     }
701 
702     return (struct pcm_mask *)param_to_mask(params, p);
703 }
704 
pcm_params_get_min(struct pcm_params * pcm_params,enum pcm_param param)705 unsigned int pcm_params_get_min(struct pcm_params *pcm_params,
706                                 enum pcm_param param)
707 {
708     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
709     int p;
710 
711     if (!params)
712         return 0;
713 
714     p = pcm_param_to_alsa(param);
715     if (p < 0)
716         return 0;
717 
718     return param_get_min(params, p);
719 }
720 
pcm_params_set_min(struct pcm_params * pcm_params,enum pcm_param param,unsigned int val)721 void pcm_params_set_min(struct pcm_params *pcm_params,
722                                 enum pcm_param param, unsigned int val)
723 {
724     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
725     int p;
726 
727     if (!params)
728         return;
729 
730     p = pcm_param_to_alsa(param);
731     if (p < 0)
732         return;
733 
734     param_set_min(params, p, val);
735 }
736 
pcm_params_get_max(struct pcm_params * pcm_params,enum pcm_param param)737 unsigned int pcm_params_get_max(struct pcm_params *pcm_params,
738                                 enum pcm_param param)
739 {
740     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
741     int p;
742 
743     if (!params)
744         return 0;
745 
746     p = pcm_param_to_alsa(param);
747     if (p < 0)
748         return 0;
749 
750     return param_get_max(params, p);
751 }
752 
pcm_params_set_max(struct pcm_params * pcm_params,enum pcm_param param,unsigned int val)753 void pcm_params_set_max(struct pcm_params *pcm_params,
754                                 enum pcm_param param, unsigned int val)
755 {
756     struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
757     int p;
758 
759     if (!params)
760         return;
761 
762     p = pcm_param_to_alsa(param);
763     if (p < 0)
764         return;
765 
766     param_set_max(params, p, val);
767 }
768 
pcm_mask_test(struct pcm_mask * m,unsigned int index)769 static int pcm_mask_test(struct pcm_mask *m, unsigned int index)
770 {
771     const unsigned int bitshift = 5; /* for 32 bit integer */
772     const unsigned int bitmask = (1 << bitshift) - 1;
773     unsigned int element;
774 
775     element = index >> bitshift;
776     if (element >= ARRAY_SIZE(m->bits))
777         return 0; /* for safety, but should never occur */
778     return (m->bits[element] >> (index & bitmask)) & 1;
779 }
780 
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)781 static int pcm_mask_to_string(struct pcm_mask *m, char *string, unsigned int size,
782                               char *mask_name,
783                               const char * const *bit_array_name, size_t bit_array_size)
784 {
785     unsigned int i;
786     unsigned int offset = 0;
787 
788     if (m == NULL)
789         return 0;
790     if (bit_array_size < 32) {
791         STRLOG(string, offset, size, "%12s:\t%#08x\n", mask_name, m->bits[0]);
792     } else { /* spans two or more bitfields, print with an array index */
793         for (i = 0; i < (bit_array_size + 31) >> 5; ++i) {
794             STRLOG(string, offset, size, "%9s[%d]:\t%#08x\n",
795                    mask_name, i, m->bits[i]);
796         }
797     }
798     for (i = 0; i < bit_array_size; ++i) {
799         if (pcm_mask_test(m, i)) {
800             STRLOG(string, offset, size, "%12s \t%s\n", "", bit_array_name[i]);
801         }
802     }
803     return offset;
804 }
805 
pcm_params_to_string(struct pcm_params * params,char * string,unsigned int size)806 int pcm_params_to_string(struct pcm_params *params, char *string, unsigned int size)
807 {
808     struct pcm_mask *m;
809     unsigned int min, max;
810     unsigned int clipoffset, offset;
811 
812     m = pcm_params_get_mask(params, PCM_PARAM_ACCESS);
813     offset = pcm_mask_to_string(m, string, size,
814                                  "Access", access_lookup, ARRAY_SIZE(access_lookup));
815     m = pcm_params_get_mask(params, PCM_PARAM_FORMAT);
816     clipoffset = offset > size ? size : offset;
817     offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
818                                  "Format", format_lookup, ARRAY_SIZE(format_lookup));
819     m = pcm_params_get_mask(params, PCM_PARAM_SUBFORMAT);
820     clipoffset = offset > size ? size : offset;
821     offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
822                                  "Subformat", subformat_lookup, ARRAY_SIZE(subformat_lookup));
823     min = pcm_params_get_min(params, PCM_PARAM_RATE);
824     max = pcm_params_get_max(params, PCM_PARAM_RATE);
825     STRLOG(string, offset, size, "        Rate:\tmin=%uHz\tmax=%uHz\n", min, max);
826     min = pcm_params_get_min(params, PCM_PARAM_CHANNELS);
827     max = pcm_params_get_max(params, PCM_PARAM_CHANNELS);
828     STRLOG(string, offset, size, "    Channels:\tmin=%u\t\tmax=%u\n", min, max);
829     min = pcm_params_get_min(params, PCM_PARAM_SAMPLE_BITS);
830     max = pcm_params_get_max(params, PCM_PARAM_SAMPLE_BITS);
831     STRLOG(string, offset, size, " Sample bits:\tmin=%u\t\tmax=%u\n", min, max);
832     min = pcm_params_get_min(params, PCM_PARAM_PERIOD_SIZE);
833     max = pcm_params_get_max(params, PCM_PARAM_PERIOD_SIZE);
834     STRLOG(string, offset, size, " Period size:\tmin=%u\t\tmax=%u\n", min, max);
835     min = pcm_params_get_min(params, PCM_PARAM_PERIODS);
836     max = pcm_params_get_max(params, PCM_PARAM_PERIODS);
837     STRLOG(string, offset, size, "Period count:\tmin=%u\t\tmax=%u\n", min, max);
838     return offset;
839 }
840 
pcm_params_format_test(struct pcm_params * params,enum pcm_format format)841 int pcm_params_format_test(struct pcm_params *params, enum pcm_format format)
842 {
843     unsigned int alsa_format = pcm_format_to_alsa(format);
844 
845     if (alsa_format == SNDRV_PCM_FORMAT_S16_LE && format != PCM_FORMAT_S16_LE)
846         return 0; /* caution: format not recognized is equivalent to S16_LE */
847     return pcm_mask_test(pcm_params_get_mask(params, PCM_PARAM_FORMAT), alsa_format);
848 }
849 
pcm_close(struct pcm * pcm)850 int pcm_close(struct pcm *pcm)
851 {
852     if (pcm == &bad_pcm)
853         return 0;
854 
855     pcm_hw_munmap_status(pcm);
856 
857     if (pcm->flags & PCM_MMAP) {
858         pcm_stop(pcm);
859         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
860     }
861 
862     if (pcm->fd >= 0)
863         close(pcm->fd);
864     pcm->prepared = 0;
865     pcm->running = 0;
866     pcm->buffer_size = 0;
867     pcm->fd = -1;
868     free(pcm);
869     return 0;
870 }
871 
pcm_open(unsigned int card,unsigned int device,unsigned int flags,struct pcm_config * config)872 struct pcm *pcm_open(unsigned int card, unsigned int device,
873                      unsigned int flags, struct pcm_config *config)
874 {
875     struct pcm *pcm;
876     struct snd_pcm_info info;
877     struct snd_pcm_hw_params params;
878     struct snd_pcm_sw_params sparams;
879     char fn[256];
880     int rc;
881 
882     pcm = calloc(1, sizeof(struct pcm));
883     if (!pcm || !config)
884         return &bad_pcm; /* TODO: could support default config here */
885 
886     pcm->config = *config;
887 
888     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
889              flags & PCM_IN ? 'c' : 'p');
890 
891     pcm->flags = flags;
892     pcm->fd = open(fn, O_RDWR|O_NONBLOCK);
893     if (pcm->fd < 0) {
894         oops(pcm, errno, "cannot open device '%s'", fn);
895         return pcm;
896     }
897 
898     if (fcntl(pcm->fd, F_SETFL, fcntl(pcm->fd, F_GETFL) &
899               ~O_NONBLOCK) < 0) {
900         oops(pcm, errno, "failed to reset blocking mode '%s'", fn);
901         goto fail_close;
902     }
903 
904     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_INFO, &info)) {
905         oops(pcm, errno, "cannot get info");
906         goto fail_close;
907     }
908     pcm->subdevice = info.subdevice;
909 
910     param_init(&params);
911     param_set_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT,
912                    pcm_format_to_alsa(config->format));
913     param_set_mask(&params, SNDRV_PCM_HW_PARAM_SUBFORMAT,
914                    SNDRV_PCM_SUBFORMAT_STD);
915     param_set_min(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, config->period_size);
916     param_set_int(&params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
917                   pcm_format_to_bits(config->format));
918     param_set_int(&params, SNDRV_PCM_HW_PARAM_FRAME_BITS,
919                   pcm_format_to_bits(config->format) * config->channels);
920     param_set_int(&params, SNDRV_PCM_HW_PARAM_CHANNELS,
921                   config->channels);
922     param_set_int(&params, SNDRV_PCM_HW_PARAM_PERIODS, config->period_count);
923     param_set_int(&params, SNDRV_PCM_HW_PARAM_RATE, config->rate);
924 
925     if (flags & PCM_NOIRQ) {
926         if (!(flags & PCM_MMAP)) {
927             oops(pcm, -EINVAL, "noirq only currently supported with mmap().");
928             goto fail_close;
929         }
930 
931         params.flags |= SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP;
932         pcm->noirq_frames_per_msec = config->rate / 1000;
933     }
934 
935     if (flags & PCM_MMAP)
936         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
937                        SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
938     else
939         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
940                        SNDRV_PCM_ACCESS_RW_INTERLEAVED);
941 
942     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_HW_PARAMS, &params)) {
943         oops(pcm, errno, "cannot set hw params");
944         goto fail_close;
945     }
946 
947     /* get our refined hw_params */
948     config->period_size = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
949     config->period_count = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIODS);
950     pcm->buffer_size = config->period_count * config->period_size;
951 
952     if (flags & PCM_MMAP) {
953         pcm->mmap_buffer = mmap(NULL, pcm_frames_to_bytes(pcm, pcm->buffer_size),
954                                 PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, pcm->fd, 0);
955         if (pcm->mmap_buffer == MAP_FAILED) {
956             oops(pcm, -errno, "failed to mmap buffer %d bytes\n",
957                  pcm_frames_to_bytes(pcm, pcm->buffer_size));
958             goto fail_close;
959         }
960     }
961 
962     memset(&sparams, 0, sizeof(sparams));
963     sparams.tstamp_mode = SNDRV_PCM_TSTAMP_ENABLE;
964     sparams.period_step = 1;
965 
966     if (!config->start_threshold) {
967         if (pcm->flags & PCM_IN)
968             pcm->config.start_threshold = sparams.start_threshold = 1;
969         else
970             pcm->config.start_threshold = sparams.start_threshold =
971                 config->period_count * config->period_size / 2;
972     } else
973         sparams.start_threshold = config->start_threshold;
974 
975     /* pick a high stop threshold - todo: does this need further tuning */
976     if (!config->stop_threshold) {
977         if (pcm->flags & PCM_IN)
978             pcm->config.stop_threshold = sparams.stop_threshold =
979                 config->period_count * config->period_size * 10;
980         else
981             pcm->config.stop_threshold = sparams.stop_threshold =
982                 config->period_count * config->period_size;
983     }
984     else
985         sparams.stop_threshold = config->stop_threshold;
986 
987     if (!pcm->config.avail_min) {
988         if (pcm->flags & PCM_MMAP)
989             pcm->config.avail_min = sparams.avail_min = pcm->config.period_size;
990         else
991             pcm->config.avail_min = sparams.avail_min = 1;
992     } else
993         sparams.avail_min = config->avail_min;
994 
995     sparams.xfer_align = config->period_size / 2; /* needed for old kernels */
996     sparams.silence_threshold = config->silence_threshold;
997     sparams.silence_size = config->silence_size;
998     pcm->boundary = sparams.boundary = pcm->buffer_size;
999 
1000     while (pcm->boundary * 2 <= INT_MAX - pcm->buffer_size)
1001         pcm->boundary *= 2;
1002 
1003     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
1004         oops(pcm, errno, "cannot set sw params");
1005         goto fail;
1006     }
1007 
1008     rc = pcm_hw_mmap_status(pcm);
1009     if (rc < 0) {
1010         oops(pcm, rc, "mmap status failed");
1011         goto fail;
1012     }
1013 
1014 #ifdef SNDRV_PCM_IOCTL_TTSTAMP
1015     if (pcm->flags & PCM_MONOTONIC) {
1016         int arg = SNDRV_PCM_TSTAMP_TYPE_MONOTONIC;
1017         rc = ioctl(pcm->fd, SNDRV_PCM_IOCTL_TTSTAMP, &arg);
1018         if (rc < 0) {
1019             oops(pcm, rc, "cannot set timestamp type");
1020             goto fail;
1021         }
1022     }
1023 #endif
1024 
1025     pcm->underruns = 0;
1026     return pcm;
1027 
1028 fail:
1029     if (flags & PCM_MMAP)
1030         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
1031 fail_close:
1032     close(pcm->fd);
1033     pcm->fd = -1;
1034     return pcm;
1035 }
1036 
pcm_is_ready(struct pcm * pcm)1037 int pcm_is_ready(struct pcm *pcm)
1038 {
1039     return pcm->fd >= 0;
1040 }
1041 
pcm_prepare(struct pcm * pcm)1042 int pcm_prepare(struct pcm *pcm)
1043 {
1044     if (pcm->prepared)
1045         return 0;
1046 
1047     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE) < 0)
1048         return oops(pcm, errno, "cannot prepare channel");
1049 
1050     pcm->prepared = 1;
1051     return 0;
1052 }
1053 
pcm_start(struct pcm * pcm)1054 int pcm_start(struct pcm *pcm)
1055 {
1056     int prepare_error = pcm_prepare(pcm);
1057     if (prepare_error)
1058         return prepare_error;
1059 
1060     if (pcm->flags & PCM_MMAP)
1061 	    pcm_sync_ptr(pcm, 0);
1062 
1063     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_START) < 0)
1064         return oops(pcm, errno, "cannot start channel");
1065 
1066     pcm->running = 1;
1067     return 0;
1068 }
1069 
pcm_stop(struct pcm * pcm)1070 int pcm_stop(struct pcm *pcm)
1071 {
1072     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DROP) < 0)
1073         return oops(pcm, errno, "cannot stop channel");
1074 
1075     pcm->prepared = 0;
1076     pcm->running = 0;
1077     return 0;
1078 }
1079 
pcm_mmap_playback_avail(struct pcm * pcm)1080 static inline int pcm_mmap_playback_avail(struct pcm *pcm)
1081 {
1082     int avail;
1083 
1084     avail = pcm->mmap_status->hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
1085 
1086     if (avail < 0)
1087         avail += pcm->boundary;
1088     else if (avail > (int)pcm->boundary)
1089         avail -= pcm->boundary;
1090 
1091     return avail;
1092 }
1093 
pcm_mmap_capture_avail(struct pcm * pcm)1094 static inline int pcm_mmap_capture_avail(struct pcm *pcm)
1095 {
1096     int avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
1097     if (avail < 0)
1098         avail += pcm->boundary;
1099     return avail;
1100 }
1101 
pcm_mmap_avail(struct pcm * pcm)1102 int pcm_mmap_avail(struct pcm *pcm)
1103 {
1104     pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
1105     if (pcm->flags & PCM_IN)
1106         return pcm_mmap_capture_avail(pcm);
1107     else
1108         return pcm_mmap_playback_avail(pcm);
1109 }
1110 
pcm_mmap_appl_forward(struct pcm * pcm,int frames)1111 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
1112 {
1113     unsigned int appl_ptr = pcm->mmap_control->appl_ptr;
1114     appl_ptr += frames;
1115 
1116     /* check for boundary wrap */
1117     if (appl_ptr > pcm->boundary)
1118          appl_ptr -= pcm->boundary;
1119     pcm->mmap_control->appl_ptr = appl_ptr;
1120 }
1121 
pcm_mmap_begin(struct pcm * pcm,void ** areas,unsigned int * offset,unsigned int * frames)1122 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
1123                    unsigned int *frames)
1124 {
1125     unsigned int continuous, copy_frames, avail;
1126 
1127     /* return the mmap buffer */
1128     *areas = pcm->mmap_buffer;
1129 
1130     /* and the application offset in frames */
1131     *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
1132 
1133     avail = pcm_mmap_avail(pcm);
1134     if (avail > pcm->buffer_size)
1135         avail = pcm->buffer_size;
1136     continuous = pcm->buffer_size - *offset;
1137 
1138     /* we can only copy frames if the are availabale and continuos */
1139     copy_frames = *frames;
1140     if (copy_frames > avail)
1141         copy_frames = avail;
1142     if (copy_frames > continuous)
1143         copy_frames = continuous;
1144     *frames = copy_frames;
1145 
1146     return 0;
1147 }
1148 
pcm_mmap_commit(struct pcm * pcm,unsigned int offset,unsigned int frames)1149 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset __attribute__((unused)), unsigned int frames)
1150 {
1151     /* update the application pointer in userspace and kernel */
1152     pcm_mmap_appl_forward(pcm, frames);
1153     pcm_sync_ptr(pcm, 0);
1154 
1155     return frames;
1156 }
1157 
pcm_avail_update(struct pcm * pcm)1158 int pcm_avail_update(struct pcm *pcm)
1159 {
1160     pcm_sync_ptr(pcm, 0);
1161     return pcm_mmap_avail(pcm);
1162 }
1163 
pcm_state(struct pcm * pcm)1164 int pcm_state(struct pcm *pcm)
1165 {
1166     int err = pcm_sync_ptr(pcm, 0);
1167     if (err < 0)
1168         return err;
1169 
1170     return pcm->mmap_status->state;
1171 }
1172 
pcm_set_avail_min(struct pcm * pcm,int avail_min)1173 int pcm_set_avail_min(struct pcm *pcm, int avail_min)
1174 {
1175     if ((~pcm->flags) & (PCM_MMAP | PCM_NOIRQ))
1176         return -ENOSYS;
1177 
1178     pcm->config.avail_min = avail_min;
1179     return 0;
1180 }
1181 
pcm_wait(struct pcm * pcm,int timeout)1182 int pcm_wait(struct pcm *pcm, int timeout)
1183 {
1184     struct pollfd pfd;
1185     int err;
1186 
1187     pfd.fd = pcm->fd;
1188     pfd.events = POLLOUT | POLLERR | POLLNVAL;
1189 
1190     do {
1191         /* let's wait for avail or timeout */
1192         err = poll(&pfd, 1, timeout);
1193         if (err < 0)
1194             return -errno;
1195 
1196         /* timeout ? */
1197         if (err == 0)
1198             return 0;
1199 
1200         /* have we been interrupted ? */
1201         if (errno == -EINTR)
1202             continue;
1203 
1204         /* check for any errors */
1205         if (pfd.revents & (POLLERR | POLLNVAL)) {
1206             switch (pcm_state(pcm)) {
1207             case PCM_STATE_XRUN:
1208                 return -EPIPE;
1209             case PCM_STATE_SUSPENDED:
1210                 return -ESTRPIPE;
1211             case PCM_STATE_DISCONNECTED:
1212                 return -ENODEV;
1213             default:
1214                 return -EIO;
1215             }
1216         }
1217     /* poll again if fd not ready for IO */
1218     } while (!(pfd.revents & (POLLIN | POLLOUT)));
1219 
1220     return 1;
1221 }
1222 
pcm_get_poll_fd(struct pcm * pcm)1223 int pcm_get_poll_fd(struct pcm *pcm)
1224 {
1225     return pcm->fd;
1226 }
1227 
pcm_mmap_transfer(struct pcm * pcm,const void * buffer,unsigned int bytes)1228 int pcm_mmap_transfer(struct pcm *pcm, const void *buffer, unsigned int bytes)
1229 {
1230     int err = 0, frames, avail;
1231     unsigned int offset = 0, count;
1232 
1233     if (bytes == 0)
1234         return 0;
1235 
1236     count = pcm_bytes_to_frames(pcm, bytes);
1237 
1238     while (count > 0) {
1239 
1240         /* get the available space for writing new frames */
1241         avail = pcm_avail_update(pcm);
1242         if (avail < 0) {
1243             fprintf(stderr, "cannot determine available mmap frames");
1244             return err;
1245         }
1246 
1247         /* start the audio if we reach the threshold */
1248 	    if (!pcm->running &&
1249             (pcm->buffer_size - avail) >= pcm->config.start_threshold) {
1250             if (pcm_start(pcm) < 0) {
1251                fprintf(stderr, "start error: hw 0x%x app 0x%x avail 0x%x\n",
1252                     (unsigned int)pcm->mmap_status->hw_ptr,
1253                     (unsigned int)pcm->mmap_control->appl_ptr,
1254                     avail);
1255                 return -errno;
1256             }
1257             pcm->wait_for_avail_min = 0;
1258         }
1259 
1260         /* sleep until we have space to write new frames */
1261         if (pcm->running) {
1262             /* enable waiting for avail_min threshold when less frames than we have to write
1263              * are available. */
1264             if (!pcm->wait_for_avail_min && (count > (unsigned int)avail))
1265                 pcm->wait_for_avail_min = 1;
1266 
1267             if (pcm->wait_for_avail_min && (avail < pcm->config.avail_min)) {
1268                 int time = -1;
1269 
1270                 /* disable waiting for avail_min threshold to allow small amounts of data to be
1271                  * written without waiting as long as there is enough room in buffer. */
1272                 pcm->wait_for_avail_min = 0;
1273 
1274                 if (pcm->flags & PCM_NOIRQ)
1275                     time = (pcm->config.avail_min - avail) / pcm->noirq_frames_per_msec;
1276 
1277                 err = pcm_wait(pcm, time);
1278                 if (err < 0) {
1279                     pcm->prepared = 0;
1280                     pcm->running = 0;
1281                     oops(pcm, err, "wait error: hw 0x%x app 0x%x avail 0x%x\n",
1282                         (unsigned int)pcm->mmap_status->hw_ptr,
1283                         (unsigned int)pcm->mmap_control->appl_ptr,
1284                         avail);
1285                     pcm->mmap_control->appl_ptr = 0;
1286                     return err;
1287                 }
1288                 continue;
1289             }
1290         }
1291 
1292         frames = count;
1293         if (frames > avail)
1294             frames = avail;
1295 
1296         if (!frames)
1297             break;
1298 
1299         /* copy frames from buffer */
1300         frames = pcm_mmap_transfer_areas(pcm, (void *)buffer, offset, frames);
1301         if (frames < 0) {
1302             fprintf(stderr, "write error: hw 0x%x app 0x%x avail 0x%x\n",
1303                     (unsigned int)pcm->mmap_status->hw_ptr,
1304                     (unsigned int)pcm->mmap_control->appl_ptr,
1305                     avail);
1306             return frames;
1307         }
1308 
1309         offset += frames;
1310         count -= frames;
1311     }
1312 
1313     return 0;
1314 }
1315 
pcm_mmap_write(struct pcm * pcm,const void * data,unsigned int count)1316 int pcm_mmap_write(struct pcm *pcm, const void *data, unsigned int count)
1317 {
1318     if ((~pcm->flags) & (PCM_OUT | PCM_MMAP))
1319         return -ENOSYS;
1320 
1321     return pcm_mmap_transfer(pcm, (void *)data, count);
1322 }
1323 
pcm_mmap_read(struct pcm * pcm,void * data,unsigned int count)1324 int pcm_mmap_read(struct pcm *pcm, void *data, unsigned int count)
1325 {
1326     if ((~pcm->flags) & (PCM_IN | PCM_MMAP))
1327         return -ENOSYS;
1328 
1329     return pcm_mmap_transfer(pcm, data, count);
1330 }
1331 
pcm_ioctl(struct pcm * pcm,int request,...)1332 int pcm_ioctl(struct pcm *pcm, int request, ...)
1333 {
1334     va_list ap;
1335     void * arg;
1336 
1337     if (!pcm_is_ready(pcm))
1338         return -1;
1339 
1340     va_start(ap, request);
1341     arg = va_arg(ap, void *);
1342     va_end(ap);
1343 
1344     return ioctl(pcm->fd, request, arg);
1345 }
1346