1
/*
2
 * Copyright 2008-2011 Various Authors
3
 * Copyright 2005 Timo Hirvonen
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License as
7
 * published by the Free Software Foundation; either version 2 of the
8
 * License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
#include "ip.h"
20
#include "comment.h"
21
#include "xmalloc.h"
22
#include "debug.h"
23
#include "utils.h"
24
25
#include <FLAC/export.h>
26
27
#ifdef FLAC_API_VERSION_CURRENT
28
/* flac 1.1.3 */
29
#define FLAC_NEW_API 1
30
#endif
31
32
#ifdef FLAC_NEW_API
33
#include <FLAC/stream_decoder.h>
34
#else
35
#include <FLAC/seekable_stream_decoder.h>
36
#endif
37
38
#include <FLAC/metadata.h>
39
#include <stdint.h>
40
#include <sys/types.h>
41
#include <unistd.h>
42
#include <errno.h>
43
44
#ifndef UINT64_MAX
45
#define UINT64_MAX ((uint64_t)-1)
46
#endif
47
48
/* Reduce typing.  Namespaces are nice but FLAC API is fscking ridiculous.  */
49
50
/* functions, types, enums */
51
#ifdef FLAC_NEW_API
52
#define F(s) FLAC__stream_decoder_ ## s
53
#define T(s) FLAC__StreamDecoder ## s
54
#define Dec FLAC__StreamDecoder
55
#define E(s) FLAC__STREAM_DECODER_ ## s
56
#else
57
#define F(s) FLAC__seekable_stream_decoder_ ## s
58
#define T(s) FLAC__SeekableStreamDecoder ## s
59
#define Dec FLAC__SeekableStreamDecoder
60
#define E(s) FLAC__SEEKABLE_STREAM_DECODER_ ## s
61
#endif
62
63
struct flac_private {
64
	/* file/stream position and length */
65
	uint64_t pos;
66
	uint64_t len;
67
68
	Dec *dec;
69
70
	/* PCM data */
71
	char *buf;
72
	unsigned int buf_size;
73
	unsigned int buf_wpos;
74
	unsigned int buf_rpos;
75
76
	struct keyval *comments;
77
	double duration;
78
	long bitrate;
79
80
	unsigned int ignore_next_write : 1;
81
};
82
83
#ifdef FLAC_NEW_API
84
static T(ReadStatus) read_cb(const Dec *dec, unsigned char *buf, size_t *size, void *data)
85
#else
86
static T(ReadStatus) read_cb(const Dec *dec, unsigned char *buf, unsigned *size, void *data)
87
#endif
88
{
89
	struct input_plugin_data *ip_data = data;
90
	struct flac_private *priv = ip_data->private;
91
	int rc;
92
93
	if (priv->pos == priv->len) {
94
		*size = 0;
95
#ifdef FLAC_NEW_API
96
		return E(READ_STATUS_END_OF_STREAM);
97
#else
98
		return E(READ_STATUS_OK);
99
#endif
100
	}
101
	if (*size == 0)
102
#ifdef FLAC_NEW_API
103
		return E(READ_STATUS_CONTINUE);
104
#else
105
		return E(READ_STATUS_OK);
106
#endif
107
108
	rc = read(ip_data->fd, buf, *size);
109
	if (rc == -1) {
110
		*size = 0;
111
		if (errno == EINTR || errno == EAGAIN) {
112
			/* FIXME: not sure how the flac decoder handles this */
113
			d_print("interrupted\n");
114
#ifdef FLAC_NEW_API
115
			return E(READ_STATUS_CONTINUE);
116
#else
117
			return E(READ_STATUS_OK);
118
#endif
119
		}
120
#ifdef FLAC_NEW_API
121
		return E(READ_STATUS_ABORT);
122
#else
123
		return E(READ_STATUS_ERROR);
124
#endif
125
	}
126
127
	priv->pos += rc;
128
	*size = rc;
129
	if (rc == 0) {
130
		/* should not happen */
131
#ifdef FLAC_NEW_API
132
		return E(READ_STATUS_END_OF_STREAM);
133
#else
134
		return E(READ_STATUS_OK);
135
#endif
136
	}
137
#ifdef FLAC_NEW_API
138
	return E(READ_STATUS_CONTINUE);
139
#else
140
	return E(READ_STATUS_OK);
141
#endif
142
}
143
144
static T(SeekStatus) seek_cb(const Dec *dec, uint64_t offset, void *data)
145
{
146
	struct input_plugin_data *ip_data = data;
147
	struct flac_private *priv = ip_data->private;
148
	off_t off;
149
150
	if (priv->len == UINT64_MAX)
151
		return E(SEEK_STATUS_ERROR);
152
	off = lseek(ip_data->fd, offset, SEEK_SET);
153
	if (off == -1) {
154
		return E(SEEK_STATUS_ERROR);
155
	}
156
	priv->pos = off;
157
	return E(SEEK_STATUS_OK);
158
}
159
160
static T(TellStatus) tell_cb(const Dec *dec, uint64_t *offset, void *data)
161
{
162
	struct input_plugin_data *ip_data = data;
163
	struct flac_private *priv = ip_data->private;
164
165
	d_print("\n");
166
	*offset = priv->pos;
167
	return E(TELL_STATUS_OK);
168
}
169
170
static T(LengthStatus) length_cb(const Dec *dec, uint64_t *len, void *data)
171
{
172
	struct input_plugin_data *ip_data = data;
173
	struct flac_private *priv = ip_data->private;
174
175
	d_print("\n");
176
	if (ip_data->remote) {
177
		return E(LENGTH_STATUS_ERROR);
178
	}
179
	*len = priv->len;
180
	return E(LENGTH_STATUS_OK);
181
}
182
183
static int eof_cb(const Dec *dec, void *data)
184
{
185
	struct input_plugin_data *ip_data = data;
186
	struct flac_private *priv = ip_data->private;
187
188
	return priv->pos == priv->len;;
189
}
190
191
#if defined(WORDS_BIGENDIAN)
192
193
#define LE16(x) swap_uint16(x)
194
#define LE32(x) swap_uint32(x)
195
196
#else
197
198
#define LE16(x)	(x)
199
#define LE32(x)	(x)
200
201
#endif
202
203
static FLAC__StreamDecoderWriteStatus write_cb(const Dec *dec, const FLAC__Frame *frame,
204
		const int32_t * const *buf, void *data)
