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