2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include <sys/types.h>
18 #include <sys/queue.h>
30 #include <FLAC/stream_decoder.h>
34 static FLAC__StreamDecoderWriteStatus
35 writecb(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame,
36 const int32_t * const *buffer, void *data)
38 static uint8_t buf[BUFSIZ];
42 if (player_shouldstop())
43 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
45 for (i = 0, len = 0; i < frame->header.blocksize; ++i) {
46 if (len+4 >= sizeof(buf)) {
47 sio_write(hdl, buf, len);
51 buf[len++] = buffer[0][i] & 0xff;
52 buf[len++] = (buffer[0][i] >> 8) & 0xff;
54 buf[len++] = buffer[1][i] & 0xff;
55 buf[len++] = (buffer[1][i] >> 8) & 0xff;
59 sio_write(hdl, buf, len);
61 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
65 metacb(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *meta,
70 if (meta->type == FLAC__METADATA_TYPE_STREAMINFO) {
71 sample_rate = meta->data.stream_info.sample_rate;
73 printf("sample rate: %d\n", sample_rate);
74 printf("channels: %d\n", meta->data.stream_info.channels);
75 printf("bps: %d\n", meta->data.stream_info.bits_per_sample);
76 printf("total samples: %"PRIu64"\n", meta->data.stream_info.total_samples);
78 if (player_setrate(sample_rate) == -1)
79 err(1, "player_setrate");
84 errcb(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status,
87 warnx("error: %s", FLAC__StreamDecoderErrorStatusString[status]);
95 FLAC__StreamDecoder *decoder = NULL;
96 FLAC__StreamDecoderInitStatus init_status;
98 if ((f = fdopen(fd, "r")) == NULL)
101 decoder = FLAC__stream_decoder_new();
103 err(1, "flac stream decoder");
105 FLAC__stream_decoder_set_md5_checking(decoder, 1);
107 init_status = FLAC__stream_decoder_init_FILE(decoder, f, writecb,
108 metacb, errcb, NULL);
109 if (init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK)
110 errx(1, "flac decoder: %s",
111 FLAC__StreamDecoderInitStatusString[init_status]);
113 ok = FLAC__stream_decoder_process_until_end_of_stream(decoder);
114 warnx("decoding %s", ok ? "succeeded" : "failed");
116 FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(decoder)]);
118 FLAC__stream_decoder_delete(decoder);