205
{
206
	struct input_plugin_data *ip_data = data;
207
	struct flac_private *priv = ip_data->private;
208
	int frames, bytes, size, channels, bits, depth;
209
	int ch, nch, i, j = 0;
210
211
	if (ip_data->sf == 0) {
212
		return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
213
	}
214
215
	if (priv->ignore_next_write) {
216
		priv->ignore_next_write = 0;
217
		return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
218
	}
219
220
	frames = frame->header.blocksize;
221
	channels = sf_get_channels(ip_data->sf);
222
	bits = sf_get_bits(ip_data->sf);
223
	bytes = frames * bits / 8 * channels;
224
	size = priv->buf_size;
225
226
	if (size - priv->buf_wpos < bytes) {
227
		if (size < bytes)
228
			size = bytes;
229
		size *= 2;
230
		priv->buf = xrenew(char, priv->buf, size);
231
		priv->buf_size = size;
232
	}
233
234
	depth = frame->header.bits_per_sample;
235
	if (!depth)
236
		depth = bits;
237
	nch = frame->header.channels;
238
	if (depth == 8) {
239
		char *b = priv->buf + priv->buf_wpos;
240
241
		for (i = 0; i < frames; i++) {
242
			for (ch = 0; ch < channels; ch++)
243
				b[j++] = buf[ch % nch][i];
244
		}
245
	} else if (depth == 16) {
246
		int16_t *b = (int16_t *)(priv->buf + priv->buf_wpos);
247
248
		for (i = 0; i < frames; i++) {
249
			for (ch = 0; ch < channels; ch++)
250
				b[j++] = LE16(buf[ch % nch][i]);
251
		}
252
	} else if (depth == 32) {
253
		int32_t *b = (int32_t *)(priv->buf + priv->buf_wpos);
254
255
		for (i = 0; i < frames; i++) {
256
			for (ch = 0; ch < channels; ch++)
257
				b[j++] = LE32(buf[ch % nch][i]);
258
		}
259
	} else if (depth == 12) { /* -> 16 */
260
		int16_t *b = (int16_t *)(priv->buf + priv->buf_wpos);
261
262
		for (i = 0; i < frames; i++) {
263
			for (ch = 0; ch < channels; ch++)
264
				b[j++] = LE16(buf[ch % nch][i] << 4);
265
		}
266
	} else if (depth == 20) { /* -> 32 */
267
		int32_t *b = (int32_t *)(priv->buf + priv->buf_wpos);
268
269
		for (i = 0; i < frames; i++) {
270
			for (ch = 0; ch < channels; ch++)
271
				b[j++] = LE32(buf[ch % nch][i] << 12);
272
		}
273
	} else if (depth == 24) { /* -> 32 */
274
		int32_t *b = (int32_t *)(priv->buf + priv->buf_wpos);
275
276
		for (i = 0; i < frames; i++) {
277
			for (ch = 0; ch < channels; ch++)
278
				b[j++] = LE32(buf[ch % nch][i] << 8);
279
		}
280
	} else {
281
		d_print("bits per sample changed to %d\n", depth);
282
	}
283
284
	priv->buf_wpos += bytes;
285
	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
286
}
287
288
/* You should make a copy of metadata with FLAC__metadata_object_clone() if you will
289
 * need it elsewhere. Since metadata blocks can potentially be large, by
290
 * default the decoder only calls the metadata callback for the STREAMINFO
291
 * block; you can instruct the decoder to pass or filter other blocks with
292
 * FLAC__stream_decoder_set_metadata_*() calls.
293
 */
