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 <time.h>
42 #include <limits.h>
43
44 #include <linux/ioctl.h>
45
46 #ifndef __force
47 #define __force
48 #endif
49
50 #ifndef __bitwise
51 #define __bitwise
52 #endif
53
54 #ifndef __user
55 #define __user
56 #endif
57
58 #include <sound/asound.h>
59
60 #include <tinyalsa/pcm.h>
61 #include <tinyalsa/limits.h>
62 #include "pcm_io.h"
63 #include "snd_card_plugin.h"
64
65 #ifndef PARAM_MAX
66 #define PARAM_MAX SNDRV_PCM_HW_PARAM_LAST_INTERVAL
67 #endif /* PARAM_MAX */
68
69 #ifndef SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP
70 #define SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP (1<<2)
71 #endif /* SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP */
72
73 /* Logs information into a string; follows snprintf() in that
74 * offset may be greater than size, and though no characters are copied
75 * into string, characters are still counted into offset. */
76 #define STRLOG(string, offset, size, ...) \
77 do { int temp, clipoffset = offset > size ? size : offset; \
78 temp = snprintf(string + clipoffset, size - clipoffset, __VA_ARGS__); \
79 if (temp > 0) offset += temp; } while (0)
80
81 #ifndef ARRAY_SIZE
82 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
83 #endif
84
85 /* refer to SNDRV_PCM_ACCESS_##index in sound/asound.h. */
86 static const char * const access_lookup[] = {
87 "MMAP_INTERLEAVED",
88 "MMAP_NONINTERLEAVED",
89 "MMAP_COMPLEX",
90 "RW_INTERLEAVED",
91 "RW_NONINTERLEAVED",
92 };
93
94 /* refer to SNDRV_PCM_FORMAT_##index in sound/asound.h. */
95 static const char * const format_lookup[] = {
96 /*[0] =*/ "S8",
97 "U8",
98 "S16_LE",
99 "S16_BE",
100 "U16_LE",
101 "U16_BE",
102 "S24_LE",
103 "S24_BE",
104 "U24_LE",
105 "U24_BE",
106 "S32_LE",
107 "S32_BE",
108 "U32_LE",
109 "U32_BE",
110 "FLOAT_LE",
111 "FLOAT_BE",
112 "FLOAT64_LE",
113 "FLOAT64_BE",
114 "IEC958_SUBFRAME_LE",
115 "IEC958_SUBFRAME_BE",
116 "MU_LAW",
117 "A_LAW",
118 "IMA_ADPCM",
119 "MPEG",
120 /*[24] =*/ "GSM",
121 /* gap */
122 [31] = "SPECIAL",
123 "S24_3LE",
124 "S24_3BE",
125 "U24_3LE",
126 "U24_3BE",
127 "S20_3LE",
128 "S20_3BE",
129 "U20_3LE",
130 "U20_3BE",
131 "S18_3LE",
132 "S18_3BE",
133 "U18_3LE",
134 /*[43] =*/ "U18_3BE",
135 #if 0
136 /* recent additions, may not be present on local asound.h */
137 "G723_24",
138 "G723_24_1B",
139 "G723_40",
140 "G723_40_1B",
141 "DSD_U8",
142 "DSD_U16_LE",
143 #endif
144 };
145
146 /* refer to SNDRV_PCM_SUBFORMAT_##index in sound/asound.h. */
147 static const char * const subformat_lookup[] = {
148 "STD",
149 };
150
param_is_mask(int p)151 static inline int param_is_mask(int p)
152 {
153 return (p >= SNDRV_PCM_HW_PARAM_FIRST_MASK) &&
154 (p <= SNDRV_PCM_HW_PARAM_LAST_MASK);
155 }
156
param_is_interval(int p)157 static inline int param_is_interval(int p)
158 {
159 return (p >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL) &&
160 (p <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL);
161 }
162
param_get_interval(const struct snd_pcm_hw_params * p,int n)163 static inline const struct snd_interval *param_get_interval(const struct snd_pcm_hw_params *p, int n)
164 {
165 return &(p->intervals[n - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]);
166 }
167
param_to_interval(struct snd_pcm_hw_params * p,int n)168 static inline struct snd_interval *param_to_interval(struct snd_pcm_hw_params *p, int n)
169 {
170 return &(p->intervals[n - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]);
171 }
172
param_to_mask(struct snd_pcm_hw_params * p,int n)173 static inline struct snd_mask *param_to_mask(struct snd_pcm_hw_params *p, int n)
174 {
175 return &(p->masks[n - SNDRV_PCM_HW_PARAM_FIRST_MASK]);
176 }
177
param_set_mask(struct snd_pcm_hw_params * p,int n,unsigned int bit)178 static void param_set_mask(struct snd_pcm_hw_params *p, int n, unsigned int bit)
179 {
180 if (bit >= SNDRV_MASK_MAX)
181 return;
182 if (param_is_mask(n)) {
183 struct snd_mask *m = param_to_mask(p, n);
184 m->bits[0] = 0;
185 m->bits[1] = 0;
186 m->bits[bit >> 5] |= (1 << (bit & 31));
187 }
188 }
189
param_set_min(struct snd_pcm_hw_params * p,int n,unsigned int val)190 static void param_set_min(struct snd_pcm_hw_params *p, int n, unsigned int val)
191 {
192 if (param_is_interval(n)) {
193 struct snd_interval *i = param_to_interval(p, n);
194 i->min = val;
195 }
196 }
197
param_get_min(const struct snd_pcm_hw_params * p,int n)198 static unsigned int param_get_min(const struct snd_pcm_hw_params *p, int n)
199 {
200 if (param_is_interval(n)) {
201 const struct snd_interval *i = param_get_interval(p, n);
202 return i->min;
203 }
204 return 0;
205 }
206
param_get_max(const struct snd_pcm_hw_params * p,int n)207 static unsigned int param_get_max(const struct snd_pcm_hw_params *p, int n)
208 {
209 if (param_is_interval(n)) {
210 const struct snd_interval *i = param_get_interval(p, n);
211 return i->max;
212 }
213 return 0;
214 }
215
param_set_int(struct snd_pcm_hw_params * p,int n,unsigned int val)216 static void param_set_int(struct snd_pcm_hw_params *p, int n, unsigned int val)
217 {
218 if (param_is_interval(n)) {
219 struct snd_interval *i = param_to_interval(p, n);
220 i->min = val;
221 i->max = val;
222 i->integer = 1;
223 }
224 }
225
param_get_int(struct snd_pcm_hw_params * p,int n)226 static unsigned int param_get_int(struct snd_pcm_hw_params *p, int n)
227 {
228 if (param_is_interval(n)) {
229 struct snd_interval *i = param_to_interval(p, n);
230 if (i->integer)
231 return i->max;
232 }
233 return 0;
234 }
235
param_init(struct snd_pcm_hw_params * p)236 static void param_init(struct snd_pcm_hw_params *p)
237 {
238 int n;
239
240 memset(p, 0, sizeof(*p));
241 for (n = SNDRV_PCM_HW_PARAM_FIRST_MASK;
242 n <= SNDRV_PCM_HW_PARAM_LAST_MASK; n++) {
243 struct snd_mask *m = param_to_mask(p, n);
244 m->bits[0] = ~0;
245 m->bits[1] = ~0;
246 }
247 for (n = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
248 n <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; n++) {
249 struct snd_interval *i = param_to_interval(p, n);
250 i->min = 0;
251 i->max = ~0;
252 }
253 p->rmask = ~0U;
254 p->cmask = 0;
255 p->info = ~0U;
256 }
257
pcm_format_to_alsa(enum pcm_format format)258 static unsigned int pcm_format_to_alsa(enum pcm_format format)
259 {
260 switch (format) {
261
262 case PCM_FORMAT_S8:
263 return SNDRV_PCM_FORMAT_S8;
264
265 default:
266 case PCM_FORMAT_S16_LE:
267 return SNDRV_PCM_FORMAT_S16_LE;
268 case PCM_FORMAT_S16_BE:
269 return SNDRV_PCM_FORMAT_S16_BE;
270
271 case PCM_FORMAT_S24_LE:
272 return SNDRV_PCM_FORMAT_S24_LE;
273 case PCM_FORMAT_S24_BE:
274 return SNDRV_PCM_FORMAT_S24_BE;
275
276 case PCM_FORMAT_S24_3LE:
277 return SNDRV_PCM_FORMAT_S24_3LE;
278 case PCM_FORMAT_S24_3BE:
279 return SNDRV_PCM_FORMAT_S24_3BE;
280
281 case PCM_FORMAT_S32_LE:
282 return SNDRV_PCM_FORMAT_S32_LE;
283 case PCM_FORMAT_S32_BE:
284 return SNDRV_PCM_FORMAT_S32_BE;
285
286 case PCM_FORMAT_FLOAT_LE:
287 return SNDRV_PCM_FORMAT_FLOAT_LE;
288 case PCM_FORMAT_FLOAT_BE:
289 return SNDRV_PCM_FORMAT_FLOAT_BE;
290 };
291 }
292
293 #define PCM_ERROR_MAX 128
294
295 /** A PCM handle.
296 * @ingroup libtinyalsa-pcm
297 */
298 struct pcm {
299 /** The PCM's file descriptor */
300 int fd;
301 /** Flags that were passed to @ref pcm_open */
302 unsigned int flags;
303 /** The number of (under/over)runs that have occured */
304 int xruns;
305 /** Size of the buffer */
306 unsigned int buffer_size;
307 /** The boundary for ring buffer pointers */
308 unsigned int boundary;
309 /** Description of the last error that occured */
310 char error[PCM_ERROR_MAX];
311 /** Configuration that was passed to @ref pcm_open */
312 struct pcm_config config;
313 struct snd_pcm_mmap_status *mmap_status;
314 struct snd_pcm_mmap_control *mmap_control;
315 struct snd_pcm_sync_ptr *sync_ptr;
316 void *mmap_buffer;
317 unsigned int noirq_frames_per_msec;
318 /** The delay of the PCM, in terms of frames */
319 long pcm_delay;
320 /** The subdevice corresponding to the PCM */
321 unsigned int subdevice;
322 /** Pointer to the pcm ops, either hw or plugin */
323 const struct pcm_ops *ops;
324 /** Private data for pcm_hw or pcm_plugin */
325 void *data;
326 /** Pointer to the pcm node from snd card definition */
327 struct snd_node *snd_node;
328 };
329
oops(struct pcm * pcm,int e,const char * fmt,...)330 static int oops(struct pcm *pcm, int e, const char *fmt, ...)
331 {
332 va_list ap;
333 int sz;
334
335 va_start(ap, fmt);
336 vsnprintf(pcm->error, PCM_ERROR_MAX, fmt, ap);
337 va_end(ap);
338 sz = strlen(pcm->error);
339
340 if (e)
341 snprintf(pcm->error + sz, PCM_ERROR_MAX - sz,
342 ": %s", strerror(e));
343 return -1;
344 }
345
346 /** Gets the buffer size of the PCM.
347 * @param pcm A PCM handle.
348 * @return The buffer size of the PCM.
349 * @ingroup libtinyalsa-pcm
350 */
pcm_get_buffer_size(const struct pcm * pcm)351 unsigned int pcm_get_buffer_size(const struct pcm *pcm)
352 {
353 return pcm->buffer_size;
354 }
355
356 /** Gets the channel count of the PCM.
357 * @param pcm A PCM handle.
358 * @return The channel count of the PCM.
359 * @ingroup libtinyalsa-pcm
360 */
pcm_get_channels(const struct pcm * pcm)361 unsigned int pcm_get_channels(const struct pcm *pcm)
362 {
363 return pcm->config.channels;
364 }
365
366 /** Gets the PCM configuration.
367 * @param pcm A PCM handle.
368 * @return The PCM configuration.
369 * This function only returns NULL if
370 * @p pcm is NULL.
371 * @ingroup libtinyalsa-pcm
372 * */
pcm_get_config(const struct pcm * pcm)373 const struct pcm_config * pcm_get_config(const struct pcm *pcm)
374 {
375 if (pcm == NULL)
376 return NULL;
377 return &pcm->config;
378 }
379
380 /** Gets the rate of the PCM.
381 * The rate is given in frames per second.
382 * @param pcm A PCM handle.
383 * @return The rate of the PCM.
384 * @ingroup libtinyalsa-pcm
385 */
pcm_get_rate(const struct pcm * pcm)386 unsigned int pcm_get_rate(const struct pcm *pcm)
387 {
388 return pcm->config.rate;
389 }
390
391 /** Gets the format of the PCM.
392 * @param pcm A PCM handle.
393 * @return The format of the PCM.
394 * @ingroup libtinyalsa-pcm
395 */
pcm_get_format(const struct pcm * pcm)396 enum pcm_format pcm_get_format(const struct pcm *pcm)
397 {
398 return pcm->config.format;
399 }
400
401 /** Gets the file descriptor of the PCM.
402 * Useful for extending functionality of the PCM when needed.
403 * @param pcm A PCM handle.
404 * @return The file descriptor of the PCM.
405 * @ingroup libtinyalsa-pcm
406 */
pcm_get_file_descriptor(const struct pcm * pcm)407 int pcm_get_file_descriptor(const struct pcm *pcm)
408 {
409 return pcm->fd;
410 }
411
412 /** Gets the error message for the last error that occured.
413 * If no error occured and this function is called, the results are undefined.
414 * @param pcm A PCM handle.
415 * @return The error message of the last error that occured.
416 * @ingroup libtinyalsa-pcm
417 */
pcm_get_error(const struct pcm * pcm)418 const char* pcm_get_error(const struct pcm *pcm)
419 {
420 return pcm->error;
421 }
422
423 /** Sets the PCM configuration.
424 * @param pcm A PCM handle.
425 * @param config The configuration to use for the
426 * PCM. This parameter may be NULL, in which case
427 * the default configuration is used.
428 * @returns Zero on success, a negative errno value
429 * on failure.
430 * @ingroup libtinyalsa-pcm
431 * */
pcm_set_config(struct pcm * pcm,const struct pcm_config * config)432 int pcm_set_config(struct pcm *pcm, const struct pcm_config *config)
433 {
434 if (pcm == NULL)
435 return -EFAULT;
436 else if (config == NULL) {
437 config = &pcm->config;
438 pcm->config.channels = 2;
439 pcm->config.rate = 48000;
440 pcm->config.period_size = 1024;
441 pcm->config.period_count = 4;
442 pcm->config.format = PCM_FORMAT_S16_LE;
443 pcm->config.start_threshold = config->period_count * config->period_size;
444 pcm->config.stop_threshold = config->period_count * config->period_size;
445 pcm->config.silence_threshold = 0;
446 pcm->config.silence_size = 0;
447 } else
448 pcm->config = *config;
449
450 struct snd_pcm_hw_params params;
451 param_init(¶ms);
452 param_set_mask(¶ms, SNDRV_PCM_HW_PARAM_FORMAT,
453 pcm_format_to_alsa(config->format));
454 param_set_min(¶ms, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, config->period_size);
455 param_set_int(¶ms, SNDRV_PCM_HW_PARAM_CHANNELS,
456 config->channels);
457 param_set_int(¶ms, SNDRV_PCM_HW_PARAM_PERIODS, config->period_count);
458 param_set_int(¶ms, SNDRV_PCM_HW_PARAM_RATE, config->rate);
459
460 if (pcm->flags & PCM_NOIRQ) {
461
462 if (!(pcm->flags & PCM_MMAP)) {
463 oops(pcm, EINVAL, "noirq only currently supported with mmap().");
464 return -EINVAL;
465 }
466
467 params.flags |= SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP;
468 pcm->noirq_frames_per_msec = config->rate / 1000;
469 }
470
471 if (pcm->flags & PCM_MMAP)
472 param_set_mask(¶ms, SNDRV_PCM_HW_PARAM_ACCESS,
473 SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
474 else
475 param_set_mask(¶ms, SNDRV_PCM_HW_PARAM_ACCESS,
476 SNDRV_PCM_ACCESS_RW_INTERLEAVED);
477
478 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_HW_PARAMS, ¶ms)) {
479 int errno_copy = errno;
480 oops(pcm, errno, "cannot set hw params");
481 return -errno_copy;
482 }
483
484 /* get our refined hw_params */
485 pcm->config.period_size = param_get_int(¶ms, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
486 pcm->config.period_count = param_get_int(¶ms, SNDRV_PCM_HW_PARAM_PERIODS);
487 pcm->buffer_size = config->period_count * config->period_size;
488
489 if (pcm->flags & PCM_MMAP) {
490 pcm->mmap_buffer = pcm->ops->mmap(pcm->data, NULL, pcm_frames_to_bytes(pcm, pcm->buffer_size),
491 PROT_READ | PROT_WRITE, MAP_SHARED, 0);
492 if (pcm->mmap_buffer == MAP_FAILED) {
493 int errno_copy = errno;
494 oops(pcm, errno, "failed to mmap buffer %d bytes\n",
495 pcm_frames_to_bytes(pcm, pcm->buffer_size));
496 return -errno_copy;
497 }
498 }
499
500 struct snd_pcm_sw_params sparams;
501 memset(&sparams, 0, sizeof(sparams));
502 sparams.tstamp_mode = SNDRV_PCM_TSTAMP_ENABLE;
503 sparams.period_step = 1;
504 sparams.avail_min = config->period_size;
505
506 if (!config->start_threshold) {
507 if (pcm->flags & PCM_IN)
508 pcm->config.start_threshold = sparams.start_threshold = 1;
509 else
510 pcm->config.start_threshold = sparams.start_threshold =
511 config->period_count * config->period_size / 2;
512 } else
513 sparams.start_threshold = config->start_threshold;
514
515 /* pick a high stop threshold - todo: does this need further tuning */
516 if (!config->stop_threshold) {
517 if (pcm->flags & PCM_IN)
518 pcm->config.stop_threshold = sparams.stop_threshold =
519 config->period_count * config->period_size * 10;
520 else
521 pcm->config.stop_threshold = sparams.stop_threshold =
522 config->period_count * config->period_size;
523 }
524 else
525 sparams.stop_threshold = config->stop_threshold;
526
527 sparams.xfer_align = config->period_size / 2; /* needed for old kernels */
528 sparams.silence_size = config->silence_size;
529 sparams.silence_threshold = config->silence_threshold;
530 pcm->boundary = sparams.boundary = pcm->buffer_size;
531
532 while (pcm->boundary * 2 <= INT_MAX - pcm->buffer_size)
533 pcm->boundary *= 2;
534
535 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
536 int errno_copy = errno;
537 oops(pcm, errno, "cannot set sw params");
538 return -errno_copy;
539 }
540
541 return 0;
542 }
543
544 /** Gets the subdevice on which the pcm has been opened.
545 * @param pcm A PCM handle.
546 * @return The subdevice on which the pcm has been opened */
pcm_get_subdevice(const struct pcm * pcm)547 unsigned int pcm_get_subdevice(const struct pcm *pcm)
548 {
549 return pcm->subdevice;
550 }
551
552 /** Determines the number of bits occupied by a @ref pcm_format.
553 * @param format A PCM format.
554 * @return The number of bits associated with @p format
555 * @ingroup libtinyalsa-pcm
556 */
pcm_format_to_bits(enum pcm_format format)557 unsigned int pcm_format_to_bits(enum pcm_format format)
558 {
559 switch (format) {
560 case PCM_FORMAT_S32_LE:
561 case PCM_FORMAT_S32_BE:
562 case PCM_FORMAT_S24_LE:
563 case PCM_FORMAT_S24_BE:
564 case PCM_FORMAT_FLOAT_LE:
565 case PCM_FORMAT_FLOAT_BE:
566 return 32;
567 case PCM_FORMAT_S24_3LE:
568 case PCM_FORMAT_S24_3BE:
569 return 24;
570 default:
571 case PCM_FORMAT_S16_LE:
572 case PCM_FORMAT_S16_BE:
573 return 16;
574 case PCM_FORMAT_S8:
575 return 8;
576 };
577 }
578
579 /** Determines how many frames of a PCM can fit into a number of bytes.
580 * @param pcm A PCM handle.
581 * @param bytes The number of bytes.
582 * @return The number of frames that may fit into @p bytes
583 * @ingroup libtinyalsa-pcm
584 */
pcm_bytes_to_frames(const struct pcm * pcm,unsigned int bytes)585 unsigned int pcm_bytes_to_frames(const struct pcm *pcm, unsigned int bytes)
586 {
587 return bytes / (pcm->config.channels *
588 (pcm_format_to_bits(pcm->config.format) >> 3));
589 }
590
591 /** Determines how many bytes are occupied by a number of frames of a PCM.
592 * @param pcm A PCM handle.
593 * @param frames The number of frames of a PCM.
594 * @return The bytes occupied by @p frames.
595 * @ingroup libtinyalsa-pcm
596 */
pcm_frames_to_bytes(const struct pcm * pcm,unsigned int frames)597 unsigned int pcm_frames_to_bytes(const struct pcm *pcm, unsigned int frames)
598 {
599 return frames * pcm->config.channels *
600 (pcm_format_to_bits(pcm->config.format) >> 3);
601 }
602
pcm_sync_ptr(struct pcm * pcm,int flags)603 static int pcm_sync_ptr(struct pcm *pcm, int flags)
604 {
605 if (pcm->sync_ptr == NULL) {
606 /* status and control are mmaped */
607
608 if (flags & SNDRV_PCM_SYNC_PTR_HWSYNC) {
609 if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_HWSYNC) == -1) {
610 oops(pcm, errno, "failed to sync hardware pointer");
611 return -1;
612 }
613 }
614 } else {
615 pcm->sync_ptr->flags = flags;
616 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_SYNC_PTR,
617 pcm->sync_ptr) < 0) {
618 oops(pcm, errno, "failed to sync mmap ptr");
619 return -1;
620 }
621 }
622
623 return 0;
624 }
625
pcm_state(struct pcm * pcm)626 int pcm_state(struct pcm *pcm)
627 {
628 // Update the state only. Do not sync HW sync.
629 int err = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL | SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
630 if (err < 0)
631 return err;
632
633 return pcm->mmap_status->state;
634 }
635
pcm_hw_mmap_status(struct pcm * pcm)636 static int pcm_hw_mmap_status(struct pcm *pcm)
637 {
638 if (pcm->sync_ptr)
639 return 0;
640
641 int page_size = sysconf(_SC_PAGE_SIZE);
642 pcm->mmap_status = pcm->ops->mmap(pcm->data, NULL, page_size, PROT_READ, MAP_SHARED,
643 SNDRV_PCM_MMAP_OFFSET_STATUS);
644 if (pcm->mmap_status == MAP_FAILED)
645 pcm->mmap_status = NULL;
646 if (!pcm->mmap_status)
647 goto mmap_error;
648
649 pcm->mmap_control = pcm->ops->mmap(pcm->data, NULL, page_size, PROT_READ | PROT_WRITE,
650 MAP_SHARED, SNDRV_PCM_MMAP_OFFSET_CONTROL);
651 if (pcm->mmap_control == MAP_FAILED)
652 pcm->mmap_control = NULL;
653 if (!pcm->mmap_control) {
654 pcm->ops->munmap(pcm->data, pcm->mmap_status, page_size);
655 pcm->mmap_status = NULL;
656 goto mmap_error;
657 }
658
659 return 0;
660
661 mmap_error:
662
663 pcm->sync_ptr = calloc(1, sizeof(*pcm->sync_ptr));
664 if (!pcm->sync_ptr)
665 return -ENOMEM;
666 pcm->mmap_status = &pcm->sync_ptr->s.status;
667 pcm->mmap_control = &pcm->sync_ptr->c.control;
668
669 return 0;
670 }
671
pcm_hw_munmap_status(struct pcm * pcm)672 static void pcm_hw_munmap_status(struct pcm *pcm) {
673 if (pcm->sync_ptr) {
674 free(pcm->sync_ptr);
675 pcm->sync_ptr = NULL;
676 } else {
677 int page_size = sysconf(_SC_PAGE_SIZE);
678 if (pcm->mmap_status)
679 pcm->ops->munmap(pcm->data, pcm->mmap_status, page_size);
680 if (pcm->mmap_control)
681 pcm->ops->munmap(pcm->data, pcm->mmap_control, page_size);
682 }
683 pcm->mmap_status = NULL;
684 pcm->mmap_control = NULL;
685 }
686
687 static struct pcm bad_pcm = {
688 .fd = -1,
689 };
690
691 /** Gets the hardware parameters of a PCM, without created a PCM handle.
692 * @param card The card of the PCM.
693 * The default card is zero.
694 * @param device The device of the PCM.
695 * The default device is zero.
696 * @param flags Specifies whether the PCM is an input or output.
697 * May be one of the following:
698 * - @ref PCM_IN
699 * - @ref PCM_OUT
700 * @return On success, the hardware parameters of the PCM; on failure, NULL.
701 * @ingroup libtinyalsa-pcm
702 */
pcm_params_get(unsigned int card,unsigned int device,unsigned int flags)703 struct pcm_params *pcm_params_get(unsigned int card, unsigned int device,
704 unsigned int flags)
705 {
706 struct snd_pcm_hw_params *params;
707 void *snd_node = NULL, *data;
708 const struct pcm_ops *ops;
709 int fd;
710
711 ops = &hw_ops;
712 fd = ops->open(card, device, flags, &data, snd_node);
713
714 #ifdef TINYALSA_USES_PLUGINS
715 if (fd < 0) {
716 int pcm_type;
717 snd_node = snd_utils_open_pcm(card, device);
718 pcm_type = snd_utils_get_node_type(snd_node);
719 if (!snd_node || pcm_type != SND_NODE_TYPE_PLUGIN) {
720 fprintf(stderr, "no device (hw/plugin) for card(%u), device(%u)",
721 card, device);
722 goto err_open;
723 }
724 ops = &plug_ops;
725 fd = ops->open(card, device, flags, &data, snd_node);
726 }
727 #endif
728 if (fd < 0) {
729 fprintf(stderr, "cannot open card(%d) device (%d): %s\n",
730 card, device, strerror(errno));
731 goto err_open;
732 }
733
734 params = calloc(1, sizeof(struct snd_pcm_hw_params));
735 if (!params)
736 goto err_calloc;
737
738 param_init(params);
739 if (ops->ioctl(data, SNDRV_PCM_IOCTL_HW_REFINE, params)) {
740 fprintf(stderr, "SNDRV_PCM_IOCTL_HW_REFINE error (%d)\n", errno);
741 goto err_hw_refine;
742 }
743
744 #ifdef TINYALSA_USES_PLUGINS
745 if (snd_node)
746 snd_utils_close_dev_node(snd_node);
747 #endif
748 ops->close(data);
749
750 return (struct pcm_params *)params;
751
752 err_hw_refine:
753 free(params);
754 err_calloc:
755 #ifdef TINYALSA_USES_PLUGINS
756 if (snd_node)
757 snd_utils_close_dev_node(snd_node);
758 #endif
759 ops->close(data);
760 err_open:
761 return NULL;
762 }
763
764 /** Frees the hardware parameters returned by @ref pcm_params_get.
765 * @param pcm_params Hardware parameters of a PCM.
766 * May be NULL.
767 * @ingroup libtinyalsa-pcm
768 */
pcm_params_free(struct pcm_params * pcm_params)769 void pcm_params_free(struct pcm_params *pcm_params)
770 {
771 struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
772
773 if (params)
774 free(params);
775 }
776
pcm_param_to_alsa(enum pcm_param param)777 static int pcm_param_to_alsa(enum pcm_param param)
778 {
779 switch (param) {
780 case PCM_PARAM_ACCESS:
781 return SNDRV_PCM_HW_PARAM_ACCESS;
782 case PCM_PARAM_FORMAT:
783 return SNDRV_PCM_HW_PARAM_FORMAT;
784 case PCM_PARAM_SUBFORMAT:
785 return SNDRV_PCM_HW_PARAM_SUBFORMAT;
786 case PCM_PARAM_SAMPLE_BITS:
787 return SNDRV_PCM_HW_PARAM_SAMPLE_BITS;
788 break;
789 case PCM_PARAM_FRAME_BITS:
790 return SNDRV_PCM_HW_PARAM_FRAME_BITS;
791 break;
792 case PCM_PARAM_CHANNELS:
793 return SNDRV_PCM_HW_PARAM_CHANNELS;
794 break;
795 case PCM_PARAM_RATE:
796 return SNDRV_PCM_HW_PARAM_RATE;
797 break;
798 case PCM_PARAM_PERIOD_TIME:
799 return SNDRV_PCM_HW_PARAM_PERIOD_TIME;
800 break;
801 case PCM_PARAM_PERIOD_SIZE:
802 return SNDRV_PCM_HW_PARAM_PERIOD_SIZE;
803 break;
804 case PCM_PARAM_PERIOD_BYTES:
805 return SNDRV_PCM_HW_PARAM_PERIOD_BYTES;
806 break;
807 case PCM_PARAM_PERIODS:
808 return SNDRV_PCM_HW_PARAM_PERIODS;
809 break;
810 case PCM_PARAM_BUFFER_TIME:
811 return SNDRV_PCM_HW_PARAM_BUFFER_TIME;
812 break;
813 case PCM_PARAM_BUFFER_SIZE:
814 return SNDRV_PCM_HW_PARAM_BUFFER_SIZE;
815 break;
816 case PCM_PARAM_BUFFER_BYTES:
817 return SNDRV_PCM_HW_PARAM_BUFFER_BYTES;
818 break;
819 case PCM_PARAM_TICK_TIME:
820 return SNDRV_PCM_HW_PARAM_TICK_TIME;
821 break;
822
823 default:
824 return -1;
825 }
826 }
827
828 /** Gets a mask from a PCM's hardware parameters.
829 * @param pcm_params A PCM's hardware parameters.
830 * @param param The parameter to get.
831 * @return If @p pcm_params is NULL or @p param is not a mask, NULL is returned.
832 * Otherwise, the mask associated with @p param is returned.
833 * @ingroup libtinyalsa-pcm
834 */
pcm_params_get_mask(const struct pcm_params * pcm_params,enum pcm_param param)835 const struct pcm_mask *pcm_params_get_mask(const struct pcm_params *pcm_params,
836 enum pcm_param param)
837 {
838 int p;
839 struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
840 if (params == NULL) {
841 return NULL;
842 }
843
844 p = pcm_param_to_alsa(param);
845 if (p < 0 || !param_is_mask(p)) {
846 return NULL;
847 }
848
849 return (const struct pcm_mask *)param_to_mask(params, p);
850 }
851
852 /** Get the minimum of a specified PCM parameter.
853 * @param pcm_params A PCM parameters structure.
854 * @param param The specified parameter to get the minimum of.
855 * @returns On success, the parameter minimum.
856 * On failure, zero.
857 */
pcm_params_get_min(const struct pcm_params * pcm_params,enum pcm_param param)858 unsigned int pcm_params_get_min(const struct pcm_params *pcm_params,
859 enum pcm_param param)
860 {
861 struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
862 int p;
863
864 if (!params)
865 return 0;
866
867 p = pcm_param_to_alsa(param);
868 if (p < 0)
869 return 0;
870
871 return param_get_min(params, p);
872 }
873
874 /** Get the maximum of a specified PCM parameter.
875 * @param pcm_params A PCM parameters structure.
876 * @param param The specified parameter to get the maximum of.
877 * @returns On success, the parameter maximum.
878 * On failure, zero.
879 */
pcm_params_get_max(const struct pcm_params * pcm_params,enum pcm_param param)880 unsigned int pcm_params_get_max(const struct pcm_params *pcm_params,
881 enum pcm_param param)
882 {
883 const struct snd_pcm_hw_params *params = (const struct snd_pcm_hw_params *)pcm_params;
884 int p;
885
886 if (!params)
887 return 0;
888
889 p = pcm_param_to_alsa(param);
890 if (p < 0)
891 return 0;
892
893 return param_get_max(params, p);
894 }
895
pcm_mask_test(const struct pcm_mask * m,unsigned int index)896 static int pcm_mask_test(const struct pcm_mask *m, unsigned int index)
897 {
898 const unsigned int bitshift = 5; /* for 32 bit integer */
899 const unsigned int bitmask = (1 << bitshift) - 1;
900 unsigned int element;
901
902 element = index >> bitshift;
903 if (element >= ARRAY_SIZE(m->bits))
904 return 0; /* for safety, but should never occur */
905 return (m->bits[element] >> (index & bitmask)) & 1;
906 }
907
pcm_mask_to_string(const struct pcm_mask * m,char * string,unsigned int size,char * mask_name,const char * const * bit_array_name,size_t bit_array_size)908 static int pcm_mask_to_string(const struct pcm_mask *m, char *string, unsigned int size,
909 char *mask_name,
910 const char * const *bit_array_name, size_t bit_array_size)
911 {
912 unsigned int i;
913 unsigned int offset = 0;
914
915 if (m == NULL)
916 return 0;
917 if (bit_array_size < 32) {
918 STRLOG(string, offset, size, "%12s:\t%#08x\n", mask_name, m->bits[0]);
919 } else { /* spans two or more bitfields, print with an array index */
920 for (i = 0; i < (bit_array_size + 31) >> 5; ++i) {
921 STRLOG(string, offset, size, "%9s[%d]:\t%#08x\n",
922 mask_name, i, m->bits[i]);
923 }
924 }
925 for (i = 0; i < bit_array_size; ++i) {
926 if (pcm_mask_test(m, i)) {
927 STRLOG(string, offset, size, "%12s \t%s\n", "", bit_array_name[i]);
928 }
929 }
930 return offset;
931 }
932
pcm_params_to_string(struct pcm_params * params,char * string,unsigned int size)933 int pcm_params_to_string(struct pcm_params *params, char *string, unsigned int size)
934 {
935 const struct pcm_mask *m;
936 unsigned int min, max;
937 unsigned int clipoffset, offset;
938
939 m = pcm_params_get_mask(params, PCM_PARAM_ACCESS);
940 offset = pcm_mask_to_string(m, string, size,
941 "Access", access_lookup, ARRAY_SIZE(access_lookup));
942 m = pcm_params_get_mask(params, PCM_PARAM_FORMAT);
943 clipoffset = offset > size ? size : offset;
944 offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
945 "Format", format_lookup, ARRAY_SIZE(format_lookup));
946 m = pcm_params_get_mask(params, PCM_PARAM_SUBFORMAT);
947 clipoffset = offset > size ? size : offset;
948 offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
949 "Subformat", subformat_lookup, ARRAY_SIZE(subformat_lookup));
950 min = pcm_params_get_min(params, PCM_PARAM_RATE);
951 max = pcm_params_get_max(params, PCM_PARAM_RATE);
952 STRLOG(string, offset, size, " Rate:\tmin=%uHz\tmax=%uHz\n", min, max);
953 min = pcm_params_get_min(params, PCM_PARAM_CHANNELS);
954 max = pcm_params_get_max(params, PCM_PARAM_CHANNELS);
955 STRLOG(string, offset, size, " Channels:\tmin=%u\t\tmax=%u\n", min, max);
956 min = pcm_params_get_min(params, PCM_PARAM_SAMPLE_BITS);
957 max = pcm_params_get_max(params, PCM_PARAM_SAMPLE_BITS);
958 STRLOG(string, offset, size, " Sample bits:\tmin=%u\t\tmax=%u\n", min, max);
959 min = pcm_params_get_min(params, PCM_PARAM_PERIOD_SIZE);
960 max = pcm_params_get_max(params, PCM_PARAM_PERIOD_SIZE);
961 STRLOG(string, offset, size, " Period size:\tmin=%u\t\tmax=%u\n", min, max);
962 min = pcm_params_get_min(params, PCM_PARAM_PERIODS);
963 max = pcm_params_get_max(params, PCM_PARAM_PERIODS);
964 STRLOG(string, offset, size, "Period count:\tmin=%u\t\tmax=%u\n", min, max);
965 return offset;
966 }
967
pcm_params_format_test(struct pcm_params * params,enum pcm_format format)968 int pcm_params_format_test(struct pcm_params *params, enum pcm_format format)
969 {
970 unsigned int alsa_format = pcm_format_to_alsa(format);
971
972 if (alsa_format == SNDRV_PCM_FORMAT_S16_LE && format != PCM_FORMAT_S16_LE)
973 return 0; /* caution: format not recognized is equivalent to S16_LE */
974 return pcm_mask_test(pcm_params_get_mask(params, PCM_PARAM_FORMAT), alsa_format);
975 }
976
977 /** Closes a PCM returned by @ref pcm_open.
978 * @param pcm A PCM returned by @ref pcm_open.
979 * May not be NULL.
980 * @return Always returns zero.
981 * @ingroup libtinyalsa-pcm
982 */
pcm_close(struct pcm * pcm)983 int pcm_close(struct pcm *pcm)
984 {
985 if (pcm == &bad_pcm)
986 return 0;
987
988 pcm_hw_munmap_status(pcm);
989
990 if (pcm->flags & PCM_MMAP) {
991 pcm_stop(pcm);
992 pcm->ops->munmap(pcm->data, pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
993 }
994
995 snd_utils_close_dev_node(pcm->snd_node);
996 pcm->ops->close(pcm->data);
997 pcm->buffer_size = 0;
998 pcm->fd = -1;
999 free(pcm);
1000 return 0;
1001 }
1002
1003 /** Opens a PCM by it's name.
1004 * @param name The name of the PCM.
1005 * The name is given in the format: <i>hw</i>:<b>card</b>,<b>device</b>
1006 * @param flags Specify characteristics and functionality about the pcm.
1007 * May be a bitwise AND of the following:
1008 * - @ref PCM_IN
1009 * - @ref PCM_OUT
1010 * - @ref PCM_MMAP
1011 * - @ref PCM_NOIRQ
1012 * - @ref PCM_MONOTONIC
1013 * @param config The hardware and software parameters to open the PCM with.
1014 * @returns A PCM structure.
1015 * If an error occurs, the pointer of bad_pcm is returned.
1016 * Otherwise, it returns the pointer of PCM object.
1017 * Client code should check that the PCM opened properly by calling @ref pcm_is_ready.
1018 * If @ref pcm_is_ready returns false, check @ref pcm_get_error for more information.
1019 * @ingroup libtinyalsa-pcm
1020 */
pcm_open_by_name(const char * name,unsigned int flags,const struct pcm_config * config)1021 struct pcm *pcm_open_by_name(const char *name,
1022 unsigned int flags,
1023 const struct pcm_config *config)
1024 {
1025 unsigned int card, device;
1026 if (name[0] != 'h' || name[1] != 'w' || name[2] != ':') {
1027 oops(&bad_pcm, 0, "name format is not matched");
1028 return &bad_pcm;
1029 } else if (sscanf(&name[3], "%u,%u", &card, &device) != 2) {
1030 oops(&bad_pcm, 0, "name format is not matched");
1031 return &bad_pcm;
1032 }
1033 return pcm_open(card, device, flags, config);
1034 }
1035
1036 /** Opens a PCM.
1037 * @param card The card that the pcm belongs to.
1038 * The default card is zero.
1039 * @param device The device that the pcm belongs to.
1040 * The default device is zero.
1041 * @param flags Specify characteristics and functionality about the pcm.
1042 * May be a bitwise AND of the following:
1043 * - @ref PCM_IN
1044 * - @ref PCM_OUT
1045 * - @ref PCM_MMAP
1046 * - @ref PCM_NOIRQ
1047 * - @ref PCM_MONOTONIC
1048 * @param config The hardware and software parameters to open the PCM with.
1049 * @returns A PCM structure.
1050 * If an error occurs, the pointer of bad_pcm is returned.
1051 * Otherwise, it returns the pointer of PCM object.
1052 * Client code should check that the PCM opened properly by calling @ref pcm_is_ready.
1053 * If @ref pcm_is_ready returns false, check @ref pcm_get_error for more information.
1054 * @ingroup libtinyalsa-pcm
1055 */
pcm_open(unsigned int card,unsigned int device,unsigned int flags,const struct pcm_config * config)1056 struct pcm *pcm_open(unsigned int card, unsigned int device,
1057 unsigned int flags, const struct pcm_config *config)
1058 {
1059 struct pcm *pcm;
1060 struct snd_pcm_info info;
1061 int rc;
1062
1063 pcm = calloc(1, sizeof(struct pcm));
1064 if (!pcm) {
1065 oops(&bad_pcm, ENOMEM, "can't allocate PCM object");
1066 return &bad_pcm;
1067 }
1068
1069 /* Default to hw_ops, attemp plugin open only if hw (/dev/snd/pcm*) open fails */
1070 pcm->ops = &hw_ops;
1071 pcm->fd = pcm->ops->open(card, device, flags, &pcm->data, NULL);
1072
1073 #ifdef TINYALSA_USES_PLUGINS
1074 if (pcm->fd < 0) {
1075 int pcm_type;
1076 pcm->snd_node = snd_utils_open_pcm(card, device);
1077 pcm_type = snd_utils_get_node_type(pcm->snd_node);
1078 if (!pcm->snd_node || pcm_type != SND_NODE_TYPE_PLUGIN) {
1079 oops(&bad_pcm, ENODEV, "no device (hw/plugin) for card(%u), device(%u)",
1080 card, device);
1081 goto fail_close_dev_node;
1082 }
1083 pcm->ops = &plug_ops;
1084 pcm->fd = pcm->ops->open(card, device, flags, &pcm->data, pcm->snd_node);
1085 }
1086 #endif
1087 if (pcm->fd < 0) {
1088 oops(&bad_pcm, errno, "cannot open device (%u) for card (%u)",
1089 device, card);
1090 goto fail_close_dev_node;
1091 }
1092
1093 pcm->flags = flags;
1094
1095 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_INFO, &info)) {
1096 oops(&bad_pcm, errno, "cannot get info");
1097 goto fail_close;
1098 }
1099 pcm->subdevice = info.subdevice;
1100
1101 if (pcm_set_config(pcm, config) != 0)
1102 goto fail_close;
1103
1104 rc = pcm_hw_mmap_status(pcm);
1105 if (rc < 0) {
1106 oops(&bad_pcm, errno, "mmap status failed");
1107 goto fail;
1108 }
1109
1110 #ifdef SNDRV_PCM_IOCTL_TTSTAMP
1111 if (pcm->flags & PCM_MONOTONIC) {
1112 int arg = SNDRV_PCM_TSTAMP_TYPE_MONOTONIC;
1113 rc = pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_TTSTAMP, &arg);
1114 if (rc < 0) {
1115 oops(&bad_pcm, errno, "cannot set timestamp type");
1116 goto fail;
1117 }
1118 }
1119 #endif
1120
1121 pcm->xruns = 0;
1122 return pcm;
1123
1124 fail:
1125 pcm_hw_munmap_status(pcm);
1126 if (flags & PCM_MMAP)
1127 pcm->ops->munmap(pcm->data, pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
1128 fail_close:
1129 pcm->ops->close(pcm->data);
1130 fail_close_dev_node:
1131 #ifdef TINYALSA_USES_PLUGINS
1132 if (pcm->snd_node)
1133 snd_utils_close_dev_node(pcm->snd_node);
1134 #endif
1135 free(pcm);
1136 return &bad_pcm;
1137 }
1138
1139 /** Checks if a PCM file has been opened without error.
1140 * @param pcm A PCM handle.
1141 * May be NULL.
1142 * @return If a PCM's file descriptor is not valid or the pointer is NULL, it returns zero.
1143 * Otherwise, the function returns one.
1144 * @ingroup libtinyalsa-pcm
1145 */
pcm_is_ready(const struct pcm * pcm)1146 int pcm_is_ready(const struct pcm *pcm)
1147 {
1148 if (pcm != NULL) {
1149 return pcm->fd >= 0;
1150 }
1151 return 0;
1152 }
1153
1154 /** Links two PCMs.
1155 * After this function is called, the two PCMs will prepare, start and stop in sync (at the same time).
1156 * If an error occurs, the error message will be written to @p pcm1.
1157 * @param pcm1 A PCM handle.
1158 * @param pcm2 Another PCM handle.
1159 * @return On success, zero; on failure, a negative number.
1160 * @ingroup libtinyalsa-pcm
1161 */
pcm_link(struct pcm * pcm1,struct pcm * pcm2)1162 int pcm_link(struct pcm *pcm1, struct pcm *pcm2)
1163 {
1164 int err = ioctl(pcm1->fd, SNDRV_PCM_IOCTL_LINK, pcm2->fd);
1165 if (err == -1) {
1166 return oops(pcm1, errno, "cannot link PCM");
1167 }
1168 return 0;
1169 }
1170
1171 /** Unlinks a PCM.
1172 * @see @ref pcm_link
1173 * @param pcm A PCM handle.
1174 * @return On success, zero; on failure, a negative number.
1175 * @ingroup libtinyalsa-pcm
1176 */
pcm_unlink(struct pcm * pcm)1177 int pcm_unlink(struct pcm *pcm)
1178 {
1179 int err = ioctl(pcm->fd, SNDRV_PCM_IOCTL_UNLINK);
1180 if (err == -1) {
1181 return oops(pcm, errno, "cannot unlink PCM");
1182 }
1183 return 0;
1184 }
1185
1186 /** Prepares a PCM, if it has not been prepared already.
1187 * @param pcm A PCM handle.
1188 * @return On success, zero; on failure, a negative number.
1189 * @ingroup libtinyalsa-pcm
1190 */
pcm_prepare(struct pcm * pcm)1191 int pcm_prepare(struct pcm *pcm)
1192 {
1193 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_PREPARE) < 0)
1194 return oops(pcm, errno, "cannot prepare channel");
1195
1196 /* get appl_ptr and avail_min from kernel */
1197 pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
1198
1199 return 0;
1200 }
1201
1202 /** Starts a PCM.
1203 * @param pcm A PCM handle.
1204 * @return On success, zero; on failure, a negative number.
1205 * @ingroup libtinyalsa-pcm
1206 */
pcm_start(struct pcm * pcm)1207 int pcm_start(struct pcm *pcm)
1208 {
1209 if (pcm_state(pcm) == PCM_STATE_SETUP && pcm_prepare(pcm) != 0) {
1210 return -1;
1211 }
1212
1213 /* set appl_ptr and avail_min in kernel */
1214 if (pcm_sync_ptr(pcm, 0) < 0)
1215 return -1;
1216
1217 if (pcm->mmap_status->state != PCM_STATE_RUNNING) {
1218 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_START) < 0)
1219 return oops(pcm, errno, "cannot start channel");
1220 }
1221
1222 return 0;
1223 }
1224
1225 /** Stops a PCM.
1226 * @param pcm A PCM handle.
1227 * @return On success, zero; on failure, a negative number.
1228 * @ingroup libtinyalsa-pcm
1229 */
pcm_stop(struct pcm * pcm)1230 int pcm_stop(struct pcm *pcm)
1231 {
1232 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_DROP) < 0)
1233 return oops(pcm, errno, "cannot stop channel");
1234
1235 return 0;
1236 }
1237
pcm_mmap_playback_avail(struct pcm * pcm)1238 static inline int pcm_mmap_playback_avail(struct pcm *pcm)
1239 {
1240 int avail;
1241
1242 avail = pcm->mmap_status->hw_ptr + pcm->buffer_size - pcm->mmap_control->appl_ptr;
1243
1244 if (avail < 0)
1245 avail += pcm->boundary;
1246 else if (avail >= (int)pcm->boundary)
1247 avail -= pcm->boundary;
1248
1249 return avail;
1250 }
1251
pcm_mmap_capture_avail(struct pcm * pcm)1252 static inline int pcm_mmap_capture_avail(struct pcm *pcm)
1253 {
1254 int avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
1255 if (avail < 0)
1256 avail += pcm->boundary;
1257 return avail;
1258 }
1259
pcm_mmap_avail(struct pcm * pcm)1260 int pcm_mmap_avail(struct pcm *pcm)
1261 {
1262 pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
1263 if (pcm->flags & PCM_IN)
1264 return pcm_mmap_capture_avail(pcm);
1265 else
1266 return pcm_mmap_playback_avail(pcm);
1267 }
1268
pcm_mmap_appl_forward(struct pcm * pcm,int frames)1269 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
1270 {
1271 unsigned int appl_ptr = pcm->mmap_control->appl_ptr;
1272 appl_ptr += frames;
1273
1274 /* check for boundary wrap */
1275 if (appl_ptr > pcm->boundary)
1276 appl_ptr -= pcm->boundary;
1277 pcm->mmap_control->appl_ptr = appl_ptr;
1278 }
1279
pcm_mmap_begin(struct pcm * pcm,void ** areas,unsigned int * offset,unsigned int * frames)1280 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
1281 unsigned int *frames)
1282 {
1283 unsigned int continuous, copy_frames, avail;
1284
1285 /* return the mmap buffer */
1286 *areas = pcm->mmap_buffer;
1287
1288 /* and the application offset in frames */
1289 *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
1290
1291 avail = pcm_mmap_avail(pcm);
1292 if (avail > pcm->buffer_size)
1293 avail = pcm->buffer_size;
1294 continuous = pcm->buffer_size - *offset;
1295
1296 /* we can only copy frames if the are availabale and continuos */
1297 copy_frames = *frames;
1298 if (copy_frames > avail)
1299 copy_frames = avail;
1300 if (copy_frames > continuous)
1301 copy_frames = continuous;
1302 *frames = copy_frames;
1303
1304 return 0;
1305 }
1306
pcm_areas_copy(struct pcm * pcm,unsigned int pcm_offset,char * buf,unsigned int src_offset,unsigned int frames)1307 static int pcm_areas_copy(struct pcm *pcm, unsigned int pcm_offset,
1308 char *buf, unsigned int src_offset,
1309 unsigned int frames)
1310 {
1311 int size_bytes = pcm_frames_to_bytes(pcm, frames);
1312 int pcm_offset_bytes = pcm_frames_to_bytes(pcm, pcm_offset);
1313 int src_offset_bytes = pcm_frames_to_bytes(pcm, src_offset);
1314
1315 /* interleaved only atm */
1316 if (pcm->flags & PCM_IN)
1317 memcpy(buf + src_offset_bytes,
1318 (char*)pcm->mmap_buffer + pcm_offset_bytes,
1319 size_bytes);
1320 else
1321 memcpy((char*)pcm->mmap_buffer + pcm_offset_bytes,
1322 buf + src_offset_bytes,
1323 size_bytes);
1324 return 0;
1325 }
1326
pcm_mmap_commit(struct pcm * pcm,unsigned int offset,unsigned int frames)1327 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset, unsigned int frames)
1328 {
1329 int ret;
1330
1331 /* not used */
1332 (void) offset;
1333
1334 /* update the application pointer in userspace and kernel */
1335 pcm_mmap_appl_forward(pcm, frames);
1336 ret = pcm_sync_ptr(pcm, 0);
1337 if (ret != 0){
1338 printf("%d\n", ret);
1339 return ret;
1340 }
1341
1342 return frames;
1343 }
1344
pcm_mmap_transfer_areas(struct pcm * pcm,char * buf,unsigned int offset,unsigned int size)1345 static int pcm_mmap_transfer_areas(struct pcm *pcm, char *buf,
1346 unsigned int offset, unsigned int size)
1347 {
1348 void *pcm_areas;
1349 int commit;
1350 unsigned int pcm_offset, frames, count = 0;
1351
1352 while (pcm_mmap_avail(pcm) && size) {
1353 frames = size;
1354 pcm_mmap_begin(pcm, &pcm_areas, &pcm_offset, &frames);
1355 pcm_areas_copy(pcm, pcm_offset, buf, offset, frames);
1356 commit = pcm_mmap_commit(pcm, pcm_offset, frames);
1357 if (commit < 0) {
1358 oops(pcm, commit, "failed to commit %d frames\n", frames);
1359 return commit;
1360 }
1361
1362 offset += commit;
1363 count += commit;
1364 size -= commit;
1365 }
1366 return count;
1367 }
1368
pcm_get_poll_fd(struct pcm * pcm)1369 int pcm_get_poll_fd(struct pcm *pcm)
1370 {
1371 return pcm->fd;
1372 }
1373
pcm_avail_update(struct pcm * pcm)1374 int pcm_avail_update(struct pcm *pcm)
1375 {
1376 pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
1377 return pcm_mmap_avail(pcm);
1378 }
1379
1380 /** Returns available frames in pcm buffer and corresponding time stamp.
1381 * The clock is CLOCK_MONOTONIC if flag @ref PCM_MONOTONIC was specified in @ref pcm_open,
1382 * otherwise the clock is CLOCK_REALTIME.
1383 * For an input stream, frames available are frames ready for the application to read.
1384 * For an output stream, frames available are the number of empty frames available for the application to write.
1385 * @param pcm A PCM handle.
1386 * @param avail The number of available frames
1387 * @param tstamp The timestamp
1388 * @return On success, zero is returned; on failure, negative one.
1389 */
pcm_get_htimestamp(struct pcm * pcm,unsigned int * avail,struct timespec * tstamp)1390 int pcm_get_htimestamp(struct pcm *pcm, unsigned int *avail,
1391 struct timespec *tstamp)
1392 {
1393 int checking;
1394 int tmp;
1395
1396 if (!pcm_is_ready(pcm))
1397 return -1;
1398
1399 checking = 0;
1400
1401 again:
1402
1403 tmp = pcm_avail_update(pcm);
1404 if (tmp < 0)
1405 return tmp; /* error */
1406
1407 if (checking && (unsigned int) tmp == *avail)
1408 return 0;
1409
1410 *avail = (unsigned int) tmp;
1411 *tstamp = pcm->mmap_status->tstamp;
1412
1413 /*
1414 * When status is mmaped, get avail again to ensure
1415 * valid timestamp.
1416 */
1417 if (!pcm->sync_ptr) {
1418 checking = 1;
1419 goto again;
1420 }
1421
1422 /* SYNC_PTR ioctl was used, no need to check avail */
1423 return 0;
1424 }
1425
1426 /** Waits for frames to be available for read or write operations.
1427 * @param pcm A PCM handle.
1428 * @param timeout The maximum amount of time to wait for, in terms of milliseconds.
1429 * @returns If frames became available, one is returned.
1430 * If a timeout occured, zero is returned.
1431 * If an error occured, a negative number is returned.
1432 * @ingroup libtinyalsa-pcm
1433 */
pcm_wait(struct pcm * pcm,int timeout)1434 int pcm_wait(struct pcm *pcm, int timeout)
1435 {
1436 struct pollfd pfd;
1437 int err;
1438
1439 pfd.fd = pcm->fd;
1440 pfd.events = POLLIN | POLLOUT | POLLERR | POLLNVAL;
1441
1442 do {
1443 /* let's wait for avail or timeout */
1444 err = pcm->ops->poll(pcm->data, &pfd, 1, timeout);
1445 if (err < 0)
1446 return -errno;
1447
1448 /* timeout ? */
1449 if (err == 0)
1450 return 0;
1451
1452 /* have we been interrupted ? */
1453 if (errno == -EINTR)
1454 continue;
1455
1456 /* check for any errors */
1457 if (pfd.revents & (POLLERR | POLLNVAL)) {
1458 switch (pcm_state(pcm)) {
1459 case PCM_STATE_XRUN:
1460 return -EPIPE;
1461 case PCM_STATE_SUSPENDED:
1462 return -ESTRPIPE;
1463 case PCM_STATE_DISCONNECTED:
1464 return -ENODEV;
1465 default:
1466 return -EIO;
1467 }
1468 }
1469 /* poll again if fd not ready for IO */
1470 } while (!(pfd.revents & (POLLIN | POLLOUT)));
1471
1472 return 1;
1473 }
1474
1475 /*
1476 * Transfer data to/from mmaped buffer. This imitates the
1477 * behavior of read/write system calls.
1478 *
1479 * However, this doesn't seems to offer any advantage over
1480 * the read/write syscalls. Should it be removed?
1481 */
pcm_mmap_transfer(struct pcm * pcm,void * buffer,unsigned int frames)1482 int pcm_mmap_transfer(struct pcm *pcm, void *buffer, unsigned int frames)
1483 {
1484 int is_playback;
1485
1486 int state;
1487 unsigned int avail;
1488 unsigned int user_offset;
1489
1490 int err;
1491 int tmp;
1492
1493 is_playback = !(pcm->flags & PCM_IN);
1494
1495 if (frames == 0)
1496 return 0;
1497
1498 /* update hardware pointer and get state */
1499 err = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC |
1500 SNDRV_PCM_SYNC_PTR_APPL |
1501 SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
1502 if (err == -1)
1503 return -1;
1504 state = pcm->mmap_status->state;
1505
1506 /*
1507 * If frames < start_threshold, wait indefinitely.
1508 * Another thread may start capture
1509 */
1510 if (!is_playback && state == PCM_STATE_PREPARED &&
1511 frames >= pcm->config.start_threshold) {
1512 err = pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_START);
1513 if (err == -1)
1514 return -1;
1515 /* state = PCM_STATE_RUNNING */
1516 }
1517
1518 avail = pcm_mmap_avail(pcm);
1519 user_offset = 0;
1520
1521 while (frames) {
1522 if (!avail) {
1523 if (pcm->flags & PCM_NONBLOCK) {
1524 errno = EAGAIN;
1525 break;
1526 }
1527
1528 /* wait for interrupt */
1529 err = pcm_wait(pcm, -1);
1530 if (err < 0) {
1531 errno = -err;
1532 break;
1533 }
1534
1535 /* get hardware pointer */
1536 avail = pcm_avail_update(pcm);
1537 }
1538
1539 tmp = pcm_mmap_transfer_areas(pcm, buffer, user_offset, frames);
1540 if (tmp < 0)
1541 break;
1542
1543 user_offset += tmp;
1544 frames -= tmp;
1545 avail -= tmp;
1546
1547 /* start playback if written >= start_threshold */
1548 if (is_playback && state == PCM_STATE_PREPARED &&
1549 pcm->buffer_size - avail >= pcm->config.start_threshold) {
1550 err = pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_START);
1551 if (err == -1)
1552 break;
1553 }
1554 }
1555
1556 return user_offset ? (int) user_offset : -1;
1557 }
1558
pcm_mmap_write(struct pcm * pcm,const void * data,unsigned int count)1559 int pcm_mmap_write(struct pcm *pcm, const void *data, unsigned int count)
1560 {
1561 if ((~pcm->flags) & (PCM_OUT | PCM_MMAP))
1562 return -EINVAL;
1563
1564 unsigned int frames = pcm_bytes_to_frames(pcm, count);
1565 int res = pcm_writei(pcm, (void *) data, frames);
1566
1567 if (res < 0) {
1568 return res;
1569 }
1570
1571 return (unsigned int) res == frames ? 0 : -EIO;
1572 }
1573
pcm_mmap_read(struct pcm * pcm,void * data,unsigned int count)1574 int pcm_mmap_read(struct pcm *pcm, void *data, unsigned int count)
1575 {
1576 if ((~pcm->flags) & (PCM_IN | PCM_MMAP))
1577 return -EINVAL;
1578
1579 unsigned int frames = pcm_bytes_to_frames(pcm, count);
1580 int res = pcm_readi(pcm, data, frames);
1581
1582 if (res < 0) {
1583 return res;
1584 }
1585
1586 return (unsigned int) res == frames ? 0 : -EIO;
1587 }
1588
1589 /* Returns current read/write position in the mmap buffer with associated time stamp. */
pcm_mmap_get_hw_ptr(struct pcm * pcm,unsigned int * hw_ptr,struct timespec * tstamp)1590 int pcm_mmap_get_hw_ptr(struct pcm* pcm, unsigned int *hw_ptr, struct timespec *tstamp)
1591 {
1592 int rc;
1593
1594 if (pcm == NULL || hw_ptr == NULL || tstamp == NULL)
1595 return oops(pcm, EINVAL, "pcm %p, hw_ptr %p, tstamp %p", pcm, hw_ptr, tstamp);
1596
1597 if (!pcm_is_ready(pcm))
1598 return oops(pcm, errno, "pcm_is_ready failed");
1599
1600 rc = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
1601 if (rc < 0)
1602 return oops(pcm, errno, "pcm_sync_ptr failed");
1603
1604 if (pcm->mmap_status == NULL)
1605 return oops(pcm, EINVAL, "pcm %p, mmap_status is NULL", pcm);
1606
1607 if ((pcm->mmap_status->state != PCM_STATE_RUNNING) &&
1608 (pcm->mmap_status->state != PCM_STATE_DRAINING))
1609 return oops(pcm, ENOSYS, "invalid stream state %d", pcm->mmap_status->state);
1610
1611 *tstamp = pcm->mmap_status->tstamp;
1612 if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
1613 return oops(pcm, errno, "invalid time stamp");
1614
1615 *hw_ptr = pcm->mmap_status->hw_ptr;
1616
1617 return 0;
1618 }
1619
pcm_rw_transfer(struct pcm * pcm,void * data,unsigned int frames)1620 static int pcm_rw_transfer(struct pcm *pcm, void *data, unsigned int frames)
1621 {
1622 int is_playback;
1623
1624 struct snd_xferi transfer;
1625 int res;
1626
1627 is_playback = !(pcm->flags & PCM_IN);
1628
1629 transfer.buf = data;
1630 transfer.frames = frames;
1631 transfer.result = 0;
1632
1633 res = pcm->ops->ioctl(pcm->data, is_playback
1634 ? SNDRV_PCM_IOCTL_WRITEI_FRAMES
1635 : SNDRV_PCM_IOCTL_READI_FRAMES, &transfer);
1636
1637 return res == 0 ? (int) transfer.result : -1;
1638 }
1639
pcm_generic_transfer(struct pcm * pcm,void * data,unsigned int frames)1640 static int pcm_generic_transfer(struct pcm *pcm, void *data,
1641 unsigned int frames)
1642 {
1643 int res;
1644
1645 #if UINT_MAX > TINYALSA_FRAMES_MAX
1646 if (frames > TINYALSA_FRAMES_MAX)
1647 return -EINVAL;
1648 #endif
1649 if (frames > INT_MAX)
1650 return -EINVAL;
1651
1652 if (pcm_state(pcm) == PCM_STATE_SETUP && pcm_prepare(pcm) != 0) {
1653 return -1;
1654 }
1655
1656 again:
1657
1658 if (pcm->flags & PCM_MMAP)
1659 res = pcm_mmap_transfer(pcm, data, frames);
1660 else
1661 res = pcm_rw_transfer(pcm, data, frames);
1662
1663 if (res < 0) {
1664 switch (errno) {
1665 case EPIPE:
1666 pcm->xruns++;
1667 /* fallthrough */
1668 case ESTRPIPE:
1669 /*
1670 * Try to restart if we are allowed to do so.
1671 * Otherwise, return error.
1672 */
1673 if (pcm->flags & PCM_NORESTART || pcm_prepare(pcm))
1674 return -1;
1675 goto again;
1676 case EAGAIN:
1677 if (pcm->flags & PCM_NONBLOCK)
1678 return -1;
1679 /* fallthrough */
1680 default:
1681 return oops(pcm, errno, "cannot read/write stream data");
1682 }
1683 }
1684
1685 return res;
1686 }
1687
1688 /** Writes audio samples to PCM.
1689 * If the PCM has not been started, it is started in this function.
1690 * This function is only valid for PCMs opened with the @ref PCM_OUT flag.
1691 * @param pcm A PCM handle.
1692 * @param data The audio sample array
1693 * @param frame_count The number of frames occupied by the sample array.
1694 * This value should not be greater than @ref TINYALSA_FRAMES_MAX
1695 * or INT_MAX.
1696 * @return On success, this function returns the number of frames written; otherwise, a negative number.
1697 * @ingroup libtinyalsa-pcm
1698 */
pcm_writei(struct pcm * pcm,const void * data,unsigned int frame_count)1699 int pcm_writei(struct pcm *pcm, const void *data, unsigned int frame_count)
1700 {
1701 if (pcm->flags & PCM_IN)
1702 return -EINVAL;
1703
1704 return pcm_generic_transfer(pcm, (void*) data, frame_count);
1705 }
1706
1707 /** Reads audio samples from PCM.
1708 * If the PCM has not been started, it is started in this function.
1709 * This function is only valid for PCMs opened with the @ref PCM_IN flag.
1710 * @param pcm A PCM handle.
1711 * @param data The audio sample array
1712 * @param frame_count The number of frames occupied by the sample array.
1713 * This value should not be greater than @ref TINYALSA_FRAMES_MAX
1714 * or INT_MAX.
1715 * @return On success, this function returns the number of frames written; otherwise, a negative number.
1716 * @ingroup libtinyalsa-pcm
1717 */
pcm_readi(struct pcm * pcm,void * data,unsigned int frame_count)1718 int pcm_readi(struct pcm *pcm, void *data, unsigned int frame_count)
1719 {
1720 if (!(pcm->flags & PCM_IN))
1721 return -EINVAL;
1722
1723 return pcm_generic_transfer(pcm, data, frame_count);
1724 }
1725
1726 /** Writes audio samples to PCM.
1727 * If the PCM has not been started, it is started in this function.
1728 * This function is only valid for PCMs opened with the @ref PCM_OUT flag.
1729 * This function is not valid for PCMs opened with the @ref PCM_MMAP flag.
1730 * @param pcm A PCM handle.
1731 * @param data The audio sample array
1732 * @param count The number of bytes occupied by the sample array.
1733 * @return On success, this function returns zero; otherwise, a negative number.
1734 * @deprecated
1735 * @ingroup libtinyalsa-pcm
1736 */
pcm_write(struct pcm * pcm,const void * data,unsigned int count)1737 int pcm_write(struct pcm *pcm, const void *data, unsigned int count)
1738 {
1739 unsigned int requested_frames = pcm_bytes_to_frames(pcm, count);
1740 int ret = pcm_writei(pcm, data, requested_frames);
1741
1742 if (ret < 0)
1743 return ret;
1744
1745 return ((unsigned int )ret == requested_frames) ? 0 : -EIO;
1746 }
1747
1748 /** Reads audio samples from PCM.
1749 * If the PCM has not been started, it is started in this function.
1750 * This function is only valid for PCMs opened with the @ref PCM_IN flag.
1751 * This function is not valid for PCMs opened with the @ref PCM_MMAP flag.
1752 * @param pcm A PCM handle.
1753 * @param data The audio sample array
1754 * @param count The number of bytes occupied by the sample array.
1755 * @return On success, this function returns zero; otherwise, a negative number.
1756 * @deprecated
1757 * @ingroup libtinyalsa-pcm
1758 */
pcm_read(struct pcm * pcm,void * data,unsigned int count)1759 int pcm_read(struct pcm *pcm, void *data, unsigned int count)
1760 {
1761 unsigned int requested_frames = pcm_bytes_to_frames(pcm, count);
1762 int ret = pcm_readi(pcm, data, requested_frames);
1763
1764 if (ret < 0)
1765 return ret;
1766
1767 return ((unsigned int )ret == requested_frames) ? 0 : -EIO;
1768 }
1769
1770 /** Gets the delay of the PCM, in terms of frames.
1771 * @param pcm A PCM handle.
1772 * @returns On success, the delay of the PCM.
1773 * On failure, a negative number.
1774 * @ingroup libtinyalsa-pcm
1775 */
pcm_get_delay(struct pcm * pcm)1776 long pcm_get_delay(struct pcm *pcm)
1777 {
1778 if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DELAY, &pcm->pcm_delay) < 0)
1779 return -1;
1780
1781 return pcm->pcm_delay;
1782 }
1783
1784 // TODO: Currently in Android, there are some libraries using this function to control the driver.
1785 // We should remove this function as soon as possible.
pcm_ioctl(struct pcm * pcm,int request,...)1786 int pcm_ioctl(struct pcm *pcm, int request, ...)
1787 {
1788 va_list ap;
1789 void * arg;
1790
1791 if (!pcm_is_ready(pcm))
1792 return -1;
1793
1794 va_start(ap, request);
1795 arg = va_arg(ap, void *);
1796 va_end(ap);
1797
1798 // FIXME Does not handle plugins
1799 return ioctl(pcm->fd, request, arg);
1800 }
1801