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 bool 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 }
275
main(int argc,char ** argv)276 int main(int argc, char **argv)
277 {
278 int c;
279 struct cmd cmd;
280 struct ctx ctx;
281 struct optparse opts;
282 struct optparse_long long_options[] = {
283 { "card", 'D', OPTPARSE_REQUIRED },
284 { "device", 'd', OPTPARSE_REQUIRED },
285 { "period-size", 'p', OPTPARSE_REQUIRED },
286 { "period-count", 'n', OPTPARSE_REQUIRED },
287 { "file-type", 'i', OPTPARSE_REQUIRED },
288 { "channels", 'c', OPTPARSE_REQUIRED },
289 { "rate", 'r', OPTPARSE_REQUIRED },
290 { "bits", 'b', OPTPARSE_REQUIRED },
291 { "float", 'f', OPTPARSE_NONE },
292 { "mmap", 'M', OPTPARSE_NONE },
293 { "help", 'h', OPTPARSE_NONE },
294 { 0, 0, 0 }
295 };
296
297 if (argc < 2) {
298 print_usage(argv[0]);
299 return EXIT_FAILURE;
300 }
301
302 cmd_init(&cmd);
303 optparse_init(&opts, argv);
304 while ((c = optparse_long(&opts, long_options, NULL)) != -1) {
305 switch (c) {
306 case 'D':
307 if (sscanf(opts.optarg, "%u", &cmd.card) != 1) {
308 fprintf(stderr, "failed parsing card number '%s'\n", argv[1]);
309 return EXIT_FAILURE;
310 }
311 break;
312 case 'd':
313 if (sscanf(opts.optarg, "%u", &cmd.device) != 1) {
314 fprintf(stderr, "failed parsing device number '%s'\n", argv[1]);
315 return EXIT_FAILURE;
316 }
317 break;
318 case 'p':
319 if (sscanf(opts.optarg, "%u", &cmd.config.period_size) != 1) {
320 fprintf(stderr, "failed parsing period size '%s'\n", argv[1]);
321 return EXIT_FAILURE;
322 }
323 break;
324 case 'n':
325 if (sscanf(opts.optarg, "%u", &cmd.config.period_count) != 1) {
326 fprintf(stderr, "failed parsing period count '%s'\n", argv[1]);
327 return EXIT_FAILURE;
328 }
329 break;
330 case 'c':
331 if (sscanf(opts.optarg, "%u", &cmd.config.channels) != 1) {
332 fprintf(stderr, "failed parsing channel count '%s'\n", argv[1]);
333 return EXIT_FAILURE;
334 }
335 break;
336 case 'r':
337 if (sscanf(opts.optarg, "%u", &cmd.config.rate) != 1) {
338 fprintf(stderr, "failed parsing rate '%s'\n", argv[1]);
339 return EXIT_FAILURE;
340 }
341 break;
342 case 'i':
343 cmd.filetype = opts.optarg;
344 break;
345 case 'b':
346 if (sscanf(opts.optarg, "%u", &cmd.bits) != 1) {
347 fprintf(stderr, "failed parsing bits per one sample '%s'\n", argv[1]);
348 return EXIT_FAILURE;
349 }
350 break;
351 case 'f':
352 cmd.is_float = true;
353 break;
354 case 'M':
355 cmd.flags |= PCM_MMAP;
356 break;
357 case 'h':
358 print_usage(argv[0]);
359 return EXIT_SUCCESS;
360 case '?':
361 fprintf(stderr, "%s\n", opts.errmsg);
362 return EXIT_FAILURE;
363 }
364 }
365 cmd.filename = optparse_arg(&opts);
366
367 if (cmd.filename != NULL && cmd.filetype == NULL &&
368 (cmd.filetype = strrchr(cmd.filename, '.')) != NULL) {
369 cmd.filetype++;
370 }
371
372 cmd.config.silence_threshold = cmd.config.period_size * cmd.config.period_count;
373 cmd.config.stop_threshold = cmd.config.period_size * cmd.config.period_count;
374 cmd.config.start_threshold = cmd.config.period_size;
375
376 if (ctx_init(&ctx, &cmd) < 0) {
377 return EXIT_FAILURE;
378 }
379
380 printf("playing '%s': %u ch, %u hz, %u-bit ", cmd.filename, cmd.config.channels,
381 cmd.config.rate, pcm_format_to_bits(cmd.config.format));
382 if (cmd.config.format == PCM_FORMAT_FLOAT_LE) {
383 printf("floating-point PCM\n");
384 } else {
385 printf("signed PCM\n");
386 }
387
388 if (play_sample(&ctx) < 0) {
389 ctx_free(&ctx);
390 return EXIT_FAILURE;
391 }
392
393 ctx_free(&ctx);
394 return EXIT_SUCCESS;
395 }
396
check_param(struct pcm_params * params,unsigned int param,unsigned int value,char * param_name,char * param_unit)397 int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
398 char *param_name, char *param_unit)
399 {
400 unsigned int min;
401 unsigned int max;
402 bool is_within_bounds = true;
403
404 min = pcm_params_get_min(params, param);
405 if (value < min) {
406 fprintf(stderr, "%s is %u%s, device only supports >= %u%s\n", param_name, value,
407 param_unit, min, param_unit);
408 is_within_bounds = false;
409 }
410
411 max = pcm_params_get_max(params, param);
412 if (value > max) {
413 fprintf(stderr, "%s is %u%s, device only supports <= %u%s\n", param_name, value,
414 param_unit, max, param_unit);
415 is_within_bounds = false;
416 }
417
418 return is_within_bounds;
419 }
420
sample_is_playable(const struct cmd * cmd)421 int sample_is_playable(const struct cmd *cmd)
422 {
423 struct pcm_params *params;
424 int can_play;
425
426 params = pcm_params_get(cmd->card, cmd->device, PCM_OUT);
427 if (params == NULL) {
428 fprintf(stderr, "unable to open PCM %u,%u\n", cmd->card, cmd->device);
429 return 0;
430 }
431
432 can_play = check_param(params, PCM_PARAM_RATE, cmd->config.rate, "sample rate", "hz");
433 can_play &= check_param(params, PCM_PARAM_CHANNELS, cmd->config.channels, "sample",
434 " channels");
435 can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, cmd->bits, "bits", " bits");
436 can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, cmd->config.period_size, "period size",
437 " frames");
438 can_play &= check_param(params, PCM_PARAM_PERIODS, cmd->config.period_count, "period count",
439 "");
440
441 pcm_params_free(params);
442
443 return can_play;
444 }
445
play_sample(struct ctx * ctx)446 int play_sample(struct ctx *ctx)
447 {
448 char *buffer;
449 bool is_stdin_source = ctx->file == stdin;
450 size_t buffer_size = 0;
451 size_t num_read = 0;
452 size_t remaining_data_size = is_stdin_source ? SIZE_MAX : ctx->file_size;
453 size_t played_data_size = 0;
454 size_t read_size = 0;
455 const struct pcm_config *config = pcm_get_config(ctx->pcm);
456
457 if (config == NULL) {
458 fprintf(stderr, "unable to get pcm config\n");
459 return -1;
460 }
461
462 buffer_size = pcm_frames_to_bytes(ctx->pcm, config->period_size);
463 buffer = malloc(buffer_size);
464 if (!buffer) {
465 fprintf(stderr, "unable to allocate %zu bytes\n", buffer_size);
466 return -1;
467 }
468
469 /* catch ctrl-c to shutdown cleanly */
470 signal(SIGINT, stream_close);
471
472 do {
473 read_size = remaining_data_size > buffer_size ? buffer_size : remaining_data_size;
474 num_read = fread(buffer, 1, read_size, ctx->file);
475 if (num_read > 0) {
476 int written_frames = pcm_writei(ctx->pcm, buffer,
477 pcm_bytes_to_frames(ctx->pcm, num_read));
478 if (written_frames < 0) {
479 fprintf(stderr, "error playing sample. %s\n", pcm_get_error(ctx->pcm));
480 break;
481 }
482
483 if (!is_stdin_source) {
484 remaining_data_size -= num_read;
485 }
486 played_data_size += pcm_frames_to_bytes(ctx->pcm, written_frames);
487 }
488 } while (!close && num_read > 0 && remaining_data_size > 0);
489
490 printf("Played %zu bytes. ", played_data_size);
491 if (is_stdin_source) {
492 printf("\n");
493 } else {
494 printf("Remains %zu bytes.\n", remaining_data_size);
495 }
496
497 pcm_wait(ctx->pcm, -1);
498
499 free(buffer);
500 return 0;
501 }
502
503