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 long 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
531 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_SW_PARAMS, &sparams)) {
532 int errno_copy = errno;
533 oops(pcm, errno, "cannot set sw params");
534 return -errno_copy;
535 }
536
537 pcm->boundary = sparams.boundary;
538 return 0;
539 }
540
541 /** Gets the subdevice on which the pcm has been opened.
542 * @param pcm A PCM handle.
543 * @return The subdevice on which the pcm has been opened */
pcm_get_subdevice(const struct pcm * pcm)544 unsigned int pcm_get_subdevice(const struct pcm *pcm)
545 {
546 return pcm->subdevice;
547 }
548
549 /** Determines the number of bits occupied by a @ref pcm_format.
550 * @param format A PCM format.
551 * @return The number of bits associated with @p format
552 * @ingroup libtinyalsa-pcm
553 */
pcm_format_to_bits(enum pcm_format format)554 unsigned int pcm_format_to_bits(enum pcm_format format)
555 {
556 switch (format) {
557 case PCM_FORMAT_S32_LE:
558 case PCM_FORMAT_S32_BE:
559 case PCM_FORMAT_S24_LE:
560 case PCM_FORMAT_S24_BE:
561 case PCM_FORMAT_FLOAT_LE:
562 case PCM_FORMAT_FLOAT_BE:
563 return 32;
564 case PCM_FORMAT_S24_3LE:
565 case PCM_FORMAT_S24_3BE:
566 return 24;
567 default:
568 case PCM_FORMAT_S16_LE:
569 case PCM_FORMAT_S16_BE:
570 return 16;
571 case PCM_FORMAT_S8:
572 return 8;
573 };
574 }
575
576 /** Determines how many frames of a PCM can fit into a number of bytes.
577 * @param pcm A PCM handle.
578 * @param bytes The number of bytes.
579 * @return The number of frames that may fit into @p bytes
580 * @ingroup libtinyalsa-pcm
581 */
pcm_bytes_to_frames(const struct pcm * pcm,unsigned int bytes)582 unsigned int pcm_bytes_to_frames(const struct pcm *pcm, unsigned int bytes)
583 {
584 return bytes / (pcm->config.channels *
585 (pcm_format_to_bits(pcm->config.format) >> 3));
586 }
587
588 /** Determines how many bytes are occupied by a number of frames of a PCM.
589 * @param pcm A PCM handle.
590 * @param frames The number of frames of a PCM.
591 * @return The bytes occupied by @p frames.
592 * @ingroup libtinyalsa-pcm
593 */
pcm_frames_to_bytes(const struct pcm * pcm,unsigned int frames)594 unsigned int pcm_frames_to_bytes(const struct pcm *pcm, unsigned int frames)
595 {
596 return frames * pcm->config.channels *
597 (pcm_format_to_bits(pcm->config.format) >> 3);
598 }
599
pcm_sync_ptr(struct pcm * pcm,int flags)600 static int pcm_sync_ptr(struct pcm *pcm, int flags)
601 {
602 if (pcm->sync_ptr == NULL) {
603 /* status and control are mmapped */
604 if (flags & SNDRV_PCM_SYNC_PTR_HWSYNC) {
605 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_HWSYNC) == -1) {
606 return oops(pcm, errno, "failed to sync hardware pointer");
607 }
608 }
609 } else {
610 pcm->sync_ptr->flags = flags;
611 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_SYNC_PTR,
612 pcm->sync_ptr) < 0) {
613 return oops(pcm, errno, "failed to sync mmap ptr");
614 }
615 }
616
617 return 0;
618 }
619
pcm_state(struct pcm * pcm)620 int pcm_state(struct pcm *pcm)
621 {
622 // Update the state only. Do not sync HW sync.
623 int err = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL | SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
624 if (err < 0)
625 return err;
626
627 return pcm->mmap_status->state;
628 }
629
pcm_hw_mmap_status(struct pcm * pcm)630 static int pcm_hw_mmap_status(struct pcm *pcm)
631 {
632 if (pcm->sync_ptr)
633 return 0;
634
635 int page_size = sysconf(_SC_PAGE_SIZE);
636 pcm->mmap_status = pcm->ops->mmap(pcm->data, NULL, page_size, PROT_READ, MAP_SHARED,
637 SNDRV_PCM_MMAP_OFFSET_STATUS);
638 if (pcm->mmap_status == MAP_FAILED)
639 pcm->mmap_status = NULL;
640 if (!pcm->mmap_status)
641 goto mmap_error;
642
643 pcm->mmap_control = pcm->ops->mmap(pcm->data, NULL, page_size, PROT_READ | PROT_WRITE,
644 MAP_SHARED, SNDRV_PCM_MMAP_OFFSET_CONTROL);
645 if (pcm->mmap_control == MAP_FAILED)
646 pcm->mmap_control = NULL;
647 if (!pcm->mmap_control) {
648 pcm->ops->munmap(pcm->data, pcm->mmap_status, page_size);
649 pcm->mmap_status = NULL;
650 goto mmap_error;
651 }
652
653 return 0;
654
655 mmap_error:
656
657 pcm->sync_ptr = calloc(1, sizeof(*pcm->sync_ptr));
658 if (!pcm->sync_ptr)
659 return -ENOMEM;
660 pcm->mmap_status = &pcm->sync_ptr->s.status;
661 pcm->mmap_control = &pcm->sync_ptr->c.control;
662
663 return 0;
664 }
665
pcm_hw_munmap_status(struct pcm * pcm)666 static void pcm_hw_munmap_status(struct pcm *pcm) {
667 if (pcm->sync_ptr) {
668 free(pcm->sync_ptr);
669 pcm->sync_ptr = NULL;
670 } else {
671 int page_size = sysconf(_SC_PAGE_SIZE);
672 if (pcm->mmap_status)
673 pcm->ops->munmap(pcm->data, pcm->mmap_status, page_size);
674 if (pcm->mmap_control)
675 pcm->ops->munmap(pcm->data, pcm->mmap_control, page_size);
676 }
677 pcm->mmap_status = NULL;
678 pcm->mmap_control = NULL;
679 }
680
681 static struct pcm bad_pcm = {
682 .fd = -1,
683 };
684
685 /** Gets the hardware parameters of a PCM, without created a PCM handle.
686 * @param card The card of the PCM.
687 * The default card is zero.
688 * @param device The device of the PCM.
689 * The default device is zero.
690 * @param flags Specifies whether the PCM is an input or output.
691 * May be one of the following:
692 * - @ref PCM_IN
693 * - @ref PCM_OUT
694 * @return On success, the hardware parameters of the PCM; on failure, NULL.
695 * @ingroup libtinyalsa-pcm
696 */
pcm_params_get(unsigned int card,unsigned int device,unsigned int flags)697 struct pcm_params *pcm_params_get(unsigned int card, unsigned int device,
698 unsigned int flags)
699 {
700 struct snd_pcm_hw_params *params;
701 void *snd_node = NULL, *data;
702 const struct pcm_ops *ops;
703 int fd;
704
705 ops = &hw_ops;
706 fd = ops->open(card, device, flags, &data, snd_node);
707
708 #ifdef TINYALSA_USES_PLUGINS
709 if (fd < 0) {
710 int pcm_type;
711 snd_node = snd_utils_open_pcm(card, device);
712 pcm_type = snd_utils_get_node_type(snd_node);
713 if (!snd_node || pcm_type != SND_NODE_TYPE_PLUGIN) {
714 fprintf(stderr, "no device (hw/plugin) for card(%u), device(%u)",
715 card, device);
716 goto err_open;
717 }
718 ops = &plug_ops;
719 fd = ops->open(card, device, flags, &data, snd_node);
720 }
721 #endif
722 if (fd < 0) {
723 fprintf(stderr, "cannot open card(%d) device (%d): %s\n",
724 card, device, strerror(errno));
725 goto err_open;
726 }
727
728 params = calloc(1, sizeof(struct snd_pcm_hw_params));
729 if (!params)
730 goto err_calloc;
731
732 param_init(params);
733 if (ops->ioctl(data, SNDRV_PCM_IOCTL_HW_REFINE, params)) {
734 fprintf(stderr, "SNDRV_PCM_IOCTL_HW_REFINE error (%d)\n", errno);
735 goto err_hw_refine;
736 }
737
738 #ifdef TINYALSA_USES_PLUGINS
739 if (snd_node)
740 snd_utils_close_dev_node(snd_node);
741 #endif
742 ops->close(data);
743
744 return (struct pcm_params *)params;
745
746 err_hw_refine:
747 free(params);
748 err_calloc:
749 #ifdef TINYALSA_USES_PLUGINS
750 if (snd_node)
751 snd_utils_close_dev_node(snd_node);
752 #endif
753 ops->close(data);
754 err_open:
755 return NULL;
756 }
757
758 /** Frees the hardware parameters returned by @ref pcm_params_get.
759 * @param pcm_params Hardware parameters of a PCM.
760 * May be NULL.
761 * @ingroup libtinyalsa-pcm
762 */
pcm_params_free(struct pcm_params * pcm_params)763 void pcm_params_free(struct pcm_params *pcm_params)
764 {
765 struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
766
767 if (params)
768 free(params);
769 }
770
pcm_param_to_alsa(enum pcm_param param)771 static int pcm_param_to_alsa(enum pcm_param param)
772 {
773 switch (param) {
774 case PCM_PARAM_ACCESS:
775 return SNDRV_PCM_HW_PARAM_ACCESS;
776 case PCM_PARAM_FORMAT:
777 return SNDRV_PCM_HW_PARAM_FORMAT;
778 case PCM_PARAM_SUBFORMAT:
779 return SNDRV_PCM_HW_PARAM_SUBFORMAT;
780 case PCM_PARAM_SAMPLE_BITS:
781 return SNDRV_PCM_HW_PARAM_SAMPLE_BITS;
782 break;
783 case PCM_PARAM_FRAME_BITS:
784 return SNDRV_PCM_HW_PARAM_FRAME_BITS;
785 break;
786 case PCM_PARAM_CHANNELS:
787 return SNDRV_PCM_HW_PARAM_CHANNELS;
788 break;
789 case PCM_PARAM_RATE:
790 return SNDRV_PCM_HW_PARAM_RATE;
791 break;
792 case PCM_PARAM_PERIOD_TIME:
793 return SNDRV_PCM_HW_PARAM_PERIOD_TIME;
794 break;
795 case PCM_PARAM_PERIOD_SIZE:
796 return SNDRV_PCM_HW_PARAM_PERIOD_SIZE;
797 break;
798 case PCM_PARAM_PERIOD_BYTES:
799 return SNDRV_PCM_HW_PARAM_PERIOD_BYTES;
800 break;
801 case PCM_PARAM_PERIODS:
802 return SNDRV_PCM_HW_PARAM_PERIODS;
803 break;
804 case PCM_PARAM_BUFFER_TIME:
805 return SNDRV_PCM_HW_PARAM_BUFFER_TIME;
806 break;
807 case PCM_PARAM_BUFFER_SIZE:
808 return SNDRV_PCM_HW_PARAM_BUFFER_SIZE;
809 break;
810 case PCM_PARAM_BUFFER_BYTES:
811 return SNDRV_PCM_HW_PARAM_BUFFER_BYTES;
812 break;
813 case PCM_PARAM_TICK_TIME:
814 return SNDRV_PCM_HW_PARAM_TICK_TIME;
815 break;
816
817 default:
818 return -1;
819 }
820 }
821
822 /** Gets a mask from a PCM's hardware parameters.
823 * @param pcm_params A PCM's hardware parameters.
824 * @param param The parameter to get.
825 * @return If @p pcm_params is NULL or @p param is not a mask, NULL is returned.
826 * Otherwise, the mask associated with @p param is returned.
827 * @ingroup libtinyalsa-pcm
828 */
pcm_params_get_mask(const struct pcm_params * pcm_params,enum pcm_param param)829 const struct pcm_mask *pcm_params_get_mask(const struct pcm_params *pcm_params,
830 enum pcm_param param)
831 {
832 int p;
833 struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
834 if (params == NULL) {
835 return NULL;
836 }
837
838 p = pcm_param_to_alsa(param);
839 if (p < 0 || !param_is_mask(p)) {
840 return NULL;
841 }
842
843 return (const struct pcm_mask *)param_to_mask(params, p);
844 }
845
846 /** Get the minimum of a specified PCM parameter.
847 * @param pcm_params A PCM parameters structure.
848 * @param param The specified parameter to get the minimum of.
849 * @returns On success, the parameter minimum.
850 * On failure, zero.
851 */
pcm_params_get_min(const struct pcm_params * pcm_params,enum pcm_param param)852 unsigned int pcm_params_get_min(const struct pcm_params *pcm_params,
853 enum pcm_param param)
854 {
855 struct snd_pcm_hw_params *params = (struct snd_pcm_hw_params *)pcm_params;
856 int p;
857
858 if (!params)
859 return 0;
860
861 p = pcm_param_to_alsa(param);
862 if (p < 0)
863 return 0;
864
865 return param_get_min(params, p);
866 }
867
868 /** Get the maximum of a specified PCM parameter.
869 * @param pcm_params A PCM parameters structure.
870 * @param param The specified parameter to get the maximum of.
871 * @returns On success, the parameter maximum.
872 * On failure, zero.
873 */
pcm_params_get_max(const struct pcm_params * pcm_params,enum pcm_param param)874 unsigned int pcm_params_get_max(const struct pcm_params *pcm_params,
875 enum pcm_param param)
876 {
877 const struct snd_pcm_hw_params *params = (const struct snd_pcm_hw_params *)pcm_params;
878 int p;
879
880 if (!params)
881 return 0;
882
883 p = pcm_param_to_alsa(param);
884 if (p < 0)
885 return 0;
886
887 return param_get_max(params, p);
888 }
889
pcm_mask_test(const struct pcm_mask * m,unsigned int index)890 static int pcm_mask_test(const struct pcm_mask *m, unsigned int index)
891 {
892 const unsigned int bitshift = 5; /* for 32 bit integer */
893 const unsigned int bitmask = (1 << bitshift) - 1;
894 unsigned int element;
895
896 element = index >> bitshift;
897 if (element >= ARRAY_SIZE(m->bits))
898 return 0; /* for safety, but should never occur */
899 return (m->bits[element] >> (index & bitmask)) & 1;
900 }
901
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)902 static int pcm_mask_to_string(const struct pcm_mask *m, char *string, unsigned int size,
903 char *mask_name,
904 const char * const *bit_array_name, size_t bit_array_size)
905 {
906 unsigned int i;
907 unsigned int offset = 0;
908
909 if (m == NULL)
910 return 0;
911 if (bit_array_size < 32) {
912 STRLOG(string, offset, size, "%12s:\t%#08x\n", mask_name, m->bits[0]);
913 } else { /* spans two or more bitfields, print with an array index */
914 for (i = 0; i < (bit_array_size + 31) >> 5; ++i) {
915 STRLOG(string, offset, size, "%9s[%d]:\t%#08x\n",
916 mask_name, i, m->bits[i]);
917 }
918 }
919 for (i = 0; i < bit_array_size; ++i) {
920 if (pcm_mask_test(m, i)) {
921 STRLOG(string, offset, size, "%12s \t%s\n", "", bit_array_name[i]);
922 }
923 }
924 return offset;
925 }
926
pcm_params_to_string(struct pcm_params * params,char * string,unsigned int size)927 int pcm_params_to_string(struct pcm_params *params, char *string, unsigned int size)
928 {
929 const struct pcm_mask *m;
930 unsigned int min, max;
931 unsigned int clipoffset, offset;
932
933 m = pcm_params_get_mask(params, PCM_PARAM_ACCESS);
934 offset = pcm_mask_to_string(m, string, size,
935 "Access", access_lookup, ARRAY_SIZE(access_lookup));
936 m = pcm_params_get_mask(params, PCM_PARAM_FORMAT);
937 clipoffset = offset > size ? size : offset;
938 offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
939 "Format", format_lookup, ARRAY_SIZE(format_lookup));
940 m = pcm_params_get_mask(params, PCM_PARAM_SUBFORMAT);
941 clipoffset = offset > size ? size : offset;
942 offset += pcm_mask_to_string(m, string + clipoffset, size - clipoffset,
943 "Subformat", subformat_lookup, ARRAY_SIZE(subformat_lookup));
944 min = pcm_params_get_min(params, PCM_PARAM_RATE);
945 max = pcm_params_get_max(params, PCM_PARAM_RATE);
946 STRLOG(string, offset, size, " Rate:\tmin=%uHz\tmax=%uHz\n", min, max);
947 min = pcm_params_get_min(params, PCM_PARAM_CHANNELS);
948 max = pcm_params_get_max(params, PCM_PARAM_CHANNELS);
949 STRLOG(string, offset, size, " Channels:\tmin=%u\t\tmax=%u\n", min, max);
950 min = pcm_params_get_min(params, PCM_PARAM_SAMPLE_BITS);
951 max = pcm_params_get_max(params, PCM_PARAM_SAMPLE_BITS);
952 STRLOG(string, offset, size, " Sample bits:\tmin=%u\t\tmax=%u\n", min, max);
953 min = pcm_params_get_min(params, PCM_PARAM_PERIOD_SIZE);
954 max = pcm_params_get_max(params, PCM_PARAM_PERIOD_SIZE);
955 STRLOG(string, offset, size, " Period size:\tmin=%u\t\tmax=%u\n", min, max);
956 min = pcm_params_get_min(params, PCM_PARAM_PERIODS);
957 max = pcm_params_get_max(params, PCM_PARAM_PERIODS);
958 STRLOG(string, offset, size, "Period count:\tmin=%u\t\tmax=%u\n", min, max);
959 return offset;
960 }
961
pcm_params_format_test(struct pcm_params * params,enum pcm_format format)962 int pcm_params_format_test(struct pcm_params *params, enum pcm_format format)
963 {
964 unsigned int alsa_format = pcm_format_to_alsa(format);
965
966 if (alsa_format == SNDRV_PCM_FORMAT_S16_LE && format != PCM_FORMAT_S16_LE)
967 return 0; /* caution: format not recognized is equivalent to S16_LE */
968 return pcm_mask_test(pcm_params_get_mask(params, PCM_PARAM_FORMAT), alsa_format);
969 }
970
971 /** Closes a PCM returned by @ref pcm_open.
972 * @param pcm A PCM returned by @ref pcm_open.
973 * May not be NULL.
974 * @return Always returns zero.
975 * @ingroup libtinyalsa-pcm
976 */
pcm_close(struct pcm * pcm)977 int pcm_close(struct pcm *pcm)
978 {
979 if (pcm == &bad_pcm)
980 return 0;
981
982 pcm_hw_munmap_status(pcm);
983
984 if (pcm->flags & PCM_MMAP) {
985 pcm_stop(pcm);
986 pcm->ops->munmap(pcm->data, pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
987 }
988
989 snd_utils_close_dev_node(pcm->snd_node);
990 pcm->ops->close(pcm->data);
991 pcm->buffer_size = 0;
992 pcm->fd = -1;
993 free(pcm);
994 return 0;
995 }
996
997 /** Opens a PCM by it's name.
998 * @param name The name of the PCM.
999 * The name is given in the format: <i>hw</i>:<b>card</b>,<b>device</b>
1000 * @param flags Specify characteristics and functionality about the pcm.
1001 * May be a bitwise AND of the following:
1002 * - @ref PCM_IN
1003 * - @ref PCM_OUT
1004 * - @ref PCM_MMAP
1005 * - @ref PCM_NOIRQ
1006 * - @ref PCM_MONOTONIC
1007 * @param config The hardware and software parameters to open the PCM with.
1008 * @returns A PCM structure.
1009 * If an error occurs, the pointer of bad_pcm is returned.
1010 * Otherwise, it returns the pointer of PCM object.
1011 * Client code should check that the PCM opened properly by calling @ref pcm_is_ready.
1012 * If @ref pcm_is_ready returns false, check @ref pcm_get_error for more information.
1013 * @ingroup libtinyalsa-pcm
1014 */
pcm_open_by_name(const char * name,unsigned int flags,const struct pcm_config * config)1015 struct pcm *pcm_open_by_name(const char *name,
1016 unsigned int flags,
1017 const struct pcm_config *config)
1018 {
1019 unsigned int card, device;
1020 if (name[0] != 'h' || name[1] != 'w' || name[2] != ':') {
1021 oops(&bad_pcm, 0, "name format is not matched");
1022 return &bad_pcm;
1023 } else if (sscanf(&name[3], "%u,%u", &card, &device) != 2) {
1024 oops(&bad_pcm, 0, "name format is not matched");
1025 return &bad_pcm;
1026 }
1027 return pcm_open(card, device, flags, config);
1028 }
1029
1030 /** Opens a PCM.
1031 * @param card The card that the pcm belongs to.
1032 * The default card is zero.
1033 * @param device The device that the pcm belongs to.
1034 * The default device is zero.
1035 * @param flags Specify characteristics and functionality about the pcm.
1036 * May be a bitwise AND of the following:
1037 * - @ref PCM_IN
1038 * - @ref PCM_OUT
1039 * - @ref PCM_MMAP
1040 * - @ref PCM_NOIRQ
1041 * - @ref PCM_MONOTONIC
1042 * @param config The hardware and software parameters to open the PCM with.
1043 * @returns A PCM structure.
1044 * If an error occurs, the pointer of bad_pcm is returned.
1045 * Otherwise, it returns the pointer of PCM object.
1046 * Client code should check that the PCM opened properly by calling @ref pcm_is_ready.
1047 * If @ref pcm_is_ready returns false, check @ref pcm_get_error for more information.
1048 * @ingroup libtinyalsa-pcm
1049 */
pcm_open(unsigned int card,unsigned int device,unsigned int flags,const struct pcm_config * config)1050 struct pcm *pcm_open(unsigned int card, unsigned int device,
1051 unsigned int flags, const struct pcm_config *config)
1052 {
1053 struct pcm *pcm;
1054 struct snd_pcm_info info;
1055 int rc;
1056
1057 pcm = calloc(1, sizeof(struct pcm));
1058 if (!pcm) {
1059 oops(&bad_pcm, ENOMEM, "can't allocate PCM object");
1060 return &bad_pcm;
1061 }
1062
1063 /* Default to hw_ops, attemp plugin open only if hw (/dev/snd/pcm*) open fails */
1064 pcm->ops = &hw_ops;
1065 pcm->fd = pcm->ops->open(card, device, flags, &pcm->data, NULL);
1066
1067 #ifdef TINYALSA_USES_PLUGINS
1068 if (pcm->fd < 0) {
1069 int pcm_type;
1070 pcm->snd_node = snd_utils_open_pcm(card, device);
1071 pcm_type = snd_utils_get_node_type(pcm->snd_node);
1072 if (!pcm->snd_node || pcm_type != SND_NODE_TYPE_PLUGIN) {
1073 oops(&bad_pcm, ENODEV, "no device (hw/plugin) for card(%u), device(%u)",
1074 card, device);
1075 goto fail_close_dev_node;
1076 }
1077 pcm->ops = &plug_ops;
1078 pcm->fd = pcm->ops->open(card, device, flags, &pcm->data, pcm->snd_node);
1079 }
1080 #endif
1081 if (pcm->fd < 0) {
1082 oops(&bad_pcm, errno, "cannot open device (%u) for card (%u)",
1083 device, card);
1084 goto fail_close_dev_node;
1085 }
1086
1087 pcm->flags = flags;
1088
1089 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_INFO, &info)) {
1090 oops(&bad_pcm, errno, "cannot get info");
1091 goto fail_close;
1092 }
1093 pcm->subdevice = info.subdevice;
1094
1095 if (pcm_set_config(pcm, config) != 0) {
1096 memcpy(bad_pcm.error, pcm->error, sizeof(pcm->error));
1097 goto fail_close;
1098 }
1099
1100 rc = pcm_hw_mmap_status(pcm);
1101 if (rc < 0) {
1102 oops(&bad_pcm, errno, "mmap status failed");
1103 goto fail;
1104 }
1105
1106 #ifdef SNDRV_PCM_IOCTL_TTSTAMP
1107 if (pcm->flags & PCM_MONOTONIC) {
1108 int arg = SNDRV_PCM_TSTAMP_TYPE_MONOTONIC;
1109 rc = pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_TTSTAMP, &arg);
1110 if (rc < 0) {
1111 oops(&bad_pcm, errno, "cannot set timestamp type");
1112 goto fail;
1113 }
1114 }
1115 #endif
1116
1117 pcm->xruns = 0;
1118 return pcm;
1119
1120 fail:
1121 pcm_hw_munmap_status(pcm);
1122 if (flags & PCM_MMAP)
1123 pcm->ops->munmap(pcm->data, pcm->mmap_buffer, pcm_frames_to_bytes(pcm, pcm->buffer_size));
1124 fail_close:
1125 pcm->ops->close(pcm->data);
1126 fail_close_dev_node:
1127 #ifdef TINYALSA_USES_PLUGINS
1128 if (pcm->snd_node)
1129 snd_utils_close_dev_node(pcm->snd_node);
1130 #endif
1131 free(pcm);
1132 return &bad_pcm;
1133 }
1134
1135 /** Checks if a PCM file has been opened without error.
1136 * @param pcm A PCM handle.
1137 * May be NULL.
1138 * @return If a PCM's file descriptor is not valid or the pointer is NULL, it returns zero.
1139 * Otherwise, the function returns one.
1140 * @ingroup libtinyalsa-pcm
1141 */
pcm_is_ready(const struct pcm * pcm)1142 int pcm_is_ready(const struct pcm *pcm)
1143 {
1144 if (pcm != NULL) {
1145 return pcm->fd >= 0;
1146 }
1147 return 0;
1148 }
1149
1150 /** Links two PCMs.
1151 * After this function is called, the two PCMs will prepare, start and stop in sync (at the same time).
1152 * If an error occurs, the error message will be written to @p pcm1.
1153 * @param pcm1 A PCM handle.
1154 * @param pcm2 Another PCM handle.
1155 * @return On success, zero; on failure, a negative number.
1156 * @ingroup libtinyalsa-pcm
1157 */
pcm_link(struct pcm * pcm1,struct pcm * pcm2)1158 int pcm_link(struct pcm *pcm1, struct pcm *pcm2)
1159 {
1160 int err = ioctl(pcm1->fd, SNDRV_PCM_IOCTL_LINK, pcm2->fd);
1161 if (err == -1) {
1162 return oops(pcm1, errno, "cannot link PCM");
1163 }
1164 return 0;
1165 }
1166
1167 /** Unlinks a PCM.
1168 * @see @ref pcm_link
1169 * @param pcm A PCM handle.
1170 * @return On success, zero; on failure, a negative number.
1171 * @ingroup libtinyalsa-pcm
1172 */
pcm_unlink(struct pcm * pcm)1173 int pcm_unlink(struct pcm *pcm)
1174 {
1175 int err = ioctl(pcm->fd, SNDRV_PCM_IOCTL_UNLINK);
1176 if (err == -1) {
1177 return oops(pcm, errno, "cannot unlink PCM");
1178 }
1179 return 0;
1180 }
1181
1182 /** Prepares a PCM, if it has not been prepared already.
1183 * @param pcm A PCM handle.
1184 * @return On success, zero; on failure, a negative number.
1185 * @ingroup libtinyalsa-pcm
1186 */
pcm_prepare(struct pcm * pcm)1187 int pcm_prepare(struct pcm *pcm)
1188 {
1189 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_PREPARE) < 0)
1190 return oops(pcm, errno, "cannot prepare channel");
1191
1192 /* get appl_ptr and avail_min from kernel */
1193 pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
1194
1195 return 0;
1196 }
1197
1198 /** Starts a PCM.
1199 * @param pcm A PCM handle.
1200 * @return On success, zero; on failure, a negative number.
1201 * @ingroup libtinyalsa-pcm
1202 */
pcm_start(struct pcm * pcm)1203 int pcm_start(struct pcm *pcm)
1204 {
1205 if (pcm_state(pcm) == PCM_STATE_SETUP && pcm_prepare(pcm) != 0) {
1206 return -1;
1207 }
1208
1209 /* set appl_ptr and avail_min in kernel */
1210 if (pcm_sync_ptr(pcm, 0) < 0)
1211 return -1;
1212
1213 if (pcm->mmap_status->state != PCM_STATE_RUNNING) {
1214 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_START) < 0)
1215 return oops(pcm, errno, "cannot start channel");
1216 }
1217
1218 return 0;
1219 }
1220
1221 /** Drains a PCM.
1222 * @param pcm A PCM handle.
1223 * @return On success, zero; on failure, a negative number.
1224 * @ingroup libtinyalsa-pcm
1225 */
pcm_drain(struct pcm * pcm)1226 int pcm_drain(struct pcm *pcm)
1227 {
1228 if (!pcm_is_ready(pcm))
1229 return -1;
1230
1231 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_DRAIN) < 0)
1232 return oops(pcm, errno, "cannot drain channel");
1233
1234 return 0;
1235 }
1236
1237 /** Stops a PCM.
1238 * @param pcm A PCM handle.
1239 * @return On success, zero; on failure, a negative number.
1240 * @ingroup libtinyalsa-pcm
1241 */
pcm_stop(struct pcm * pcm)1242 int pcm_stop(struct pcm *pcm)
1243 {
1244 if (pcm->ops->ioctl(pcm->data, SNDRV_PCM_IOCTL_DROP) < 0)
1245 return oops(pcm, errno, "cannot stop channel");
1246
1247 return 0;
1248 }
1249
pcm_mmap_playback_avail(struct pcm * pcm)1250 static inline long pcm_mmap_playback_avail(struct pcm *pcm)
1251 {
1252 long avail = pcm->mmap_status->hw_ptr + (unsigned long) pcm->buffer_size -
1253 pcm->mmap_control->appl_ptr;
1254
1255 if (avail < 0) {
1256 avail += pcm->boundary;
1257 } else if ((unsigned long) avail >= pcm->boundary) {
1258 avail -= pcm->boundary;
1259 }
1260
1261 return avail;
1262 }
1263
pcm_mmap_capture_avail(struct pcm * pcm)1264 static inline long pcm_mmap_capture_avail(struct pcm *pcm)
1265 {
1266 long avail = pcm->mmap_status->hw_ptr - pcm->mmap_control->appl_ptr;
1267 if (avail < 0) {
1268 avail += pcm->boundary;
1269 }
1270
1271 return avail;
1272 }
1273
pcm_mmap_avail(struct pcm * pcm)1274 int pcm_mmap_avail(struct pcm *pcm)
1275 {
1276 pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
1277 if (pcm->flags & PCM_IN) {
1278 return (int) pcm_mmap_capture_avail(pcm);
1279 } else {
1280 return (int) pcm_mmap_playback_avail(pcm);
1281 }
1282 }
1283
pcm_mmap_appl_forward(struct pcm * pcm,int frames)1284 static void pcm_mmap_appl_forward(struct pcm *pcm, int frames)
1285 {
1286 unsigned long appl_ptr = pcm->mmap_control->appl_ptr;
1287 appl_ptr += frames;
1288
1289 /* check for boundary wrap */
1290 if (appl_ptr >= pcm->boundary) {
1291 appl_ptr -= pcm->boundary;
1292 }
1293 pcm->mmap_control->appl_ptr = appl_ptr;
1294 }
1295
pcm_mmap_begin(struct pcm * pcm,void ** areas,unsigned int * offset,unsigned int * frames)1296 int pcm_mmap_begin(struct pcm *pcm, void **areas, unsigned int *offset,
1297 unsigned int *frames)
1298 {
1299 unsigned int continuous, copy_frames, avail;
1300
1301 /* return the mmap buffer */
1302 *areas = pcm->mmap_buffer;
1303
1304 /* and the application offset in frames */
1305 *offset = pcm->mmap_control->appl_ptr % pcm->buffer_size;
1306
1307 avail = pcm_mmap_avail(pcm);
1308 if (avail > pcm->buffer_size)
1309 avail = pcm->buffer_size;
1310 continuous = pcm->buffer_size - *offset;
1311
1312 /* we can only copy frames if the are available and continuos */
1313 copy_frames = *frames;
1314 if (copy_frames > avail)
1315 copy_frames = avail;
1316 if (copy_frames > continuous)
1317 copy_frames = continuous;
1318 *frames = copy_frames;
1319
1320 return 0;
1321 }
1322
pcm_areas_copy(struct pcm * pcm,unsigned int pcm_offset,char * buf,unsigned int src_offset,unsigned int frames)1323 static int pcm_areas_copy(struct pcm *pcm, unsigned int pcm_offset,
1324 char *buf, unsigned int src_offset,
1325 unsigned int frames)
1326 {
1327 int size_bytes = pcm_frames_to_bytes(pcm, frames);
1328 int pcm_offset_bytes = pcm_frames_to_bytes(pcm, pcm_offset);
1329 int src_offset_bytes = pcm_frames_to_bytes(pcm, src_offset);
1330
1331 /* interleaved only atm */
1332 if (pcm->flags & PCM_IN)
1333 memcpy(buf + src_offset_bytes,
1334 (char*)pcm->mmap_buffer + pcm_offset_bytes,
1335 size_bytes);
1336 else
1337 memcpy((char*)pcm->mmap_buffer + pcm_offset_bytes,
1338 buf + src_offset_bytes,
1339 size_bytes);
1340 return 0;
1341 }
1342
pcm_mmap_commit(struct pcm * pcm,unsigned int offset,unsigned int frames)1343 int pcm_mmap_commit(struct pcm *pcm, unsigned int offset, unsigned int frames)
1344 {
1345 int ret;
1346
1347 /* not used */
1348 (void) offset;
1349
1350 /* update the application pointer in userspace and kernel */
1351 pcm_mmap_appl_forward(pcm, frames);
1352 ret = pcm_sync_ptr(pcm, 0);
1353 if (ret != 0){
1354 printf("%d\n", ret);
1355 return ret;
1356 }
1357
1358 return frames;
1359 }
1360
pcm_mmap_transfer_areas(struct pcm * pcm,char * buf,unsigned int offset,unsigned int size)1361 static int pcm_mmap_transfer_areas(struct pcm *pcm, char *buf,
1362 unsigned int offset, unsigned int size)
1363 {
1364 void *pcm_areas;
1365 int commit;
1366 unsigned int pcm_offset, frames, count = 0;
1367
1368 while (pcm_mmap_avail(pcm) && size) {
1369 frames = size;
1370 pcm_mmap_begin(pcm, &pcm_areas, &pcm_offset, &frames);
1371 pcm_areas_copy(pcm, pcm_offset, buf, offset, frames);
1372 commit = pcm_mmap_commit(pcm, pcm_offset, frames);
1373 if (commit < 0) {
1374 oops(pcm, commit, "failed to commit %d frames\n", frames);
1375 return commit;
1376 }
1377
1378 offset += commit;
1379 count += commit;
1380 size -= commit;
1381 }
1382 return count;
1383 }
1384
pcm_get_poll_fd(struct pcm * pcm)1385 int pcm_get_poll_fd(struct pcm *pcm)
1386 {
1387 return pcm->fd;
1388 }
1389
pcm_avail_update(struct pcm * pcm)1390 int pcm_avail_update(struct pcm *pcm)
1391 {
1392 pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_APPL|SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
1393 return pcm_mmap_avail(pcm);
1394 }
1395
1396 /** Returns available frames in pcm buffer and corresponding time stamp.
1397 * The clock is CLOCK_MONOTONIC if flag @ref PCM_MONOTONIC was specified in @ref pcm_open,
1398 * otherwise the clock is CLOCK_REALTIME.
1399 * For an input stream, frames available are frames ready for the application to read.
1400 * For an output stream, frames available are the number of empty frames available for the application to write.
1401 * @param pcm A PCM handle.
1402 * @param avail The number of available frames
1403 * @param tstamp The timestamp
1404 * @return On success, zero is returned; on failure, negative one.
1405 */
pcm_get_htimestamp(struct pcm * pcm,unsigned int * avail,struct timespec * tstamp)1406 int pcm_get_htimestamp(struct pcm *pcm, unsigned int *avail,
1407 struct timespec *tstamp)
1408 {
1409 int checking;
1410 int tmp;
1411
1412 if (!pcm_is_ready(pcm))
1413 return -1;
1414
1415 checking = 0;
1416
1417 again:
1418
1419 tmp = pcm_avail_update(pcm);
1420 if (tmp < 0)
1421 return tmp; /* error */
1422
1423 if (checking && (unsigned int) tmp == *avail)
1424 return 0;
1425
1426 *avail = (unsigned int) tmp;
1427 *tstamp = pcm->mmap_status->tstamp;
1428
1429 /*
1430 * When status is mmapped, get avail again to ensure
1431 * valid timestamp.
1432 */
1433 if (!pcm->sync_ptr) {
1434 checking = 1;
1435 goto again;
1436 }
1437
1438 /* SYNC_PTR ioctl was used, no need to check avail */
1439 return 0;
1440 }
1441
1442 /** Waits for frames to be available for read or write operations.
1443 * @param pcm A PCM handle.
1444 * @param timeout The maximum amount of time to wait for, in terms of milliseconds.
1445 * @returns If frames became available, one is returned.
1446 * If a timeout occured, zero is returned.
1447 * If an error occured, a negative number is returned.
1448 * @ingroup libtinyalsa-pcm
1449 */
pcm_wait(struct pcm * pcm,int timeout)1450 int pcm_wait(struct pcm *pcm, int timeout)
1451 {
1452 struct pollfd pfd;
1453 int err;
1454
1455 pfd.fd = pcm->fd;
1456 pfd.events = POLLIN | POLLOUT | POLLERR | POLLNVAL;
1457
1458 do {
1459 /* let's wait for avail or timeout */
1460 err = pcm->ops->poll(pcm->data, &pfd, 1, timeout);
1461 if (err < 0)
1462 return -errno;
1463
1464 /* timeout ? */
1465 if (err == 0)
1466 return 0;
1467
1468 /* have we been interrupted ? */
1469 if (errno == -EINTR)
1470 continue;
1471
1472 /* check for any errors */
1473 if (pfd.revents & (POLLERR | POLLNVAL)) {
1474 switch (pcm_state(pcm)) {
1475 case PCM_STATE_XRUN:
1476 return -EPIPE;
1477 case PCM_STATE_SUSPENDED:
1478 return -ESTRPIPE;
1479 case PCM_STATE_DISCONNECTED:
1480 return -ENODEV;
1481 default:
1482 return -EIO;
1483 }
1484 }
1485 /* poll again if fd not ready for IO */
1486 } while (!(pfd.revents & (POLLIN | POLLOUT)));
1487
1488 return 1;
1489 }
1490
1491 /*
1492 * Transfer data to/from mmapped buffer. This imitates the
1493 * behavior of read/write system calls.
1494 *
1495 * However, this doesn't seems to offer any advantage over
1496 * the read/write syscalls. Should it be removed?
1497 */
pcm_mmap_transfer(struct pcm * pcm,void * buffer,unsigned int frames)1498 static int pcm_mmap_transfer(struct pcm *pcm, void *buffer, unsigned int frames)
1499 {
1500 int is_playback;
1501
1502 int state;
1503 unsigned int avail;
1504 unsigned int user_offset = 0;
1505
1506 int err;
1507 int transferred_frames;
1508
1509 is_playback = !(pcm->flags & PCM_IN);
1510
1511 if (frames == 0)
1512 return 0;
1513
1514 /* update hardware pointer and get state */
1515 err = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC |
1516 SNDRV_PCM_SYNC_PTR_APPL |
1517 SNDRV_PCM_SYNC_PTR_AVAIL_MIN);
1518 if (err == -1)
1519 return -1;
1520 state = pcm->mmap_status->state;
1521
1522 /*
1523 * If frames < start_threshold, wait indefinitely.
1524 * Another thread may start capture
1525 */
1526 if (!is_playback && state == PCM_STATE_PREPARED &&
1527 frames >= pcm->config.start_threshold) {
1528 if (pcm_start(pcm) < 0) {
1529 return -1;
1530 }
1531 }
1532
1533 while (frames) {
1534 avail = pcm_mmap_avail(pcm);
1535
1536 if (!avail) {
1537 if (pcm->flags & PCM_NONBLOCK) {
1538 errno = EAGAIN;
1539 break;
1540 }
1541
1542 /* wait for interrupt */
1543 err = pcm_wait(pcm, -1);
1544 if (err < 0) {
1545 errno = -err;
1546 break;
1547 }
1548 }
1549
1550 transferred_frames = pcm_mmap_transfer_areas(pcm, buffer, user_offset, frames);
1551 if (transferred_frames < 0) {
1552 break;
1553 }
1554
1555 user_offset += transferred_frames;
1556 frames -= transferred_frames;
1557
1558 /* start playback if written >= start_threshold */
1559 if (is_playback && state == PCM_STATE_PREPARED &&
1560 pcm->buffer_size - avail >= pcm->config.start_threshold) {
1561 if (pcm_start(pcm) < 0) {
1562 break;
1563 }
1564 }
1565 }
1566
1567 return user_offset ? (int) user_offset : -1;
1568 }
1569
pcm_mmap_write(struct pcm * pcm,const void * data,unsigned int count)1570 int pcm_mmap_write(struct pcm *pcm, const void *data, unsigned int count)
1571 {
1572 if ((~pcm->flags) & (PCM_OUT | PCM_MMAP))
1573 return -EINVAL;
1574
1575 unsigned int frames = pcm_bytes_to_frames(pcm, count);
1576 int res = pcm_writei(pcm, (void *) data, frames);
1577
1578 if (res < 0) {
1579 return res;
1580 }
1581
1582 return (unsigned int) res == frames ? 0 : -EIO;
1583 }
1584
pcm_mmap_read(struct pcm * pcm,void * data,unsigned int count)1585 int pcm_mmap_read(struct pcm *pcm, void *data, unsigned int count)
1586 {
1587 if ((~pcm->flags) & (PCM_IN | PCM_MMAP))
1588 return -EINVAL;
1589
1590 unsigned int frames = pcm_bytes_to_frames(pcm, count);
1591 int res = pcm_readi(pcm, data, frames);
1592
1593 if (res < 0) {
1594 return res;
1595 }
1596
1597 return (unsigned int) res == frames ? 0 : -EIO;
1598 }
1599
1600 /* 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)1601 int pcm_mmap_get_hw_ptr(struct pcm* pcm, unsigned int *hw_ptr, struct timespec *tstamp)
1602 {
1603 int rc;
1604
1605 if (pcm == NULL || hw_ptr == NULL || tstamp == NULL)
1606 return oops(pcm, EINVAL, "pcm %p, hw_ptr %p, tstamp %p", pcm, hw_ptr, tstamp);
1607
1608 if (!pcm_is_ready(pcm))
1609 return oops(pcm, errno, "pcm_is_ready failed");
1610
1611 rc = pcm_sync_ptr(pcm, SNDRV_PCM_SYNC_PTR_HWSYNC);
1612 if (rc < 0)
1613 return oops(pcm, errno, "pcm_sync_ptr failed");
1614
1615 if (pcm->mmap_status == NULL)
1616 return oops(pcm, EINVAL, "pcm %p, mmap_status is NULL", pcm);
1617
1618 if ((pcm->mmap_status->state != PCM_STATE_RUNNING) &&
1619 (pcm->mmap_status->state != PCM_STATE_DRAINING))
1620 return oops(pcm, ENOSYS, "invalid stream state %d", pcm->mmap_status->state);
1621
1622 *tstamp = pcm->mmap_status->tstamp;
1623 if (tstamp->tv_sec == 0 && tstamp->tv_nsec == 0)
1624 return oops(pcm, errno, "invalid time stamp");
1625
1626 *hw_ptr = pcm->mmap_status->hw_ptr;
1627
1628 return 0;
1629 }
1630
pcm_rw_transfer(struct pcm * pcm,void * data,unsigned int frames)1631 static int pcm_rw_transfer(struct pcm *pcm, void *data, unsigned int frames)
1632 {
1633 int is_playback;
1634
1635 struct snd_xferi transfer;
1636 int res;
1637
1638 is_playback = !(pcm->flags & PCM_IN);
1639
1640 transfer.buf = data;
1641 transfer.frames = frames;
1642 transfer.result = 0;
1643
1644 res = pcm->ops->ioctl(pcm->data, is_playback
1645 ? SNDRV_PCM_IOCTL_WRITEI_FRAMES
1646 : SNDRV_PCM_IOCTL_READI_FRAMES, &transfer);
1647
1648 return res == 0 ? (int) transfer.result : -1;
1649 }
1650
pcm_generic_transfer(struct pcm * pcm,void * data,unsigned int frames)1651 static int pcm_generic_transfer(struct pcm *pcm, void *data,
1652 unsigned int frames)
1653 {
1654 int res;
1655
1656 #if UINT_MAX > TINYALSA_FRAMES_MAX
1657 if (frames > TINYALSA_FRAMES_MAX)
1658 return -EINVAL;
1659 #endif
1660 if (frames > INT_MAX)
1661 return -EINVAL;
1662
1663 if (pcm_state(pcm) == PCM_STATE_SETUP && pcm_prepare(pcm) != 0) {
1664 return -1;
1665 }
1666
1667 again:
1668
1669 if (pcm->flags & PCM_MMAP)
1670 res = pcm_mmap_transfer(pcm, data, frames);
1671 else
1672 res = pcm_rw_transfer(pcm, data, frames);
1673
1674 if (res < 0) {
1675 switch (errno) {
1676 case EPIPE:
1677 pcm->xruns++;
1678 /* fallthrough */
1679 case ESTRPIPE:
1680 /*
1681 * Try to restart if we are allowed to do so.
1682 * Otherwise, return error.
1683 */
1684 if (pcm->flags & PCM_NORESTART || pcm_prepare(pcm))
1685 return -1;
1686 goto again;
1687 case EAGAIN:
1688 if (pcm->flags & PCM_NONBLOCK)
1689 return -1;
1690 /* fallthrough */
1691 default:
1692 return oops(pcm, errno, "cannot read/write stream data");
1693 }
1694 }
1695
1696 return res;
1697 }
1698
1699 /** Writes audio samples to PCM.
1700 * If the PCM has not been started, it is started in this function.
1701 * This function is only valid for PCMs opened with the @ref PCM_OUT flag.
1702 * @param pcm A PCM handle.
1703 * @param data The audio sample array
1704 * @param frame_count The number of frames occupied by the sample array.
1705 * This value should not be greater than @ref TINYALSA_FRAMES_MAX
1706 * or INT_MAX.
1707 * @return On success, this function returns the number of frames written; otherwise, a negative number.
1708 * @ingroup libtinyalsa-pcm
1709 */
pcm_writei(struct pcm * pcm,const void * data,unsigned int frame_count)1710 int pcm_writei(struct pcm *pcm, const void *data, unsigned int frame_count)
1711 {
1712 if (pcm->flags & PCM_IN)
1713 return -EINVAL;
1714
1715 return pcm_generic_transfer(pcm, (void*) data, frame_count);
1716 }
1717
1718 /** Reads audio samples from PCM.
1719 * If the PCM has not been started, it is started in this function.
1720 * This function is only valid for PCMs opened with the @ref PCM_IN flag.
1721 * @param pcm A PCM handle.
1722 * @param data The audio sample array
1723 * @param frame_count The number of frames occupied by the sample array.
1724 * This value should not be greater than @ref TINYALSA_FRAMES_MAX
1725 * or INT_MAX.
1726 * @return On success, this function returns the number of frames written; otherwise, a negative number.
1727 * @ingroup libtinyalsa-pcm
1728 */
pcm_readi(struct pcm * pcm,void * data,unsigned int frame_count)1729 int pcm_readi(struct pcm *pcm, void *data, unsigned int frame_count)
1730 {
1731 if (!(pcm->flags & PCM_IN))
1732 return -EINVAL;
1733
1734 return pcm_generic_transfer(pcm, data, frame_count);
1735 }
1736
1737 /** Writes audio samples to PCM.
1738 * If the PCM has not been started, it is started in this function.
1739 * This function is only valid for PCMs opened with the @ref PCM_OUT flag.
1740 * This function is not valid for PCMs opened with the @ref PCM_MMAP flag.
1741 * @param pcm A PCM handle.
1742 * @param data The audio sample array
1743 * @param count The number of bytes occupied by the sample array.
1744 * @return On success, this function returns zero; otherwise, a negative number.
1745 * @deprecated
1746 * @ingroup libtinyalsa-pcm
1747 */
pcm_write(struct pcm * pcm,const void * data,unsigned int count)1748 int pcm_write(struct pcm *pcm, const void *data, unsigned int count)
1749 {
1750 unsigned int requested_frames = pcm_bytes_to_frames(pcm, count);
1751 int ret = pcm_writei(pcm, data, requested_frames);
1752
1753 if (ret < 0)
1754 return ret;
1755
1756 return ((unsigned int )ret == requested_frames) ? 0 : -EIO;
1757 }
1758
1759 /** Reads audio samples from PCM.
1760 * If the PCM has not been started, it is started in this function.
1761 * This function is only valid for PCMs opened with the @ref PCM_IN flag.
1762 * This function is not valid for PCMs opened with the @ref PCM_MMAP flag.
1763 * @param pcm A PCM handle.
1764 * @param data The audio sample array
1765 * @param count The number of bytes occupied by the sample array.
1766 * @return On success, this function returns zero; otherwise, a negative number.
1767 * @deprecated
1768 * @ingroup libtinyalsa-pcm
1769 */
pcm_read(struct pcm * pcm,void * data,unsigned int count)1770 int pcm_read(struct pcm *pcm, void *data, unsigned int count)
1771 {
1772 unsigned int requested_frames = pcm_bytes_to_frames(pcm, count);
1773 int ret = pcm_readi(pcm, data, requested_frames);
1774
1775 if (ret < 0)
1776 return ret;
1777
1778 return ((unsigned int )ret == requested_frames) ? 0 : -EIO;
1779 }
1780
1781 /** Gets the delay of the PCM, in terms of frames.
1782 * @param pcm A PCM handle.
1783 * @returns On success, the delay of the PCM.
1784 * On failure, a negative number.
1785 * @ingroup libtinyalsa-pcm
1786 */
pcm_get_delay(struct pcm * pcm)1787 long pcm_get_delay(struct pcm *pcm)
1788 {
1789 if (ioctl(pcm->fd, SNDRV_PCM_IOCTL_DELAY, &pcm->pcm_delay) < 0)
1790 return -1;
1791
1792 return pcm->pcm_delay;
1793 }
1794
1795 // TODO: Currently in Android, there are some libraries using this function to control the driver.
1796 // We should remove this function as soon as possible.
pcm_ioctl(struct pcm * pcm,int request,...)1797 int pcm_ioctl(struct pcm *pcm, int request, ...)
1798 {
1799 va_list ap;
1800 void * arg;
1801
1802 if (!pcm_is_ready(pcm))
1803 return -1;
1804
1805 va_start(ap, request);
1806 arg = va_arg(ap, void *);
1807 va_end(ap);
1808
1809 // FIXME Does not handle plugins
1810 return ioctl(pcm->fd, request, arg);
1811 }
1812