• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* pcm.c
2 **
3 ** Copyright 2011, The Android Open Source Project
4 **
5 ** Redistribution and use in source and binary forms, with or without
6 ** modification, are permitted provided that the following conditions are met:
7 **     * Redistributions of source code must retain the above copyright
8 **       notice, this list of conditions and the following disclaimer.
9 **     * Redistributions in binary form must reproduce the above copyright
10 **       notice, this list of conditions and the following disclaimer in the
11 **       documentation and/or other materials provided with the distribution.
12 **     * Neither the name of The Android Open Source Project nor the names of
13 **       its contributors may be used to endorse or promote products derived
14 **       from this software without specific prior written permission.
15 **
16 ** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND
17 ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE
20 ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 ** DAMAGE.
27 */
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <fcntl.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <poll.h>
37 
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/time.h>
41 #include <limits.h>
42 
43 #include <linux/ioctl.h>
44 #define __force
45 #define __bitwise
46 #define __user
47 #include <sound/asound.h>
48 
49 #include <tinyalsa/asoundlib.h>
50 
51 #define PARAM_MAX SNDRV_PCM_HW_PARAM_LAST_INTERVAL
52 #define SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP (1<<2)
53 
param_is_mask(int p)54 static inline int param_is_mask(int p)
55 {
56     return (p >= SNDRV_PCM_HW_PARAM_FIRST_MASK) &&
57         (p <= SNDRV_PCM_HW_PARAM_LAST_MASK);
58 }
59 
param_is_interval(int p)60 static inline int param_is_interval(int p)
61 {
62     return (p >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL) &&
63         (p <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL);
64 }
65 
param_to_interval(struct snd_pcm_hw_params * p,int n)66 static inline struct snd_interval *param_to_interval(struct snd_pcm_hw_params *p, int n)
67 {
68     return &(p->intervals[n - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]);
69 }
70 
param_to_mask(struct snd_pcm_hw_params * p,int n)71 static inline struct snd_mask *param_to_mask(struct snd_pcm_hw_params *p, int n)
72 {
73     return &(p->masks[n - SNDRV_PCM_HW_PARAM_FIRST_MASK]);
74 }
75 
param_set_mask(struct snd_pcm_hw_params * p,int n,unsigned int bit)76 static void param_set_mask(struct snd_pcm_hw_params *p, int n, unsigned int bit)
77 {
78     if (bit >= SNDRV_MASK_MAX)
79         return;
80     if (param_is_mask(n)) {
81         struct snd_mask *m = param_to_mask(p, n);
82         m->bits[0] = 0;
83         m->bits[1] = 0;
84         m->bits[bit >> 5] |= (1 << (bit & 31));
85     }
86 }
87 
param_set_min(struct snd_pcm_hw_params * p,int n,unsigned int val)88 static void param_set_min(struct snd_pcm_hw_params *p, int n, unsigned int val)
89 {
90     if (param_is_interval(n)) {
91         struct snd_interval *i = param_to_interval(p, n);
92         i->min = val;
93     }
94 }
95 
param_set_max(struct snd_pcm_hw_params * p,int n,unsigned int val)96 static void param_set_max(struct snd_pcm_hw_params *p, int n, unsigned int val)
97 {
98     if (param_is_interval(n)) {
99         struct snd_interval *i = param_to_interval(p, n);
100         i->max = val;
101     }
102 }
103 
param_set_int(struct snd_pcm_hw_params * p,int n,unsigned int val)104 static void param_set_int(struct snd_pcm_hw_params *p, int n, unsigned int val)
105 {
106     if (param_is_interval(n)) {
107         struct snd_interval *i = param_to_interval(p, n);
108         i->min = val;
109         i->max = val;
110         i->integer = 1;
111     }
112 }
113 
param_get_int(struct snd_pcm_hw_params * p,int n)114 static unsigned int param_get_int(struct snd_pcm_hw_params *p, int n)
115 {
116     if (param_is_interval(n)) {
117         struct snd_interval *i = param_to_interval(p, n);
118         if (i->integer)
119             return i->max;
120     }
121     return 0;
122 }
123 
param_init(struct snd_pcm_hw_params * p)124 static void param_init(struct snd_pcm_hw_params *p)
125 {
126     int n;
127 
128     memset(p, 0, sizeof(*p));
129     for (n = SNDRV_PCM_HW_PARAM_FIRST_MASK;
130          n <= SNDRV_PCM_HW_PARAM_LAST_MASK; n++) {
131             struct snd_mask *m = param_to_mask(p, n);
132             m->bits[0] = ~0;
133             m->bits[1] = ~0;
134     }
135     for (n = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
136          n <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; n++) {
137             struct snd_interval *i = param_to_interval(p, n);
138             i->min = 0;
139             i->max = ~0;
140     }
141 }
142 
143 #define PCM_ERROR_MAX 128
144 
145 struct pcm {
146     int fd;
147     unsigned int flags;
148     int running:1;
149     int underruns;
150     unsigned int buffer_size;
151     unsigned int boundary;
152     char error[PCM_ERROR_MAX];
153     struct pcm_config config;
154     struct snd_pcm_mmap_status *mmap_status;
155     struct snd_pcm_mmap_control *mmap_control;
156     struct snd_pcm_sync_ptr *sync_ptr;
157     void *mmap_buffer;
158     unsigned int noirq_frames_per_msec;
159     int wait_for_avail_min;
160 };
161 
pcm_get_buffer_size(struct pcm * pcm)162 unsigned int pcm_get_buffer_size(struct pcm *pcm)
163 {
164     return pcm->buffer_size;
165 }
166 
pcm_get_error(struct pcm * pcm)167 const char* pcm_get_error(struct pcm *pcm)
168 {
169     return pcm->error;
170 }
171 
oops(struct pcm * pcm,int e,const char * fmt,...)172 static int oops(struct pcm *pcm, int e, const char *fmt, ...)
173 {
174     va_list ap;
175     int sz;
176 
177     va_start(ap, fmt);
178     vsnprintf(pcm->error, PCM_ERROR_MAX, fmt, ap);
179     va_end(ap);
180     sz = strlen(pcm->error);
181 
182     if (errno)
183         snprintf(pcm->error + sz, PCM_ERROR_MAX - sz,
184                  ": %s", strerror(e));
185     return -1;
186 }
187 
pcm_format_to_alsa(enum pcm_format format)188 static unsigned int pcm_format_to_alsa(enum pcm_format format)
189 {
190     switch (format) {
191     case PCM_FORMAT_S32_LE:
192         return SNDRV_PCM_FORMAT_S32_LE;
193     default:
194     case PCM_FORMAT_S16_LE:
195         return SNDRV_PCM_FORMAT_S16_LE;
196     };
197 }
198 
pcm_format_to_bits(enum pcm_format format)199 static unsigned int pcm_format_to_bits(enum pcm_format format)
200 {
201     switch (format) {
202     case PCM_FORMAT_S32_LE:
203         return 32;
204     default:
205     case PCM_FORMAT_S16_LE:
206         return 16;
207     };
208 }
209 
pcm_bytes_to_frames(struct pcm * pcm,unsigned int bytes)210 unsigned int pcm_bytes_to_frames(struct pcm *pcm, unsigned int bytes)
211 {
212     return bytes / (pcm->config.channels *
213         (pcm_format_to_bits(pcm->config.format) >> 3));
214 }
215 
pcm_frames_to_bytes(struct pcm * pcm,unsigned int frames)216 unsigned int pcm_frames_to_bytes(struct pcm *pcm, unsigned int frames)
217 {
218     return frames * pcm->config.channels *
219         (pcm_format_to_bits(pcm->config.format) >> 3);
220 }
221 
pcm_sync_ptr(struct pcm * pcm,int flags)222 static int pcm_sync_ptr(struct pcm *pcm, int flags) {
223     if (pcm->sync_ptr) {
224         pcm->sync_ptr->flags = flags;
225         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SYNC_PTR, pcm->sync_ptr) < 0)
226             return -1;
227     }
228     return 0;
229 }
230 
pcm_hw_mmap_status(struct pcm * pcm)231 static int pcm_hw_mmap_status(struct pcm *pcm) {
232 
233     if (pcm->sync_ptr)
234         return 0;
235 
236     int page_size = sysconf(_SC_PAGE_SIZE);
237     pcm->mmap_status = mmap(NULL, page_size, PROT_READ, MAP_FILE | MAP_SHARED,
238                             pcm->fd, SNDRV_PCM_MMAP_OFFSET_STATUS);
239     if (pcm->mmap_status == MAP_FAILED)
240         pcm->mmap_status = NULL;
241     if (!pcm->mmap_status)
242         goto mmap_error;
243 
244     pcm->mmap_control = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
245                              MAP_FILE | MAP_SHARED, pcm->fd, SNDRV_PCM_MMAP_OFFSET_CONTROL);
246     if (pcm->mmap_control == MAP_FAILED)
247         pcm->mmap_control = NULL;
248     if (!pcm->mmap_control) {
249         munmap(pcm->mmap_status, page_size);
250         pcm->mmap_status = NULL;
251         goto mmap_error;
252     }
253     if (pcm->flags & PCM_MMAP)
254         pcm->mmap_control->avail_min = pcm->config.avail_min;
255     else
256         pcm->mmap_control->avail_min = 1;
257 
258     return 0;
259 
260 mmap_error:
261 
262     pcm->sync_ptr = calloc(1, sizeof(*pcm->sync_ptr));
263     if (!pcm->sync_ptr)
264         return -ENOMEM;
265     pcm->mmap_status = &pcm->sync_ptr->s.status;
266     pcm->mmap_control = &pcm->sync_ptr->c.control;
267     if (pcm->flags & PCM_MMAP)
268         pcm->mmap_control->avail_min = pcm->config.avail_min;
269     else
270         pcm->mmap_control->avail_min = 1;
271 
272     pcm_sync_ptr(pcm, 0);
273 
274     return 0;
275 }
276 
pcm_hw_munmap_status(struct pcm * pcm)277 static void pcm_hw_munmap_status(struct pcm *pcm) {
278     if (pcm->sync_ptr) {
279         free(pcm->sync_ptr);
280         pcm->sync_ptr = NULL;
281     } else {
282         int page_size = sysconf(_SC_PAGE_SIZE);
283         if (pcm->mmap_status)
284             munmap(pcm->mmap_status, page_size);
285         if (pcm->mmap_control)
286             munmap(pcm->mmap_control, page_size);
287     }
288     pcm->mmap_status = NULL;
289     pcm->mmap_control = NULL;
290 }
291 
pcm_areas_copy(struct pcm * pcm,unsigned int pcm_offset,const char * src,unsigned int src_offset,unsigned int frames)292 static int pcm_areas_copy(struct pcm *pcm, unsigned int pcm_offset,
293                           const char *src, unsigned int src_offset,
294                           unsigned int frames)
295 {
296     int size_bytes = pcm_frames_to_bytes(pcm, frames);
297     int pcm_offset_bytes = pcm_frames_to_bytes(pcm, pcm_offset);
298     int src_offset_bytes = pcm_frames_to_bytes(pcm, src_offset);
299 
300     /* interleaved only atm */
301     memcpy((char*)pcm->mmap_buffer + pcm_offset_bytes,
302            src + src_offset_bytes, size_bytes);
303     return 0;
304 }
305 
pcm_mmap_write_areas(struct pcm * pcm,const char * src,unsigned int offset,unsigned int size)306 static int pcm_mmap_write_areas(struct pcm *pcm, const char *src,
307                                 unsigned int offset, unsigned int size)
308 {
309     void *pcm_areas;
310     int commit;
311     unsigned int pcm_offset, frames, count = 0;
312 
313     while (size > 0) {
314         frames = size;
315         pcm_mmap_begin(pcm, &pcm_areas, &pcm_offset, &frames);
316         pcm_areas_copy(pcm, pcm_offset, src, offset, frames);
317         commit = pcm_mmap_commit(pcm, pcm_offset, frames);
318         if (commit < 0) {
319             oops(pcm, commit, "failed to commit %d frames\n", frames);
320             return commit;
321         }
322 
323         offset += commit;
324         count += commit;
325         size -= commit;
326     }
327     return count;
328 }
329 
pcm_get_htimestamp(struct pcm * pcm,unsigned int * avail,struct timespec * tstamp)330 int pcm_get_htimestamp(struct pcm *pcm, unsigned int *avail,
331                        struct timespec *tstamp)
332 {
333     int frames;
334     int rc;
335     snd_pcm_uframes_t hw_ptr;
336 
337     if (!pcm_is_ready(pcm))
338         return -1;
339 
340     rc = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_HWSYNC);
341     if (rc < 0)
342         return -1;
343 
344     if ((pcm->mmap_status->state != PCM_STATE_RUNNING) &&
345             (pcm->mmap_status->state != PCM_STATE_DRAINING))
346         return -1;
347 
348     *tstamp = pcm->mmap_status->tstamp;
349     if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
350         return -1;
351 
352     hw_ptr = pcm->mmap_status->hw_ptr;
353     if (pcm->flags & PCM_IN)
354         frames = hw_ptr - pcm->mmap_control->appl_ptr;
355     else
356         frames = hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
357 
358     if (frames < 0)
359         frames += pcm->boundary;
360     else if (frames > (int)pcm->boundary)
361         frames -= pcm->boundary;
362 
363     *avail = (unsigned int)frames;
364 
365     return 0;
366 }
367 
pcm_write(struct pcm * pcm,const void * data,unsigned int count)368 int pcm_write(struct pcm *pcm, const void *data, unsigned int count)
369 {
370     struct snd_xferi x;
371 
372     if (pcm->flags & PCM_IN)
373         return -EINVAL;
374 
375     x.buf = (void*)data;
376     x.frames = count / (pcm->config.channels *
377                         pcm_format_to_bits(pcm->config.format) / 8);
378 
379     for (;;) {
380         if (!pcm->running) {
381             if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE))
382                 return oops(pcm, errno, "cannot prepare channel");
383             if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x))
384                 return oops(pcm, errno, "cannot write initial data");
385             pcm->running = 1;
386             return 0;
387         }
388         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_WRITEI_FRAMES, &x)) {
389             pcm->running = 0;
390             if (errno == EPIPE) {
391                 /* we failed to make our window -- try to restart if we are
392                  * allowed to do so.  Otherwise, simply allow the EPIPE error to
393                  * propagate up to the app level */
394                 pcm->underruns++;
395                 if (pcm->flags & PCM_NORESTART)
396                     return -EPIPE;
397                 continue;
398             }
399             return oops(pcm, errno, "cannot write stream data");
400         }
401         return 0;
402     }
403 }
404 
pcm_read(struct pcm * pcm,void * data,unsigned int count)405 int pcm_read(struct pcm *pcm, void *data, unsigned int count)
406 {
407     struct snd_xferi x;
408 
409     if (!(pcm->flags & PCM_IN))
410         return -EINVAL;
411 
412     x.buf = data;
413     x.frames = count / (pcm->config.channels *
414                         pcm_format_to_bits(pcm->config.format) / 8);
415 
416     for (;;) {
417         if (!pcm->running) {
418             pcm_start(pcm);
419         }
420         if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_READI_FRAMES, &x)) {
421             pcm->running = 0;
422             if (errno == EPIPE) {
423                     /* we failed to make our window -- try to restart */
424                 pcm->underruns++;
425                 continue;
426             }
427             return oops(pcm, errno, "cannot read stream data");
428         }
429         return 0;
430     }
431 }
432 
433 static struct pcm bad_pcm = {
434     .fd = -1,
435 };
436 
pcm_close(struct pcm * pcm)437 int pcm_close(struct pcm *pcm)
438 {
439     if (pcm == &bad_pcm)
440         return 0;
441 
442     pcm_hw_munmap_status(pcm);
443 
444     if (pcm->flags & PCM_MMAP) {
445         pcm_stop(pcm);
446         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
447     }
448 
449     if (pcm->fd >= 0)
450         close(pcm->fd);
451     pcm->running = 0;
452     pcm->buffer_size = 0;
453     pcm->fd = -1;
454     free(pcm);
455     return 0;
456 }
457 
pcm_open(unsigned int card,unsigned int device,unsigned int flags,struct pcm_config * config)458 struct pcm *pcm_open(unsigned int card, unsigned int device,
459                      unsigned int flags, struct pcm_config *config)
460 {
461     struct pcm *pcm;
462     struct snd_pcm_info info;
463     struct snd_pcm_hw_params params;
464     struct snd_pcm_sw_params sparams;
465     char fn[256];
466     int rc;
467 
468     pcm = calloc(1, sizeof(struct pcm));
469     if (!pcm || !config)
470         return &bad_pcm; /* TODO: could support default config here */
471 
472     pcm->config = *config;
473 
474     snprintf(fn, sizeof(fn), "/dev/snd/pcmC%uD%u%c", card, device,
475              flags & PCM_IN ? 'c' : 'p');
476 
477     pcm->flags = flags;
478     pcm->fd = open(fn, O_RDWR);
479     if (pcm->fd < 0) {
480         oops(pcm, errno, "cannot open device '%s'", fn);
481         return pcm;
482     }
483 
484     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_INFO, &info)) {
485         oops(pcm, errno, "cannot get info");
486         goto fail_close;
487     }
488 
489     param_init(&params);
490     param_set_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT,
491                    pcm_format_to_alsa(config->format));
492     param_set_mask(&params, SNDRV_PCM_HW_PARAM_SUBFORMAT,
493                    SNDRV_PCM_SUBFORMAT_STD);
494     param_set_min(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, config->period_size);
495     param_set_int(&params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
496                   pcm_format_to_bits(config->format));
497     param_set_int(&params, SNDRV_PCM_HW_PARAM_FRAME_BITS,
498                   pcm_format_to_bits(config->format) * config->channels);
499     param_set_int(&params, SNDRV_PCM_HW_PARAM_CHANNELS,
500                   config->channels);
501     param_set_int(&params, SNDRV_PCM_HW_PARAM_PERIODS, config->period_count);
502     param_set_int(&params, SNDRV_PCM_HW_PARAM_RATE, config->rate);
503 
504     if (flags & PCM_NOIRQ) {
505 
506         if (!(flags & PCM_MMAP)) {
507             oops(pcm, -EINVAL, "noirq only currently supported with mmap().");
508             goto fail;
509         }
510 
511         params.flags |= SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP;
512         pcm->noirq_frames_per_msec = config->rate / 1000;
513     }
514 
515     if (flags & PCM_MMAP)
516         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
517                    SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
518     else
519         param_set_mask(&params, SNDRV_PCM_HW_PARAM_ACCESS,
520                    SNDRV_PCM_ACCESS_RW_INTERLEAVED);
521 
522     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_HW_PARAMS, &params)) {
523         oops(pcm, errno, "cannot set hw params");
524         goto fail_close;
525     }
526 
527     /* get our refined hw_params */
528     config->period_size = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
529     config->period_count = param_get_int(&params, SNDRV_PCM_HW_PARAM_PERIODS);
530     pcm->buffer_size = config->period_count * config->period_size;
531 
532     if (flags & PCM_MMAP) {
533         pcm->mmap_buffer = mmap(NULL, pcm_frames_to_bytes(pcm, pcm->buffer_size),
534                                 PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, pcm->fd, 0);
535         if (pcm->mmap_buffer == MAP_FAILED) {
536             oops(pcm, -errno, "failed to mmap buffer %d bytes\n",
537                  pcm_frames_to_bytes(pcm, pcm->buffer_size));
538             goto fail_close;
539         }
540     }
541 
542 
543     memset(&sparams, 0, sizeof(sparams));
544     sparams.tstamp_mode = SNDRV_PCM_TSTAMP_ENABLE;
545     sparams.period_step = 1;
546 
547     if (!config->start_threshold)
548         pcm->config.start_threshold = sparams.start_threshold =
549             config->period_count * config->period_size / 2;
550     else
551         sparams.start_threshold = config->start_threshold;
552 
553     /* pick a high stop threshold - todo: does this need further tuning */
554     if (!config->stop_threshold) {
555         if (pcm->flags & PCM_IN)
556             pcm->config.stop_threshold = sparams.stop_threshold =
557                 config->period_count * config->period_size * 10;
558         else
559             pcm->config.stop_threshold = sparams.stop_threshold =
560                 config->period_count * config->period_size;
561     }
562     else
563         sparams.stop_threshold = config->stop_threshold;
564 
565     if (!pcm->config.avail_min) {
566         if (pcm->flags & PCM_MMAP)
567             pcm->config.avail_min = sparams.avail_min = pcm->config.period_size;
568         else
569             pcm->config.avail_min = sparams.avail_min = 1;
570     } else
571         sparams.avail_min = config->avail_min;
572 
573     sparams.xfer_align = config->period_size / 2; /* needed for old kernels */
574     sparams.silence_size = 0;
575     sparams.silence_threshold = config->silence_threshold;
576     pcm->boundary = sparams.boundary = pcm->buffer_size;
577 
578     while (pcm->boundary * 2 <= INT_MAX - pcm->buffer_size)
579 		pcm->boundary *= 2;
580 
581     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
582         oops(pcm, errno, "cannot set sw params");
583         goto fail;
584     }
585 
586     rc = pcm_hw_mmap_status(pcm);
587     if (rc < 0) {
588         oops(pcm, rc, "mmap status failed");
589         goto fail;
590     }
591 
592     pcm->underruns = 0;
593     return pcm;
594 
595 fail:
596     if (flags & PCM_MMAP)
597         munmap(pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
598 fail_close:
599     close(pcm->fd);
600     pcm->fd = -1;
601     return pcm;
602 }
603 
pcm_is_ready(struct pcm * pcm)604 int pcm_is_ready(struct pcm *pcm)
605 {
606     return pcm->fd >= 0;
607 }
608 
pcm_start(struct pcm * pcm)609 int pcm_start(struct pcm *pcm)
610 {
611     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_PREPARE) < 0)
612         return oops(pcm, errno, "cannot prepare channel");
613 
614     if (pcm->flags & PCM_MMAP)
615 	    pcm_sync_ptr(pcm, 0);
616 
617     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_START) < 0)
618         return oops(pcm, errno, "cannot start channel");
619 
620     pcm->running = 1;
621     return 0;
622 }
623 
pcm_stop(struct pcm * pcm)624 int pcm_stop(struct pcm *pcm)
625 {
626     if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DROP) < 0)
627         return oops(pcm, errno, "cannot stop channel");
628 
629     pcm->running = 0;
630     return 0;
631 }
632 
pcm_mmap_playback_avail(struct pcm * pcm)633 static inline int pcm_mmap_playback_avail(struct pcm *pcm)
634 {
635     int avail;
636 
637     avail = pcm->mmap_status->hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
638 
639     if (avail < 0)
640         avail += pcm->boundary;
641     else if (avail > (int)pcm->boundary)
642         avail -= pcm->boundary;
643 
644     return avail;
645 }
646 
pcm_mmap_capture_avail(struct pcm * pcm)647 static inline int pcm_mmap_capture_avail(struct pcm *pcm)
648 {
649     int avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
650     if (avail < 0)
651         avail += pcm->boundary;
652     return avail;
653 }
654 
pcm_mmap_avail(struct pcm * pcm)655 static inline int pcm_mmap_avail(struct pcm *pcm)
656 {
657     pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
658     if (pcm->flags & PCM_IN)
659         return pcm_mmap_capture_avail(pcm);
660     else
661         return pcm_mmap_playback_avail(pcm);
662 }
663 
pcm_mmap_appl_forward(struct pcm * pcm,int frames)664 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
665 {
666     unsigned int appl_ptr = pcm->mmap_control->appl_ptr;
667     appl_ptr += frames;
668 
669     /* check for boundary wrap */
670     if (appl_ptr > pcm->boundary)
671          appl_ptr -= pcm->boundary;
672     pcm->mmap_control->appl_ptr = appl_ptr;
673 }
674 
pcm_mmap_begin(struct pcm * pcm,void ** areas,unsigned int * offset,unsigned int * frames)675 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
676                    unsigned int *frames)
677 {
678     unsigned int continuous, copy_frames, avail;
679 
680     /* return the mmap buffer */
681     *areas = pcm->mmap_buffer;
682 
683     /* and the application offset in frames */
684     *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
685 
686     avail = pcm_mmap_avail(pcm);
687     if (avail > pcm->buffer_size)
688         avail = pcm->buffer_size;
689     continuous = pcm->buffer_size - *offset;
690 
691     /* we can only copy frames if the are availabale and continuos */
692     copy_frames = *frames;
693     if (copy_frames > avail)
694         copy_frames = avail;
695     if (copy_frames > continuous)
696         copy_frames = continuous;
697     *frames = copy_frames;
698 
699     return 0;
700 }
701 
pcm_mmap_commit(struct pcm * pcm,unsigned int offset,unsigned int frames)702 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset, unsigned int frames)
703 {
704     /* update the application pointer in userspace and kernel */
705     pcm_mmap_appl_forward(pcm, frames);
706     pcm_sync_ptr(pcm, 0);
707 
708     return frames;
709 }
710 
pcm_avail_update(struct pcm * pcm)711 int pcm_avail_update(struct pcm *pcm)
712 {
713     pcm_sync_ptr(pcm, 0);
714     return pcm_mmap_avail(pcm);
715 }
716 
pcm_state(struct pcm * pcm)717 int pcm_state(struct pcm *pcm)
718 {
719     int err = pcm_sync_ptr(pcm, 0);
720     if (err < 0)
721         return err;
722 
723     return pcm->mmap_status->state;
724 }
725 
pcm_set_avail_min(struct pcm * pcm,int avail_min)726 int pcm_set_avail_min(struct pcm *pcm, int avail_min)
727 {
728     if ((~pcm->flags) & (PCM_MMAP | PCM_NOIRQ))
729         return -ENOSYS;
730 
731     pcm->config.avail_min = avail_min;
732     return 0;
733 }
734 
pcm_wait(struct pcm * pcm,int timeout)735 int pcm_wait(struct pcm *pcm, int timeout)
736 {
737     struct pollfd pfd;
738     unsigned short revents = 0;
739     int err;
740 
741     pfd.fd = pcm->fd;
742     pfd.events = POLLOUT | POLLERR | POLLNVAL;
743 
744     do {
745         /* let's wait for avail or timeout */
746         err = poll(&pfd, 1, timeout);
747         if (err < 0)
748             return -errno;
749 
750         /* timeout ? */
751         if (err == 0)
752             return 0;
753 
754         /* have we been interrupted ? */
755         if (errno == -EINTR)
756             continue;
757 
758         /* check for any errors */
759         if (pfd.revents & (POLLERR | POLLNVAL)) {
760             switch (pcm_state(pcm)) {
761             case PCM_STATE_XRUN:
762                 return -EPIPE;
763             case PCM_STATE_SUSPENDED:
764                 return -ESTRPIPE;
765             case PCM_STATE_DISCONNECTED:
766                 return -ENODEV;
767             default:
768                 return -EIO;
769             }
770         }
771     /* poll again if fd not ready for IO */
772     } while (!(pfd.revents & (POLLIN | POLLOUT)));
773 
774     return 1;
775 }
776 
pcm_mmap_write(struct pcm * pcm,const void * buffer,unsigned int bytes)777 int pcm_mmap_write(struct pcm *pcm, const void *buffer, unsigned int bytes)
778 {
779     int err = 0, frames, avail;
780     unsigned int offset = 0, count;
781 
782     if (bytes == 0)
783         return 0;
784 
785     count = pcm_bytes_to_frames(pcm, bytes);
786 
787     while (count > 0) {
788 
789         /* get the available space for writing new frames */
790         avail = pcm_avail_update(pcm);
791         if (avail < 0) {
792             fprintf(stderr, "cannot determine available mmap frames");
793             return err;
794         }
795 
796         /* start the audio if we reach the threshold */
797 	    if (!pcm->running &&
798             (pcm->buffer_size - avail) >= pcm->config.start_threshold) {
799             if (pcm_start(pcm) < 0) {
800                fprintf(stderr, "start error: hw 0x%x app 0x%x avail 0x%x\n",
801                     (unsigned int)pcm->mmap_status->hw_ptr,
802                     (unsigned int)pcm->mmap_control->appl_ptr,
803                     avail);
804                 return -errno;
805             }
806             pcm->wait_for_avail_min = 0;
807         }
808 
809         /* sleep until we have space to write new frames */
810         if (pcm->running) {
811             /* enable waiting for avail_min threshold when less frames than we have to write
812              * are available. */
813             if (!pcm->wait_for_avail_min && (count > (unsigned int)avail))
814                 pcm->wait_for_avail_min = 1;
815 
816             if (pcm->wait_for_avail_min && (avail < pcm->config.avail_min)) {
817                 int time = -1;
818 
819                 /* disable waiting for avail_min threshold to allow small amounts of data to be
820                  * written without waiting as long as there is enough room in buffer. */
821                 pcm->wait_for_avail_min = 0;
822 
823                 if (pcm->flags & PCM_NOIRQ)
824                     time = (pcm->config.avail_min - avail) / pcm->noirq_frames_per_msec;
825 
826                 err = pcm_wait(pcm, time);
827                 if (err < 0) {
828                     pcm->running = 0;
829                     oops(pcm, err, "wait error: hw 0x%x app 0x%x avail 0x%x\n",
830                         (unsigned int)pcm->mmap_status->hw_ptr,
831                         (unsigned int)pcm->mmap_control->appl_ptr,
832                         avail);
833                     pcm->mmap_control->appl_ptr = 0;
834                     return err;
835                 }
836                 continue;
837             }
838         }
839 
840         frames = count;
841         if (frames > avail)
842             frames = avail;
843 
844         if (!frames)
845             break;
846 
847         /* copy frames from buffer */
848         frames = pcm_mmap_write_areas(pcm, buffer, offset, frames);
849         if (frames < 0) {
850             fprintf(stderr, "write error: hw 0x%x app 0x%x avail 0x%x\n",
851                     (unsigned int)pcm->mmap_status->hw_ptr,
852                     (unsigned int)pcm->mmap_control->appl_ptr,
853                     avail);
854             return frames;
855         }
856 
857         offset += frames;
858         count -= frames;
859     }
860 
861 _end:
862     return 0;
863 }
864