xref: /aosp_15_r20/external/tinyalsa_new/utils/tinyplay.c (revision 02e95f1a335b55495d41ca67eaf42361f13704fa)
1 /* tinyplay.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 <tinyalsa/asoundlib.h>
30 #include <signal.h>
31 #include <stdbool.h>
32 #include <stdint.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 
37 #define OPTPARSE_IMPLEMENTATION
38 #include "optparse.h"
39 
40 struct cmd {
41     const char *filename;
42     const char *filetype;
43     unsigned int card;
44     unsigned int device;
45     int flags;
46     struct pcm_config config;
47     unsigned int bits;
48     bool is_float;
49 };
50 
cmd_init(struct cmd * cmd)51 void cmd_init(struct cmd *cmd)
52 {
53     cmd->filename = NULL;
54     cmd->filetype = NULL;
55     cmd->card = 0;
56     cmd->device = 0;
57     cmd->flags = PCM_OUT;
58     cmd->config.period_size = 1024;
59     cmd->config.period_count = 2;
60     cmd->config.channels = 2;
61     cmd->config.rate = 48000;
62     cmd->config.format = PCM_FORMAT_S16_LE;
63     cmd->config.silence_threshold = cmd->config.period_size * cmd->config.period_count;
64     cmd->config.silence_size = 0;
65     cmd->config.stop_threshold = cmd->config.period_size * cmd->config.period_count;
66     cmd->config.start_threshold = cmd->config.period_size;
67     cmd->bits = 16;
68     cmd->is_float = false;
69 }
70 
71 #define ID_RIFF 0x46464952
72 #define ID_WAVE 0x45564157
73 #define ID_FMT  0x20746d66
74 #define ID_DATA 0x61746164
75 
76 #define WAVE_FORMAT_PCM 0x0001
77 #define WAVE_FORMAT_IEEE_FLOAT 0x0003
78 
79 struct riff_wave_header {
80     uint32_t riff_id;
81     uint32_t riff_sz;
82     uint32_t wave_id;
83 };
84 
85 struct chunk_header {
86     uint32_t id;
87     uint32_t sz;
88 };
89 
90 struct chunk_fmt {
91     uint16_t audio_format;
92     uint16_t num_channels;
93     uint32_t sample_rate;
94     uint32_t byte_rate;
95     uint16_t block_align;
96     uint16_t bits_per_sample;
97 };
98 
99 struct ctx {
100     struct pcm *pcm;
101 
102     struct riff_wave_header wave_header;
103     struct chunk_header chunk_header;
104     struct chunk_fmt chunk_fmt;
105 
106     FILE *file;
107     size_t file_size;
108 };
109 
is_wave_file(const char * filetype)110 static bool is_wave_file(const char *filetype)
111 {
112     return filetype != NULL && strcmp(filetype, "wav") == 0;
113 }
114 
signed_pcm_bits_to_format(int bits)115 static enum pcm_format signed_pcm_bits_to_format(int bits)
116 {
117     switch (bits) {
118     case 8:
119         return PCM_FORMAT_S8;
120     case 16:
121         return PCM_FORMAT_S16_LE;
122     case 24:
123         return PCM_FORMAT_S24_3LE;
124     case 32:
125         return PCM_FORMAT_S32_LE;
126     default:
127         return -1;
128     }
129 }
130 
parse_wave_file(struct ctx * ctx,const char * filename)131 static int parse_wave_file(struct ctx *ctx, const char *filename)
132 {
133     if (fread(&ctx->wave_header, sizeof(ctx->wave_header), 1, ctx->file) != 1){
134         fprintf(stderr, "error: '%s' does not contain a riff/wave header\n", filename);
135         return -1;
136     }
137 
138     if (ctx->wave_header.riff_id != ID_RIFF || ctx->wave_header.wave_id != ID_WAVE) {
139         fprintf(stderr, "error: '%s' is not a riff/wave file\n", filename);
140         return -1;
141     }
142 
143     bool more_chunks = true;
144     do {
145         if (fread(&ctx->chunk_header, sizeof(ctx->chunk_header), 1, ctx->file) != 1) {
146             fprintf(stderr, "error: '%s' does not contain a data chunk\n", filename);
147             return -1;
148         }
149         switch (ctx->chunk_header.id) {
150         case ID_FMT:
151             if (fread(&ctx->chunk_fmt, sizeof(ctx->chunk_fmt), 1, ctx->file) != 1) {
152                 fprintf(stderr, "error: '%s' has incomplete format chunk\n", filename);
153                 return -1;
154             }
155             /* If the format header is larger, skip the rest */
156             if (ctx->chunk_header.sz > sizeof(ctx->chunk_fmt)) {
157                 fseek(ctx->file, ctx->chunk_header.sz - sizeof(ctx->chunk_fmt), SEEK_CUR);
158             }
159             break;
160         case ID_DATA:
161             /* Stop looking for chunks */
162             more_chunks = false;
163             break;
164         default:
165             /* Unknown chunk, skip bytes */
166             fseek(ctx->file, ctx->chunk_header.sz, SEEK_CUR);
167         }
168     } while (more_chunks);
169 
170     return 0;
171 }
172 
ctx_init(struct ctx * ctx,struct cmd * cmd)173 static int ctx_init(struct ctx* ctx, struct cmd *cmd)
174 {
175     unsigned int bits = cmd->bits;
176     struct pcm_config *config = &cmd->config;
177     bool is_float = cmd->is_float;
178 
179     if (cmd->filename == NULL) {
180         fprintf(stderr, "filename not specified\n");
181         return -1;
182     }
183     if (strcmp(cmd->filename, "-") == 0) {
184         ctx->file = stdin;
185     } else {
186         ctx->file = fopen(cmd->filename, "rb");
187         fseek(ctx->file, 0L, SEEK_END);
188         ctx->file_size = ftell(ctx->file);
189         fseek(ctx->file, 0L, SEEK_SET);
190     }
191 
192     if (ctx->file == NULL) {
193         fprintf(stderr, "failed to open '%s'\n", cmd->filename);
194         return -1;
195     }
196 
197     if (is_wave_file(cmd->filetype)) {
198         if (parse_wave_file(ctx, cmd->filename) != 0) {
199             fclose(ctx->file);
200             return -1;
201         }
202         config->channels = ctx->chunk_fmt.num_channels;
203         config->rate = ctx->chunk_fmt.sample_rate;
204         bits = ctx->chunk_fmt.bits_per_sample;
205         is_float = ctx->chunk_fmt.audio_format == WAVE_FORMAT_IEEE_FLOAT;
206         ctx->file_size = (size_t) ctx->chunk_header.sz;
207     }
208 
209     if (is_float) {
210         config->format = PCM_FORMAT_FLOAT_LE;
211     } else {
212         config->format = signed_pcm_bits_to_format(bits);
213         if (config->format == -1) {
214             fprintf(stderr, "bit count '%u' not supported\n", bits);
215             fclose(ctx->file);
216             return -1;
217         }
218     }
219 
220     ctx->pcm = pcm_open(cmd->card,
221                         cmd->device,
222                         cmd->flags,
223                         config);
224     if (!pcm_is_ready(ctx->pcm)) {
225         fprintf(stderr, "failed to open for pcm %u,%u. %s\n",
226                 cmd->card, cmd->device,
227                 pcm_get_error(ctx->pcm));
228         fclose(ctx->file);
229         pcm_close(ctx->pcm);
230         return -1;
231     }
232 
233     return 0;
234 }
235 
ctx_free(struct ctx * ctx)236 void ctx_free(struct ctx *ctx)
237 {
238     if (ctx == NULL) {
239         return;
240     }
241     if (ctx->pcm != NULL) {
242         pcm_close(ctx->pcm);
243     }
244     if (ctx->file != NULL) {
245         fclose(ctx->file);
246     }
247 }
248 
249 static int close = 0;
250 
251 int play_sample(struct ctx *ctx);
252 
stream_close(int sig)253 void stream_close(int sig)
254 {
255     /* allow the stream to be closed gracefully */
256     signal(sig, SIG_IGN);
257     close = 1;
258 }
259 
print_usage(const char * argv0)260 void print_usage(const char *argv0)
261 {
262     fprintf(stderr, "usage: %s file.wav [options]\n", argv0);
263     fprintf(stderr, "options:\n");
264     fprintf(stderr, "-D | --card   <card number>     The card to receive the audio\n");
265     fprintf(stderr, "-d | --device <device number>   The device to receive the audio\n");
266     fprintf(stderr, "-p | --period-size <size>       The size of the PCM's period\n");
267     fprintf(stderr, "-n | --period-count <count>     The number of PCM periods\n");
268     fprintf(stderr, "-i | --file-type <file-type>    The type of file to read (raw or wav)\n");
269     fprintf(stderr, "-c | --channels <count>         The amount of channels per frame\n");
270     fprintf(stderr, "-r | --rate <rate>              The amount of frames per second\n");
271     fprintf(stderr, "-b | --bits <bit-count>         The number of bits in one sample\n");
272     fprintf(stderr, "-f | --float                    The frames are in floating-point PCM\n");
273     fprintf(stderr, "-M | --mmap                     Use memory mapped IO to play audio\n");
274     fprintf(stderr, "-s | --silence-threshold <size> The minimum number of frames to silence the PCM\n");
275     fprintf(stderr, "-t | --start-threshold <size>   The minimum number of frames required to start the PCM\n");
276     fprintf(stderr, "-T | --stop-threshold <size>    The minimum number of frames required to stop the PCM\n");
277 }
278 
main(int argc,char ** argv)279 int main(int argc, char **argv)
280 {
281     int c;
282     struct cmd cmd;
283     struct ctx ctx;
284     struct optparse opts;
285     struct optparse_long long_options[] = {
286         { "card",              'D', OPTPARSE_REQUIRED },
287         { "device",            'd', OPTPARSE_REQUIRED },
288         { "period-size",       'p', OPTPARSE_REQUIRED },
289         { "period-count",      'n', OPTPARSE_REQUIRED },
290         { "file-type",         'i', OPTPARSE_REQUIRED },
291         { "channels",          'c', OPTPARSE_REQUIRED },
292         { "rate",              'r', OPTPARSE_REQUIRED },
293         { "bits",              'b', OPTPARSE_REQUIRED },
294         { "float",             'f', OPTPARSE_NONE     },
295         { "mmap",              'M', OPTPARSE_NONE     },
296         { "help",              'h', OPTPARSE_NONE     },
297         { "silence-threshold", 's', OPTPARSE_REQUIRED },
298         { "start-threshold",   't', OPTPARSE_REQUIRED },
299         { "stop-threshold",    'T', OPTPARSE_REQUIRED },
300         { 0, 0, 0 }
301     };
302 
303     if (argc < 2) {
304         print_usage(argv[0]);
305         return EXIT_FAILURE;
306     }
307 
308     cmd_init(&cmd);
309     optparse_init(&opts, argv);
310     unsigned silence_threshold = 0;
311     unsigned start_threshold = 0;
312     unsigned stop_threshold = 0;
313     while ((c = optparse_long(&opts, long_options, NULL)) != -1) {
314         switch (c) {
315         case 'D':
316             if (sscanf(opts.optarg, "%u", &cmd.card) != 1) {
317                 fprintf(stderr, "failed parsing card number '%s'\n", argv[1]);
318                 return EXIT_FAILURE;
319             }
320             break;
321         case 'd':
322             if (sscanf(opts.optarg, "%u", &cmd.device) != 1) {
323                 fprintf(stderr, "failed parsing device number '%s'\n", argv[1]);
324                 return EXIT_FAILURE;
325             }
326             break;
327         case 'p':
328             if (sscanf(opts.optarg, "%u", &cmd.config.period_size) != 1) {
329                 fprintf(stderr, "failed parsing period size '%s'\n", argv[1]);
330                 return EXIT_FAILURE;
331             }
332             break;
333         case 'n':
334             if (sscanf(opts.optarg, "%u", &cmd.config.period_count) != 1) {
335                 fprintf(stderr, "failed parsing period count '%s'\n", argv[1]);
336                 return EXIT_FAILURE;
337             }
338             break;
339         case 'c':
340             if (sscanf(opts.optarg, "%u", &cmd.config.channels) != 1) {
341                 fprintf(stderr, "failed parsing channel count '%s'\n", argv[1]);
342                 return EXIT_FAILURE;
343             }
344             break;
345         case 'r':
346             if (sscanf(opts.optarg, "%u", &cmd.config.rate) != 1) {
347                 fprintf(stderr, "failed parsing rate '%s'\n", argv[1]);
348                 return EXIT_FAILURE;
349             }
350             break;
351         case 'i':
352             cmd.filetype = opts.optarg;
353             break;
354         case 'b':
355             if (sscanf(opts.optarg, "%u", &cmd.bits) != 1) {
356                 fprintf(stderr, "failed parsing bits per one sample '%s'\n", argv[1]);
357                 return EXIT_FAILURE;
358             }
359             break;
360         case 'f':
361             cmd.is_float = true;
362             break;
363         case 'M':
364             cmd.flags |= PCM_MMAP;
365             break;
366         case 's':
367             if (sscanf(opts.optarg, "%u", &silence_threshold) != 1) {
368                 fprintf(stderr, "failed parsing silence threshold '%s'\n", argv[1]);
369                 return EXIT_FAILURE;
370             }
371             break;
372         case 't':
373             if (sscanf(opts.optarg, "%u", &start_threshold) != 1) {
374                 fprintf(stderr, "failed parsing start threshold '%s'\n", argv[1]);
375                 return EXIT_FAILURE;
376             }
377             break;
378         case 'T':
379             if (sscanf(opts.optarg, "%u", &stop_threshold) != 1) {
380                 fprintf(stderr, "failed parsing stop threshold '%s'\n", argv[1]);
381                 return EXIT_FAILURE;
382             }
383             break;
384         case 'h':
385             print_usage(argv[0]);
386             return EXIT_SUCCESS;
387         case '?':
388             fprintf(stderr, "%s\n", opts.errmsg);
389             return EXIT_FAILURE;
390         }
391     }
392     cmd.filename = optparse_arg(&opts);
393 
394     if (cmd.filename != NULL && cmd.filetype == NULL &&
395         (cmd.filetype = strrchr(cmd.filename, '.')) != NULL) {
396         cmd.filetype++;
397     }
398 
399     cmd.config.silence_threshold = cmd.config.period_size * cmd.config.period_count;
400     cmd.config.stop_threshold = cmd.config.period_size * cmd.config.period_count;
401     cmd.config.start_threshold = cmd.config.period_size;
402 
403     if (silence_threshold != 0) {
404       cmd.config.silence_threshold = silence_threshold;
405     }
406     if (start_threshold != 0) {
407       cmd.config.start_threshold = start_threshold;
408     }
409     if (stop_threshold != 0) {
410       cmd.config.stop_threshold = stop_threshold;
411     }
412 
413     if (ctx_init(&ctx, &cmd) < 0) {
414         return EXIT_FAILURE;
415     }
416 
417     printf("playing '%s': %u ch, %u hz, %u-bit ", cmd.filename, cmd.config.channels,
418             cmd.config.rate, pcm_format_to_bits(cmd.config.format));
419     if (cmd.config.format == PCM_FORMAT_FLOAT_LE) {
420         printf("floating-point PCM\n");
421     } else {
422         printf("signed PCM\n");
423     }
424 
425     if (play_sample(&ctx) < 0) {
426         ctx_free(&ctx);
427         return EXIT_FAILURE;
428     }
429 
430     ctx_free(&ctx);
431     return EXIT_SUCCESS;
432 }
433 
check_param(struct pcm_params * params,unsigned int param,unsigned int value,char * param_name,char * param_unit)434 int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
435                  char *param_name, char *param_unit)
436 {
437     unsigned int min;
438     unsigned int max;
439     bool is_within_bounds = true;
440 
441     min = pcm_params_get_min(params, param);
442     if (value < min) {
443         fprintf(stderr, "%s is %u%s, device only supports >= %u%s\n", param_name, value,
444                 param_unit, min, param_unit);
445         is_within_bounds = false;
446     }
447 
448     max = pcm_params_get_max(params, param);
449     if (value > max) {
450         fprintf(stderr, "%s is %u%s, device only supports <= %u%s\n", param_name, value,
451                 param_unit, max, param_unit);
452         is_within_bounds = false;
453     }
454 
455     return is_within_bounds;
456 }
457 
sample_is_playable(const struct cmd * cmd)458 int sample_is_playable(const struct cmd *cmd)
459 {
460     struct pcm_params *params;
461     int can_play;
462 
463     params = pcm_params_get(cmd->card, cmd->device, PCM_OUT);
464     if (params == NULL) {
465         fprintf(stderr, "unable to open PCM %u,%u\n", cmd->card, cmd->device);
466         return 0;
467     }
468 
469     can_play = check_param(params, PCM_PARAM_RATE, cmd->config.rate, "sample rate", "hz");
470     can_play &= check_param(params, PCM_PARAM_CHANNELS, cmd->config.channels, "sample",
471             " channels");
472     can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, cmd->bits, "bits", " bits");
473     can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, cmd->config.period_size, "period size",
474             " frames");
475     can_play &= check_param(params, PCM_PARAM_PERIODS, cmd->config.period_count, "period count",
476             "");
477 
478     pcm_params_free(params);
479 
480     return can_play;
481 }
482 
play_sample(struct ctx * ctx)483 int play_sample(struct ctx *ctx)
484 {
485     char *buffer;
486     bool is_stdin_source = ctx->file == stdin;
487     size_t buffer_size = 0;
488     size_t num_read = 0;
489     size_t remaining_data_size = is_stdin_source ? SIZE_MAX : ctx->file_size;
490     size_t played_data_size = 0;
491     size_t read_size = 0;
492     const struct pcm_config *config = pcm_get_config(ctx->pcm);
493 
494     if (config == NULL) {
495         fprintf(stderr, "unable to get pcm config\n");
496         return -1;
497     }
498 
499     buffer_size = pcm_frames_to_bytes(ctx->pcm, config->period_size);
500     buffer = malloc(buffer_size);
501     if (!buffer) {
502         fprintf(stderr, "unable to allocate %zu bytes\n", buffer_size);
503         return -1;
504     }
505 
506     /* catch ctrl-c to shutdown cleanly */
507     signal(SIGINT, stream_close);
508 
509     do {
510         read_size = remaining_data_size > buffer_size ? buffer_size : remaining_data_size;
511         num_read = fread(buffer, 1, read_size, ctx->file);
512         if (num_read > 0) {
513             int written_frames = pcm_writei(ctx->pcm, buffer,
514                     pcm_bytes_to_frames(ctx->pcm, num_read));
515             if (written_frames < 0) {
516                 fprintf(stderr, "error playing sample. %s\n", pcm_get_error(ctx->pcm));
517                 break;
518             }
519 
520             if (!is_stdin_source) {
521                 remaining_data_size -= num_read;
522             }
523             played_data_size += pcm_frames_to_bytes(ctx->pcm, written_frames);
524         }
525     } while (!close && num_read > 0 && remaining_data_size > 0);
526 
527     printf("Played %zu bytes. ", played_data_size);
528     if (is_stdin_source) {
529         printf("\n");
530     } else {
531         printf("Remains %zu bytes.\n", remaining_data_size);
532     }
533 
534     pcm_wait(ctx->pcm, -1);
535 
536     free(buffer);
537     return 0;
538 }
539 
540