294
static void metadata_cb(const Dec *dec, const FLAC__StreamMetadata *metadata, void *data)
295
{
296
	struct input_plugin_data *ip_data = data;
297
	struct flac_private *priv = ip_data->private;
298
299
	switch (metadata->type) {
300
	case FLAC__METADATA_TYPE_STREAMINFO:
301
		{
302
			const FLAC__StreamMetadata_StreamInfo *si = &metadata->data.stream_info;
303
			int bits = 0;
304
305
			switch (si->bits_per_sample) {
306
			case 8:
307
			case 16:
308
			case 32:
309
				bits = si->bits_per_sample;
310
				break;
311
			case 12:
312
				bits = 16;
313
				break;
314
			case 20:
315
			case 24:
316
				bits = 32;
317
				break;
318
			}
319
320
			ip_data->sf = sf_rate(si->sample_rate) |
321
				sf_bits(bits) |
322
				sf_signed(1) |
323
				sf_channels(si->channels);
324
			if (!ip_data->remote && si->total_samples) {
325
				priv->duration = (double) si->total_samples / si->sample_rate;
326
				if (priv->duration >= 1 && priv->len >= 1)
327
					priv->bitrate = priv->len * 8 / priv->duration;
328
			}
329
		}
330
		break;
331
	case FLAC__METADATA_TYPE_VORBIS_COMMENT:
332
		d_print("VORBISCOMMENT\n");
333
		if (priv->comments) {
334
			d_print("Ignoring\n");
335
		} else {
336
			GROWING_KEYVALS(c);
337
			int i, nr;
338
339
			nr = metadata->data.vorbis_comment.num_comments;
340
			for (i = 0; i < nr; i++) {
341
				const char *str = (const char *)metadata->data.vorbis_comment.comments[i].entry;
342
				char *key, *val;
343
344
				val = strchr(str, '=');
345
				if (!val)
346
					continue;
347
				key = xstrndup(str, val - str);
348
				val = xstrdup(val + 1);
349
				comments_add(&c, key, val);
350
				free(key);
351
			}
352
			keyvals_terminate(&c);
353
			priv->comments = c.keyvals;
354
		}
355
		break;
356
	default:
357
		d_print("something else\n");
358
		break;
359
	}
360
}
361
362
static void error_cb(const Dec *dec, FLAC__StreamDecoderErrorStatus status, void *data)
363
{
364
	d_print("FLAC error: %s\n", FLAC__StreamDecoderErrorStatusString[status]);
365
}
366
367
static void free_priv(struct input_plugin_data *ip_data)
368
{
369
	struct flac_private *priv = ip_data->private;
370
	int save = errno;
371
372
	F(finish)(priv->dec);
373
	F(delete)(priv->dec);
374
	if (priv->comments)
375
		keyvals_free(priv->comments);
376
	free(priv->buf);
377
	free(priv);
378
	ip_data->private = NULL;
379
	errno = save;
380
}
381
382
/* http://flac.sourceforge.net/format.html#frame_header */
383
static void channel_map_init_flac(int channels, channel_position_t *map)
384
{
385
	unsigned int mask = 0;
386
	if (channels == 4)
387
		mask = 0x33; // 0b110011, without center and lfe
388
	else if (channels == 5)
389
		mask = 0x37; // 0b110111, without lfe
390
	channel_map_init_waveex(channels, mask, map);
391
}
392
393
static int flac_open(struct input_plugin_data *ip_data)
394
{
395
	struct flac_private *priv;
396
397
	Dec *dec = F(new)();
398
399
	const struct flac_private priv_init = {
400
		.dec      = dec,
401
		.duration = -1,
402
		.bitrate  = -1
403
	};
404
405
	if (!dec)
406
		return -IP_ERROR_INTERNAL;
407
408
	priv = xnew(struct flac_private, 1);
409
	*priv = priv_init;
410
	if (ip_data->remote) {
411
		priv->len = UINT64_MAX;
412
	} else {
413
		off_t off = lseek(ip_data->fd, 0, SEEK_END);
414
415
		if (off == -1 || lseek(ip_data->fd, 0, SEEK_SET) == -1) {
416
			int save = errno;
417
418
			F(delete)(dec);
419
			free(priv);
420
			errno = save;
421
			return -IP_ERROR_ERRNO;
422
		}
423
		priv->len = off;
424
	}
425
	ip_data->private = priv;
426
427
#ifndef FLAC_NEW_API
428
	F(set_read_callback)(dec, read_cb);
429
	F(set_seek_callback)(dec, seek_cb);
430
	F(set_tell_callback)(dec, tell_cb);
431
	F(set_length_callback)(dec, length_cb);
432
	F(set_eof_callback)(dec, eof_cb);
433
	F(set_write_callback)(dec, write_cb);
434
	F(set_metadata_callback)(dec, metadata_cb);
435
	F(set_error_callback)(dec, error_cb);
436
	F(set_client_data)(dec, ip_data);
437
#endif
438
439
#ifdef FLAC_NEW_API
440
	FLAC__stream_decoder_set_metadata_respond_all(dec);
441
	if (FLAC__stream_decoder_init_stream(dec, read_cb, seek_cb, tell_cb,
442
				length_cb, eof_cb, write_cb, metadata_cb,
443
				error_cb, ip_data) != E(INIT_STATUS_OK)) {
444
#else
445
	/* FLAC__METADATA_TYPE_STREAMINFO already accepted */
446
	F(set_metadata_respond)(dec, FLAC__METADATA_TYPE_VORBIS_COMMENT);
447
448
	if (F(init)(dec) != E(OK)) {
449
#endif
450
		int save = errno;
451
452
		d_print("init failed\n");
453
		F(delete)(priv->dec);
454
		free(priv);
455
		ip_data->private = NULL;
456
		errno = save;
457
		return -IP_ERROR_ERRNO;
458
	}
459
460
	ip_data->sf = 0;
461
	while (priv->buf_wpos == 0 && priv->pos < priv->len) {
462
		if (!F(process_single)(priv->dec)) {
463
			free_priv(ip_data);
464
			return -IP_ERROR_ERRNO;
465
		}
466
	}
467
468
	if (!ip_data->sf) {
469
		free_priv(ip_data);
470
		return -IP_ERROR_FILE_FORMAT;
471
	}
472
	if (!sf_get_bits(ip_data->sf)) {
473
		free_priv(ip_data);
474
		return -IP_ERROR_SAMPLE_FORMAT;
475
	}
476
477
	channel_map_init_flac(sf_get_channels(ip_data->sf), ip_data->channel_map);
478
	d_print("sr: %d, ch: %d, bits: %d\n",
479
			sf_get_rate(ip_data->sf),
480
			sf_get_channels(ip_data->sf),
481
			sf_get_bits(ip_data->sf));
482
	return 0;
483
}
484
485
static int flac_close(struct input_plugin_data *ip_data)
486
{
487
	free_priv(ip_data);
488
	return 0;
489
}
490
491
static int flac_read(struct input_plugin_data *ip_data, char *buffer, int count)
492
{
493
	struct flac_private *priv = ip_data->private;
494
	int avail;
495
496
	while (1) {
497
		avail = priv->buf_wpos - priv->buf_rpos;
498
		BUG_ON(avail < 0);
499
		if (avail > 0)
500
			break;
501
		if (priv->pos == priv->len)
502
			return 0;
503
		if (!F(process_single)(priv->dec)) {
504
			d_print("process_single failed\n");
505
			return -1;
506
		}
507
	}
508
	if (count > avail)
509
		count = avail;
510
	memcpy(buffer, priv->buf + priv->buf_rpos, count);
511
	priv->buf_rpos += count;
512
	BUG_ON(priv->buf_rpos > priv->buf_wpos);
513
	if (priv->buf_rpos == priv->buf_wpos) {
514
		priv->buf_rpos = 0;
515
		priv->buf_wpos = 0;
516
	}
517
	return count;
518
}
519
520
/* Flush the input and seek to an absolute sample. Decoding will resume at the
521
 * given sample. Note that because of this, the next write callback may contain
522
 * a partial block.
523
 */
524
static int flac_seek(struct input_plugin_data *ip_data, double offset)
525
{
526
	struct flac_private *priv = ip_data->private;
527
	uint64_t sample;
528
529
	sample = (uint64_t)(offset * (double)sf_get_rate(ip_data->sf) + 0.5);
530
	if (!F(seek_absolute)(priv->dec, sample)) {
531
		return -IP_ERROR_ERRNO;
532
	}
533
	priv->ignore_next_write = 1;
534
	priv->buf_rpos = 0;
535
	priv->buf_wpos = 0;
536
	return 0;
537
}
538
539
static int flac_read_comments(struct input_plugin_data *ip_data, struct keyval **comments)
540
{
541
	struct flac_private *priv = ip_data->private;
542
543
	if (priv->comments) {
544
		*comments = keyvals_dup(priv->comments);
545
	} else {
546
		*comments = keyvals_new(0);
547
	}
548
	return 0;
549
}
550
551
static int flac_duration(struct input_plugin_data *ip_data)
552
{
553
	struct flac_private *priv = ip_data->private;
554
555
	return priv->duration;
556
}
557
558
static long flac_bitrate(struct input_plugin_data *ip_data)
559
{
560
	struct flac_private *priv = ip_data->private;
561
	return priv->bitrate;
562
}
563
564
static char *flac_codec(struct input_plugin_data *ip_data)
565
{
566
	return xstrdup("flac");
567
}
568
569
static char *flac_codec_profile(struct input_plugin_data *ip_data)
570
{
571
	/* maybe identify compression-level over min/max blocksize/framesize */
572
	return NULL;
573
}
574
575
const struct input_plugin_ops ip_ops = {
576
	.open = flac_open,
577
	.close = flac_close,
578
	.read = flac_read,
579
	.seek = flac_seek,
580
	.read_comments = flac_read_comments,
581
	.duration = flac_duration,
582
	.bitrate = flac_bitrate,
583
	.bitrate_current = flac_bitrate,
584
	.codec = flac_codec,
585
	.codec_profile = flac_codec_profile
586
};
587
588
const int ip_priority = 50;
589
const char * const ip_extensions[] = { "flac", "fla", NULL };
590
const char * const ip_mime_types[] = { NULL };
591
const char * const ip_options[] = { NULL };