Handle streams separately in tree_add_track()
[cmus.git] / flac.c
blob6cd595ab66d44d3f67f73dd66dfa933fca1782d7
1 #include "ip.h"
2 #include "comment.h"
3 #include "xmalloc.h"
4 #include "debug.h"
6 #include <FLAC/export.h>
8 #ifdef FLAC_API_VERSION_CURRENT
9 /* flac 1.1.3 */
10 #define FLAC_NEW_API 1
11 #endif
13 #ifdef FLAC_NEW_API
14 #include <FLAC/stream_decoder.h>
15 #else
16 #include <FLAC/seekable_stream_decoder.h>
17 #endif
19 #include <FLAC/metadata.h>
20 #include <inttypes.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <errno.h>
25 #ifndef UINT64_MAX
26 #define UINT64_MAX ((uint64_t)-1)
27 #endif
29 /* Reduce typing. Namespaces are nice but FLAC API is fscking ridiculous. */
31 /* functions, types, enums */
32 #ifdef FLAC_NEW_API
33 #define F(s) FLAC__stream_decoder_ ## s
34 #define T(s) FLAC__StreamDecoder ## s
35 #define Dec FLAC__StreamDecoder
36 #define E(s) FLAC__STREAM_DECODER_ ## s
37 #else
38 #define F(s) FLAC__seekable_stream_decoder_ ## s
39 #define T(s) FLAC__SeekableStreamDecoder ## s
40 #define Dec FLAC__SeekableStreamDecoder
41 #define E(s) FLAC__SEEKABLE_STREAM_DECODER_ ## s
42 #endif
44 struct flac_private {
45 /* file/stream position and length */
46 uint64_t pos;
47 uint64_t len;
49 Dec *dec;
51 /* PCM data */
52 char *buf;
53 unsigned int buf_size;
54 unsigned int buf_wpos;
55 unsigned int buf_rpos;
57 struct keyval *comments;
58 int duration;
60 unsigned int eof : 1;
61 unsigned int ignore_next_write : 1;
64 #ifdef FLAC_NEW_API
65 static T(ReadStatus) read_cb(const Dec *dec, unsigned char *buf, size_t *size, void *data)
66 #else
67 static T(ReadStatus) read_cb(const Dec *dec, unsigned char *buf, unsigned *size, void *data)
68 #endif
70 struct input_plugin_data *ip_data = data;
71 struct flac_private *priv = ip_data->private;
72 int rc;
74 if (priv->eof) {
75 *size = 0;
76 d_print("EOF! EOF! EOF!\n");
77 #ifdef FLAC_NEW_API
78 return E(READ_STATUS_END_OF_STREAM);
79 #else
80 return E(READ_STATUS_OK);
81 #endif
83 if (*size == 0)
84 #ifdef FLAC_NEW_API
85 return E(READ_STATUS_CONTINUE);
86 #else
87 return E(READ_STATUS_OK);
88 #endif
90 rc = read(ip_data->fd, buf, *size);
91 if (rc == -1) {
92 *size = 0;
93 if (errno == EINTR || errno == EAGAIN) {
94 /* FIXME: not sure how the flac decoder handles this */
95 d_print("interrupted\n");
96 #ifdef FLAC_NEW_API
97 return E(READ_STATUS_CONTINUE);
98 #else
99 return E(READ_STATUS_OK);
100 #endif
102 #ifdef FLAC_NEW_API
103 return E(READ_STATUS_ABORT);
104 #else
105 return E(READ_STATUS_ERROR);
106 #endif
109 priv->pos += rc;
110 *size = rc;
111 if (rc == 0) {
112 /* never reached! */
113 priv->eof = 1;
114 d_print("EOF\n");
115 #ifdef FLAC_NEW_API
116 return E(READ_STATUS_END_OF_STREAM);
117 #else
118 return E(READ_STATUS_OK);
119 #endif
121 #ifdef FLAC_NEW_API
122 return E(READ_STATUS_CONTINUE);
123 #else
124 return E(READ_STATUS_OK);
125 #endif
128 static T(SeekStatus) seek_cb(const Dec *dec, uint64_t offset, void *data)
130 struct input_plugin_data *ip_data = data;
131 struct flac_private *priv = ip_data->private;
132 off_t off;
134 if (priv->len == UINT64_MAX)
135 return E(SEEK_STATUS_ERROR);
136 off = lseek(ip_data->fd, offset, SEEK_SET);
137 if (off == -1) {
138 return E(SEEK_STATUS_ERROR);
140 priv->pos = off;
141 return E(SEEK_STATUS_OK);
144 static T(TellStatus) tell_cb(const Dec *dec, uint64_t *offset, void *data)
146 struct input_plugin_data *ip_data = data;
147 struct flac_private *priv = ip_data->private;
149 d_print("\n");
150 *offset = priv->pos;
151 return E(TELL_STATUS_OK);
154 static T(LengthStatus) length_cb(const Dec *dec, uint64_t *len, void *data)
156 struct input_plugin_data *ip_data = data;
157 struct flac_private *priv = ip_data->private;
159 d_print("\n");
160 if (ip_data->remote) {
161 return E(LENGTH_STATUS_ERROR);
163 *len = priv->len;
164 return E(LENGTH_STATUS_OK);
167 static int eof_cb(const Dec *dec, void *data)
169 struct input_plugin_data *ip_data = data;
170 struct flac_private *priv = ip_data->private;
171 int eof = priv->eof;
173 if (eof)
174 d_print("EOF\n");
175 return eof;
178 #if defined(WORDS_BIGENDIAN)
180 static inline uint16_t LE16(uint16_t x)
182 return (x >> 8) | (x << 8);
185 static inline uint32_t LE32(uint32_t x)
187 uint32_t x3 = x << 24;
188 uint32_t x0 = x >> 24;
189 uint32_t x2 = (x & 0xff00) << 8;
190 uint32_t x1 = (x >> 8) & 0xff00;
191 return x3 | x2 | x1 | x0;
194 #else
196 #define LE16(x) (x)
197 #define LE32(x) (x)
199 #endif
201 static FLAC__StreamDecoderWriteStatus write_cb(const Dec *dec, const FLAC__Frame *frame,
202 const int32_t * const *buf, void *data)
204 struct input_plugin_data *ip_data = data;
205 struct flac_private *priv = ip_data->private;
206 int frames, bytes, size, channels, bits, depth;
207 int ch, i, j = 0;
209 if (ip_data->sf == 0) {
210 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
213 if (priv->ignore_next_write) {
214 priv->ignore_next_write = 0;
215 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
218 frames = frame->header.blocksize;
219 channels = sf_get_channels(ip_data->sf);
220 bits = sf_get_bits(ip_data->sf);
221 bytes = frames * bits / 8 * channels;
222 size = priv->buf_size;
224 if (size - priv->buf_wpos < bytes) {
225 if (size < bytes)
226 size = bytes;
227 size *= 2;
228 priv->buf = xrenew(char, priv->buf, size);
229 priv->buf_size = size;
232 depth = frame->header.bits_per_sample;
233 if (depth == 8) {
234 char *b = priv->buf + priv->buf_wpos;
236 for (i = 0; i < frames; i++) {
237 for (ch = 0; ch < channels; ch++)
238 b[j++] = buf[ch][i];
240 } else if (depth == 16) {
241 int16_t *b = (int16_t *)(priv->buf + priv->buf_wpos);
243 for (i = 0; i < frames; i++) {
244 for (ch = 0; ch < channels; ch++)
245 b[j++] = LE16(buf[ch][i]);
247 } else if (depth == 32) {
248 int32_t *b = (int32_t *)(priv->buf + priv->buf_wpos);
250 for (i = 0; i < frames; i++) {
251 for (ch = 0; ch < channels; ch++)
252 b[j++] = LE32(buf[ch][i]);
254 } else if (depth == 12) { /* -> 16 */
255 int16_t *b = (int16_t *)(priv->buf + priv->buf_wpos);
257 for (i = 0; i < frames; i++) {
258 for (ch = 0; ch < channels; ch++)
259 b[j++] = LE16(buf[ch][i] << 4);
261 } else if (depth == 20) { /* -> 32 */
262 int32_t *b = (int32_t *)(priv->buf + priv->buf_wpos);
264 for (i = 0; i < frames; i++) {
265 for (ch = 0; ch < channels; ch++)
266 b[j++] = LE32(buf[ch][i] << 12);
268 } else if (depth == 24) { /* -> 32 */
269 int32_t *b = (int32_t *)(priv->buf + priv->buf_wpos);
271 for (i = 0; i < frames; i++) {
272 for (ch = 0; ch < channels; ch++)
273 b[j++] = LE32(buf[ch][i] << 8);
275 } else {
276 d_print("bits per sample changed to %d\n", depth);
279 priv->buf_wpos += bytes;
280 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
283 /* You should make a copy of metadata with FLAC__metadata_object_clone() if you will
284 * need it elsewhere. Since metadata blocks can potentially be large, by
285 * default the decoder only calls the metadata callback for the STREAMINFO
286 * block; you can instruct the decoder to pass or filter other blocks with
287 * FLAC__stream_decoder_set_metadata_*() calls.
289 static void metadata_cb(const Dec *dec, const FLAC__StreamMetadata *metadata, void *data)
291 struct input_plugin_data *ip_data = data;
292 struct flac_private *priv = ip_data->private;
294 switch (metadata->type) {
295 case FLAC__METADATA_TYPE_STREAMINFO:
297 const FLAC__StreamMetadata_StreamInfo *si = &metadata->data.stream_info;
298 int bits = 0;
300 switch (si->bits_per_sample) {
301 case 8:
302 case 16:
303 case 32:
304 bits = si->bits_per_sample;
305 break;
306 case 12:
307 bits = 16;
308 break;
309 case 20:
310 case 24:
311 bits = 32;
312 break;
315 ip_data->sf = sf_rate(si->sample_rate) |
316 sf_bits(bits) |
317 sf_signed(1) |
318 sf_channels(si->channels);
319 if (!ip_data->remote && si->total_samples)
320 priv->duration = si->total_samples / si->sample_rate;
322 break;
323 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
324 d_print("VORBISCOMMENT\n");
325 if (priv->comments) {
326 d_print("Ignoring\n");
327 } else {
328 GROWING_KEYVALS(c);
329 int i, nr;
331 nr = metadata->data.vorbis_comment.num_comments;
332 for (i = 0; i < nr; i++) {
333 const char *str = metadata->data.vorbis_comment.comments[i].entry;
334 char *key, *val;
336 val = strchr(str, '=');
337 if (!val)
338 continue;
339 key = xstrndup(str, val - str);
340 val = xstrdup(val + 1);
341 comments_add(&c, key, val);
342 free(key);
344 keyvals_terminate(&c);
345 priv->comments = c.keyvals;
347 break;
348 default:
349 d_print("something else\n");
350 break;
354 static void error_cb(const Dec *dec, FLAC__StreamDecoderErrorStatus status, void *data)
356 static const char *strings[3] = {
357 "lost sync",
358 "bad header",
359 "frame crc mismatch"
361 const char *str = "unknown error";
363 if (status >= 0 && status < 3)
364 str = strings[status];
365 d_print("%d %s\n", status, str);
368 static void free_priv(struct input_plugin_data *ip_data)
370 struct flac_private *priv = ip_data->private;
371 int save = errno;
373 F(finish)(priv->dec);
374 F(delete)(priv->dec);
375 if (priv->comments)
376 keyvals_free(priv->comments);
377 free(priv->buf);
378 free(priv);
379 ip_data->private = NULL;
380 errno = save;
383 static int flac_open(struct input_plugin_data *ip_data)
385 struct flac_private *priv;
386 Dec *dec;
388 dec = F(new)();
389 if (dec == NULL)
390 return -IP_ERROR_INTERNAL;
392 priv = xnew0(struct flac_private, 1);
393 priv->dec = dec;
394 priv->duration = -1;
395 if (ip_data->remote) {
396 priv->len = UINT64_MAX;
397 } else {
398 off_t off = lseek(ip_data->fd, 0, SEEK_END);
400 if (off == -1 || lseek(ip_data->fd, 0, SEEK_SET) == -1) {
401 int save = errno;
403 F(delete)(dec);
404 free(priv);
405 errno = save;
406 return -IP_ERROR_ERRNO;
408 priv->len = off;
410 ip_data->private = priv;
412 #ifndef FLAC_NEW_API
413 F(set_read_callback)(dec, read_cb);
414 F(set_seek_callback)(dec, seek_cb);
415 F(set_tell_callback)(dec, tell_cb);
416 F(set_length_callback)(dec, length_cb);
417 F(set_eof_callback)(dec, eof_cb);
418 F(set_write_callback)(dec, write_cb);
419 F(set_metadata_callback)(dec, metadata_cb);
420 F(set_error_callback)(dec, error_cb);
421 F(set_client_data)(dec, ip_data);
422 #endif
424 #ifdef FLAC_NEW_API
425 FLAC__stream_decoder_set_metadata_respond_all(dec);
426 if (FLAC__stream_decoder_init_stream(dec, read_cb, seek_cb, tell_cb,
427 length_cb, eof_cb, write_cb, metadata_cb,
428 error_cb, ip_data) != E(INIT_STATUS_OK)) {
429 #else
430 /* FLAC__METADATA_TYPE_STREAMINFO already accepted */
431 F(set_metadata_respond)(dec, FLAC__METADATA_TYPE_VORBIS_COMMENT);
433 if (F(init)(dec) != E(OK)) {
434 #endif
435 int save = errno;
437 d_print("init failed\n");
438 F(delete)(priv->dec);
439 free(priv);
440 ip_data->private = NULL;
441 errno = save;
442 return -IP_ERROR_ERRNO;
445 ip_data->sf = 0;
446 while (priv->buf_wpos == 0 && !priv->eof) {
447 if (!F(process_single)(priv->dec)) {
448 free_priv(ip_data);
449 return -IP_ERROR_ERRNO;
453 if (!ip_data->sf) {
454 free_priv(ip_data);
455 return -IP_ERROR_FILE_FORMAT;
457 if (!sf_get_bits(ip_data->sf)) {
458 free_priv(ip_data);
459 return -IP_ERROR_SAMPLE_FORMAT;
462 d_print("sr: %d, ch: %d, bits: %d\n",
463 sf_get_rate(ip_data->sf),
464 sf_get_channels(ip_data->sf),
465 sf_get_bits(ip_data->sf));
466 return 0;
469 static int flac_close(struct input_plugin_data *ip_data)
471 free_priv(ip_data);
472 return 0;
475 static int flac_read(struct input_plugin_data *ip_data, char *buffer, int count)
477 struct flac_private *priv = ip_data->private;
478 int avail;
479 int libflac_suck_count = 0;
481 while (1) {
482 int old_pos = priv->buf_wpos;
484 avail = priv->buf_wpos - priv->buf_rpos;
485 BUG_ON(avail < 0);
486 if (avail > 0)
487 break;
488 if (priv->eof)
489 return 0;
490 if (!F(process_single)(priv->dec)) {
491 d_print("process_single failed\n");
492 return -1;
494 if (old_pos == priv->buf_wpos) {
495 libflac_suck_count++;
496 } else {
497 libflac_suck_count = 0;
499 if (libflac_suck_count > 5) {
500 d_print("libflac sucks\n");
501 priv->eof = 1;
502 return 0;
505 if (count > avail)
506 count = avail;
507 memcpy(buffer, priv->buf + priv->buf_rpos, count);
508 priv->buf_rpos += count;
509 BUG_ON(priv->buf_rpos > priv->buf_wpos);
510 if (priv->buf_rpos == priv->buf_wpos) {
511 priv->buf_rpos = 0;
512 priv->buf_wpos = 0;
514 return count;
517 /* Flush the input and seek to an absolute sample. Decoding will resume at the
518 * given sample. Note that because of this, the next write callback may contain
519 * a partial block.
521 static int flac_seek(struct input_plugin_data *ip_data, double offset)
523 struct flac_private *priv = ip_data->private;
524 uint64_t sample;
526 sample = (uint64_t)(offset * (double)sf_get_rate(ip_data->sf) + 0.5);
527 if (!F(seek_absolute)(priv->dec, sample)) {
528 return -IP_ERROR_ERRNO;
530 priv->ignore_next_write = 1;
531 priv->buf_rpos = 0;
532 priv->buf_wpos = 0;
533 return 0;
536 static int flac_read_comments(struct input_plugin_data *ip_data, struct keyval **comments)
538 struct flac_private *priv = ip_data->private;
540 if (priv->comments) {
541 *comments = keyvals_dup(priv->comments);
542 } else {
543 *comments = xnew0(struct keyval, 1);
545 return 0;
548 static int flac_duration(struct input_plugin_data *ip_data)
550 struct flac_private *priv = ip_data->private;
552 return priv->duration;
555 const struct input_plugin_ops ip_ops = {
556 .open = flac_open,
557 .close = flac_close,
558 .read = flac_read,
559 .seek = flac_seek,
560 .read_comments = flac_read_comments,
561 .duration = flac_duration
564 const char * const ip_extensions[] = { "flac", "fla", NULL };
565 const char * const ip_mime_types[] = { NULL };