• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 };
108 
is_wave_file(const char * filetype)109 static bool is_wave_file(const char *filetype)
110 {
111     return filetype != NULL && strcmp(filetype, "wav") == 0;
112 }
113 
signed_pcm_bits_to_format(int bits)114 static bool signed_pcm_bits_to_format(int bits)
115 {
116     switch (bits) {
117     case 8:
118         return PCM_FORMAT_S8;
119     case 16:
120         return PCM_FORMAT_S16_LE;
121     case 24:
122         return PCM_FORMAT_S24_3LE;
123     case 32:
124         return PCM_FORMAT_S32_LE;
125     default:
126         return -1;
127     }
128 }
129 
ctx_init(struct ctx * ctx,struct cmd * cmd)130 static int ctx_init(struct ctx* ctx, struct cmd *cmd)
131 {
132     unsigned int bits = cmd->bits;
133     struct pcm_config *config = &cmd->config;
134     bool is_float = cmd->is_float;
135 
136     if (cmd->filename == NULL) {
137         fprintf(stderr, "filename not specified\n");
138         return -1;
139     }
140     if (strcmp(cmd->filename, "-") == 0) {
141         ctx->file = stdin;
142     } else {
143         ctx->file = fopen(cmd->filename, "rb");
144     }
145 
146     if (ctx->file == NULL) {
147         fprintf(stderr, "failed to open '%s'\n", cmd->filename);
148         return -1;
149     }
150 
151     if (is_wave_file(cmd->filetype)) {
152         if (fread(&ctx->wave_header, sizeof(ctx->wave_header), 1, ctx->file) != 1){
153             fprintf(stderr, "error: '%s' does not contain a riff/wave header\n", cmd->filename);
154             fclose(ctx->file);
155             return -1;
156         }
157         if ((ctx->wave_header.riff_id != ID_RIFF) ||
158             (ctx->wave_header.wave_id != ID_WAVE)) {
159             fprintf(stderr, "error: '%s' is not a riff/wave file\n", cmd->filename);
160             fclose(ctx->file);
161             return -1;
162         }
163         unsigned int more_chunks = 1;
164         do {
165             if (fread(&ctx->chunk_header, sizeof(ctx->chunk_header), 1, ctx->file) != 1){
166                 fprintf(stderr, "error: '%s' does not contain a data chunk\n", cmd->filename);
167                 fclose(ctx->file);
168                 return -1;
169             }
170             switch (ctx->chunk_header.id) {
171             case ID_FMT:
172                 if (fread(&ctx->chunk_fmt, sizeof(ctx->chunk_fmt), 1, ctx->file) != 1){
173                     fprintf(stderr, "error: '%s' has incomplete format chunk\n", cmd->filename);
174                     fclose(ctx->file);
175                     return -1;
176                 }
177                 /* If the format header is larger, skip the rest */
178                 if (ctx->chunk_header.sz > sizeof(ctx->chunk_fmt))
179                     fseek(ctx->file, ctx->chunk_header.sz - sizeof(ctx->chunk_fmt), SEEK_CUR);
180                 break;
181             case ID_DATA:
182                 /* Stop looking for chunks */
183                 more_chunks = 0;
184                 break;
185             default:
186                 /* Unknown chunk, skip bytes */
187                 fseek(ctx->file, ctx->chunk_header.sz, SEEK_CUR);
188             }
189         } while (more_chunks);
190         config->channels = ctx->chunk_fmt.num_channels;
191         config->rate = ctx->chunk_fmt.sample_rate;
192         bits = ctx->chunk_fmt.bits_per_sample;
193         is_float = ctx->chunk_fmt.audio_format == WAVE_FORMAT_IEEE_FLOAT;
194     }
195 
196     if (is_float) {
197         config->format = PCM_FORMAT_FLOAT_LE;
198     } else {
199         config->format = signed_pcm_bits_to_format(bits);
200         if (config->format == -1) {
201             fprintf(stderr, "bit count '%u' not supported\n", bits);
202             fclose(ctx->file);
203             return -1;
204         }
205     }
206 
207     ctx->pcm = pcm_open(cmd->card,
208                         cmd->device,
209                         cmd->flags,
210                         config);
211     if (!pcm_is_ready(ctx->pcm)) {
212         fprintf(stderr, "failed to open for pcm %u,%u. %s\n",
213                 cmd->card, cmd->device,
214                 pcm_get_error(ctx->pcm));
215         fclose(ctx->file);
216         pcm_close(ctx->pcm);
217         return -1;
218     }
219 
220     return 0;
221 }
222 
ctx_free(struct ctx * ctx)223 void ctx_free(struct ctx *ctx)
224 {
225     if (ctx == NULL) {
226         return;
227     }
228     if (ctx->pcm != NULL) {
229         pcm_close(ctx->pcm);
230     }
231     if (ctx->file != NULL) {
232         fclose(ctx->file);
233     }
234 }
235 
236 static int close = 0;
237 
238 int play_sample(struct ctx *ctx);
239 
stream_close(int sig)240 void stream_close(int sig)
241 {
242     /* allow the stream to be closed gracefully */
243     signal(sig, SIG_IGN);
244     close = 1;
245 }
246 
print_usage(const char * argv0)247 void print_usage(const char *argv0)
248 {
249     fprintf(stderr, "usage: %s file.wav [options]\n", argv0);
250     fprintf(stderr, "options:\n");
251     fprintf(stderr, "-D | --card   <card number>    The card to receive the audio\n");
252     fprintf(stderr, "-d | --device <device number>  The device to receive the audio\n");
253     fprintf(stderr, "-p | --period-size <size>      The size of the PCM's period\n");
254     fprintf(stderr, "-n | --period-count <count>    The number of PCM periods\n");
255     fprintf(stderr, "-i | --file-type <file-type>   The type of file to read (raw or wav)\n");
256     fprintf(stderr, "-c | --channels <count>        The amount of channels per frame\n");
257     fprintf(stderr, "-r | --rate <rate>             The amount of frames per second\n");
258     fprintf(stderr, "-b | --bits <bit-count>        The number of bits in one sample\n");
259     fprintf(stderr, "-f | --float                   The frames are in floating-point PCM\n");
260     fprintf(stderr, "-M | --mmap                    Use memory mapped IO to play audio\n");
261 }
262 
main(int argc,char ** argv)263 int main(int argc, char **argv)
264 {
265     int c;
266     struct cmd cmd;
267     struct ctx ctx;
268     struct optparse opts;
269     struct optparse_long long_options[] = {
270         { "card",         'D', OPTPARSE_REQUIRED },
271         { "device",       'd', OPTPARSE_REQUIRED },
272         { "period-size",  'p', OPTPARSE_REQUIRED },
273         { "period-count", 'n', OPTPARSE_REQUIRED },
274         { "file-type",    'i', OPTPARSE_REQUIRED },
275         { "channels",     'c', OPTPARSE_REQUIRED },
276         { "rate",         'r', OPTPARSE_REQUIRED },
277         { "bits",         'b', OPTPARSE_REQUIRED },
278         { "float",        'f', OPTPARSE_NONE     },
279         { "mmap",         'M', OPTPARSE_NONE     },
280         { "help",         'h', OPTPARSE_NONE     },
281         { 0, 0, 0 }
282     };
283 
284     if (argc < 2) {
285         print_usage(argv[0]);
286         return EXIT_FAILURE;
287     }
288 
289     cmd_init(&cmd);
290     optparse_init(&opts, argv);
291     while ((c = optparse_long(&opts, long_options, NULL)) != -1) {
292         switch (c) {
293         case 'D':
294             if (sscanf(opts.optarg, "%u", &cmd.card) != 1) {
295                 fprintf(stderr, "failed parsing card number '%s'\n", argv[1]);
296                 return EXIT_FAILURE;
297             }
298             break;
299         case 'd':
300             if (sscanf(opts.optarg, "%u", &cmd.device) != 1) {
301                 fprintf(stderr, "failed parsing device number '%s'\n", argv[1]);
302                 return EXIT_FAILURE;
303             }
304             break;
305         case 'p':
306             if (sscanf(opts.optarg, "%u", &cmd.config.period_size) != 1) {
307                 fprintf(stderr, "failed parsing period size '%s'\n", argv[1]);
308                 return EXIT_FAILURE;
309             }
310             break;
311         case 'n':
312             if (sscanf(opts.optarg, "%u", &cmd.config.period_count) != 1) {
313                 fprintf(stderr, "failed parsing period count '%s'\n", argv[1]);
314                 return EXIT_FAILURE;
315             }
316             break;
317         case 'c':
318             if (sscanf(opts.optarg, "%u", &cmd.config.channels) != 1) {
319                 fprintf(stderr, "failed parsing channel count '%s'\n", argv[1]);
320                 return EXIT_FAILURE;
321             }
322             break;
323         case 'r':
324             if (sscanf(opts.optarg, "%u", &cmd.config.rate) != 1) {
325                 fprintf(stderr, "failed parsing rate '%s'\n", argv[1]);
326                 return EXIT_FAILURE;
327             }
328             break;
329         case 'i':
330             cmd.filetype = opts.optarg;
331             break;
332         case 'b':
333             if (sscanf(opts.optarg, "%u", &cmd.bits) != 1) {
334                 fprintf(stderr, "failed parsing bits per one sample '%s'\n", argv[1]);
335                 return EXIT_FAILURE;
336             }
337             break;
338         case 'f':
339             cmd.is_float = true;
340             break;
341         case 'M':
342             cmd.flags |= PCM_MMAP;
343             break;
344         case 'h':
345             print_usage(argv[0]);
346             return EXIT_SUCCESS;
347         case '?':
348             fprintf(stderr, "%s\n", opts.errmsg);
349             return EXIT_FAILURE;
350         }
351     }
352     cmd.filename = optparse_arg(&opts);
353 
354     if (cmd.filename != NULL && cmd.filetype == NULL &&
355         (cmd.filetype = strrchr(cmd.filename, '.')) != NULL) {
356         cmd.filetype++;
357     }
358 
359     cmd.config.silence_threshold = cmd.config.period_size * cmd.config.period_count;
360     cmd.config.stop_threshold = cmd.config.period_size * cmd.config.period_count;
361     cmd.config.start_threshold = cmd.config.period_size;
362 
363     if (ctx_init(&ctx, &cmd) < 0) {
364         return EXIT_FAILURE;
365     }
366 
367     printf("playing '%s': %u ch, %u hz, %u-bit ", cmd.filename, cmd.config.channels,
368             cmd.config.rate, pcm_format_to_bits(cmd.config.format));
369     if (cmd.config.format == PCM_FORMAT_FLOAT_LE) {
370         printf("floating-point PCM\n");
371     } else {
372         printf("signed PCM\n");
373     }
374 
375     if (play_sample(&ctx) < 0) {
376         ctx_free(&ctx);
377         return EXIT_FAILURE;
378     }
379 
380     ctx_free(&ctx);
381     return EXIT_SUCCESS;
382 }
383 
check_param(struct pcm_params * params,unsigned int param,unsigned int value,char * param_name,char * param_unit)384 int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
385                  char *param_name, char *param_unit)
386 {
387     unsigned int min;
388     unsigned int max;
389     int is_within_bounds = 1;
390 
391     min = pcm_params_get_min(params, param);
392     if (value < min) {
393         fprintf(stderr, "%s is %u%s, device only supports >= %u%s\n", param_name, value,
394                 param_unit, min, param_unit);
395         is_within_bounds = 0;
396     }
397 
398     max = pcm_params_get_max(params, param);
399     if (value > max) {
400         fprintf(stderr, "%s is %u%s, device only supports <= %u%s\n", param_name, value,
401                 param_unit, max, param_unit);
402         is_within_bounds = 0;
403     }
404 
405     return is_within_bounds;
406 }
407 
sample_is_playable(const struct cmd * cmd)408 int sample_is_playable(const struct cmd *cmd)
409 {
410     struct pcm_params *params;
411     int can_play;
412 
413     params = pcm_params_get(cmd->card, cmd->device, PCM_OUT);
414     if (params == NULL) {
415         fprintf(stderr, "unable to open PCM %u,%u\n", cmd->card, cmd->device);
416         return 0;
417     }
418 
419     can_play = check_param(params, PCM_PARAM_RATE, cmd->config.rate, "sample rate", "hz");
420     can_play &= check_param(params, PCM_PARAM_CHANNELS, cmd->config.channels, "sample", " channels");
421     can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, cmd->bits, "bits", " bits");
422     can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, cmd->config.period_size, "period size",
423                             " frames");
424     can_play &= check_param(params, PCM_PARAM_PERIODS, cmd->config.period_count, "period count",
425                             " frames");
426 
427     pcm_params_free(params);
428 
429     return can_play;
430 }
431 
play_sample(struct ctx * ctx)432 int play_sample(struct ctx *ctx)
433 {
434     char *buffer;
435     size_t buffer_size = 0;
436     size_t num_read = 0;
437     size_t remaining_data_size = ctx->chunk_header.sz;
438     size_t played_data_size = 0;
439     size_t read_size = 0;
440     const struct pcm_config *config = pcm_get_config(ctx->pcm);
441 
442     if (config == NULL) {
443         fprintf(stderr, "unable to get pcm config\n");
444         return -1;
445     }
446 
447     buffer_size = pcm_frames_to_bytes(ctx->pcm, config->period_size);
448     buffer = malloc(buffer_size);
449     if (!buffer) {
450         fprintf(stderr, "unable to allocate %zu bytes\n", buffer_size);
451         return -1;
452     }
453 
454     /* catch ctrl-c to shutdown cleanly */
455     signal(SIGINT, stream_close);
456 
457     do {
458         read_size = remaining_data_size > buffer_size ? buffer_size : remaining_data_size;
459         num_read = fread(buffer, 1, read_size, ctx->file);
460         if (num_read > 0) {
461             int written_frames = pcm_writei(ctx->pcm, buffer,
462                     pcm_bytes_to_frames(ctx->pcm, num_read));
463             if (written_frames < 0) {
464                 fprintf(stderr, "error playing sample. %s\n", pcm_get_error(ctx->pcm));
465                 break;
466             }
467             remaining_data_size -= num_read;
468             played_data_size += pcm_frames_to_bytes(ctx->pcm, written_frames);
469         }
470     } while (!close && num_read > 0 && remaining_data_size > 0);
471 
472     printf("Played %zu bytes. Remains %zu bytes.\n", played_data_size, remaining_data_size);
473     pcm_wait(ctx->pcm, -1);
474 
475     free(buffer);
476     return 0;
477 }
478 
479