aboutsummaryrefslogtreecommitdiffstats
path: root/src/inputPlugins/oggflac_plugin.c
blob: d3016c9a2a3c4f3138e715b0b957e2d7e7c82af1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/* the Music Player Daemon (MPD)
 * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * OggFLAC support (half-stolen from flac_plugin.c :))
 * (c) 2005 by Eric Wong <normalperson@yhbt.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "_flac_common.h"

#ifdef HAVE_OGGFLAC

#include "_ogg_common.h"

#include "../utils.h"
#include "../log.h"

static void oggflac_cleanup(FlacData * data,
			    OggFLAC__SeekableStreamDecoder * decoder)
{
	if (data->replayGainInfo)
		freeReplayGainInfo(data->replayGainInfo);
	if (decoder)
		OggFLAC__seekable_stream_decoder_delete(decoder);
}

static OggFLAC__SeekableStreamDecoderReadStatus of_read_cb(const
							   OggFLAC__SeekableStreamDecoder
							   * decoder,
							   FLAC__byte buf[],
							   unsigned *bytes,
							   void *fdata)
{
	FlacData *data = (FlacData *) fdata;
	size_t r;

	while (1) {
		r = readFromInputStream(data->inStream, (void *)buf, 1, *bytes);
		if (r == 0 && !inputStreamAtEOF(data->inStream) && !dc_intr())
			my_usleep(10000); /* FIXME */
		else
			break;
	}
	*bytes = r;

	if (r == 0 && !inputStreamAtEOF(data->inStream) && !dc_intr())
		return OggFLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR;

	return OggFLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
}

static OggFLAC__SeekableStreamDecoderSeekStatus of_seek_cb(const
							   OggFLAC__SeekableStreamDecoder
							   * decoder,
							   FLAC__uint64 offset,
							   void *fdata)
{
	FlacData *data = (FlacData *) fdata;

	if (seekInputStream(data->inStream, offset, SEEK_SET) < 0) {
		return OggFLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
	}

	return OggFLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK;
}

static OggFLAC__SeekableStreamDecoderTellStatus of_tell_cb(const
							   OggFLAC__SeekableStreamDecoder
							   * decoder,
							   FLAC__uint64 *
							   offset, void *fdata)
{
	FlacData *data = (FlacData *) fdata;

	*offset = (long)(data->inStream->offset);

	return OggFLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
}

static OggFLAC__SeekableStreamDecoderLengthStatus of_length_cb(const
							       OggFLAC__SeekableStreamDecoder
							       * decoder,
							       FLAC__uint64 *
							       length,
							       void *fdata)
{
	FlacData *data = (FlacData *) fdata;

	*length = (size_t) (data->inStream->size);

	return OggFLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
}

static FLAC__bool of_EOF_cb(const OggFLAC__SeekableStreamDecoder * decoder,
			    void *fdata)
{
	FlacData *data = (FlacData *) fdata;

	if (inputStreamAtEOF(data->inStream) == 1)
		return true;
	return false;
}

static void of_error_cb(const OggFLAC__SeekableStreamDecoder * decoder,
			FLAC__StreamDecoderErrorStatus status, void *fdata)
{
	flac_error_common_cb("oggflac", status, (FlacData *) fdata);
}

static void oggflacPrintErroredState(OggFLAC__SeekableStreamDecoderState state)
{
	switch (state) {
	case OggFLAC__SEEKABLE_STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
		ERROR("oggflac allocation error\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_READ_ERROR:
		ERROR("oggflac read error\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR:
		ERROR("oggflac seek error\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR:
		ERROR("oggflac seekable stream error\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_ALREADY_INITIALIZED:
		ERROR("oggflac decoder already initialized\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_INVALID_CALLBACK:
		ERROR("invalid oggflac callback\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED:
		ERROR("oggflac decoder uninitialized\n");
		break;
	case OggFLAC__SEEKABLE_STREAM_DECODER_OK:
	case OggFLAC__SEEKABLE_STREAM_DECODER_SEEKING:
	case OggFLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM:
		break;
	}
}

static FLAC__StreamDecoderWriteStatus oggflacWrite(const
						   OggFLAC__SeekableStreamDecoder
						   * decoder,
						   const FLAC__Frame * frame,
						   const FLAC__int32 *
						   const buf[], void *vdata)
{
	FlacData *data = (FlacData *) vdata;
	FLAC__uint32 samples = frame->header.blocksize;
	FLAC__uint16 u16;
	unsigned char *uc;
	unsigned int c_samp, c_chan;
	int i;
	float timeChange;

	timeChange = ((float)samples) / frame->header.sample_rate;
	data->time += timeChange;

	/* ogg123 uses a complicated method of calculating bitrate
	 * with averaging which I'm not too fond of.
	 * (waste of memory/CPU cycles, especially given this is _lossless_)
	 * a get_decode_position() is not available in OggFLAC, either
	 *
	 * this does not give an accurate bitrate:
	 * (bytes_last_read was set in the read callback)
	 data->bitRate = ((8.0 * data->bytes_last_read *
	 frame->header.sample_rate)
	 /((float)samples * 1000)) + 0.5;
	 */

	for (c_samp = 0; c_samp < frame->header.blocksize; c_samp++) {
		for (c_chan = 0; c_chan < frame->header.channels;
		     c_chan++) {
			u16 = buf[c_chan][c_samp];
			uc = (unsigned char *)&u16;
			for (i = 0; i < (dc.audio_format.bits / 8); i++) {
				if (data->chunk_length >= FLAC_CHUNK_SIZE) {
					/* FIXME: line wrapping */
					switch (flacSendChunk(data)) {
					case DC_ACTION_STOP:
						return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
					case DC_ACTION_SEEK:
						return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
					default:
						/* compilers are complainers */
						break;
					}
				}
				data->chunk[data->chunk_length++] = *(uc++);
			}
		}
	}

	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}

/* used by TagDup */
static void of_metadata_dup_cb(const OggFLAC__SeekableStreamDecoder * decoder,
			       const FLAC__StreamMetadata * block, void *vdata)
{
	FlacData *data = (FlacData *) vdata;

	switch (block->type) {
	case FLAC__METADATA_TYPE_STREAMINFO:
		if (!data->tag)
			data->tag = newMpdTag();
		data->tag->time = ((float)block->data.stream_info.
				   total_samples) /
		    block->data.stream_info.sample_rate + 0.5;
		return;
	case FLAC__METADATA_TYPE_VORBIS_COMMENT:
		copyVorbisCommentBlockToMpdTag(block, data->tag);
	default:
		break;
	}
}

/* used by decode */
static void of_metadata_decode_cb(const OggFLAC__SeekableStreamDecoder * dec,
				  const FLAC__StreamMetadata * block,
				  void *vdata)
{
	flac_metadata_common_cb(block, (FlacData *) vdata);
}

static OggFLAC__SeekableStreamDecoder
    * full_decoder_init_and_read_metadata(FlacData * data,
					  unsigned int metadata_only)
{
	OggFLAC__SeekableStreamDecoder *decoder = NULL;
	unsigned int s = 1;

	if (!(decoder = OggFLAC__seekable_stream_decoder_new()))
		return NULL;

	if (metadata_only) {
		s &= OggFLAC__seekable_stream_decoder_set_metadata_callback
		    (decoder, of_metadata_dup_cb);
		s &= OggFLAC__seekable_stream_decoder_set_metadata_respond
		    (decoder, FLAC__METADATA_TYPE_STREAMINFO);
	} else {
		s &= OggFLAC__seekable_stream_decoder_set_metadata_callback
		    (decoder, of_metadata_decode_cb);
	}

	s &= OggFLAC__seekable_stream_decoder_set_read_callback(decoder,
								of_read_cb);
	s &= OggFLAC__seekable_stream_decoder_set_seek_callback(decoder,
								of_seek_cb);
	s &= OggFLAC__seekable_stream_decoder_set_tell_callback(decoder,
								of_tell_cb);
	s &= OggFLAC__seekable_stream_decoder_set_length_callback(decoder,
								  of_length_cb);
	s &= OggFLAC__seekable_stream_decoder_set_eof_callback(decoder,
							       of_EOF_cb);
	s &= OggFLAC__seekable_stream_decoder_set_write_callback(decoder,
								 oggflacWrite);
	s &= OggFLAC__seekable_stream_decoder_set_metadata_respond(decoder,
								   FLAC__METADATA_TYPE_VORBIS_COMMENT);
	s &= OggFLAC__seekable_stream_decoder_set_error_callback(decoder,
								 of_error_cb);
	s &= OggFLAC__seekable_stream_decoder_set_client_data(decoder,
							      (void *)data);

	if (!s) {
		ERROR("oggflac problem before init()\n");
		goto fail;
	}
	if (OggFLAC__seekable_stream_decoder_init(decoder) !=
	    OggFLAC__SEEKABLE_STREAM_DECODER_OK) {
		ERROR("oggflac problem doing init()\n");
		goto fail;
	}
	if (!OggFLAC__seekable_stream_decoder_process_until_end_of_metadata
	    (decoder)) {
		ERROR("oggflac problem reading metadata\n");
		goto fail;
	}

	return decoder;

fail:
	oggflacPrintErroredState(OggFLAC__seekable_stream_decoder_get_state
				 (decoder));
	OggFLAC__seekable_stream_decoder_delete(decoder);
	return NULL;
}

/* public functions: */
static MpdTag *oggflac_TagDup(char *file)
{
	InputStream inStream;
	OggFLAC__SeekableStreamDecoder *decoder;
	FlacData data;

	if (openInputStream(&inStream, file) < 0)
		return NULL;
	if (ogg_stream_type_detect(&inStream) != FLAC) {
		closeInputStream(&inStream);
		return NULL;
	}

	init_FlacData(&data, &inStream);

	/* errors here won't matter,
	 * data.tag will be set or unset, that's all we care about */
	decoder = full_decoder_init_and_read_metadata(&data, 1);

	oggflac_cleanup(&data, decoder);
	closeInputStream(&inStream);

	return data.tag;
}

static unsigned int oggflac_try_decode(InputStream * inStream)
{
	if (!inStream->seekable)
		/* we cannot seek after the detection, so don't bother
		   checking */
		return 1;

	return (ogg_stream_type_detect(inStream) == FLAC) ? 1 : 0;
}

static int oggflac_decode(InputStream * inStream)
{
	OggFLAC__SeekableStreamDecoder *decoder = NULL;
	FlacData data;
	int ret = 0;

	init_FlacData(&data, inStream);

	if (!(decoder = full_decoder_init_and_read_metadata(&data, 0))) {
		ret = -1;
		goto fail;
	}

	while (1) {
		OggFLAC__seekable_stream_decoder_process_single(decoder);
		if (OggFLAC__seekable_stream_decoder_get_state(decoder) !=
		    OggFLAC__SEEKABLE_STREAM_DECODER_OK) {
			break;
		}
		if (dc_seek()) {
			FLAC__uint64 sampleToSeek;
			dc_action_begin();
			assert(dc.action == DC_ACTION_SEEK);
			sampleToSeek = dc.seek_where *
			                 dc.audio_format.sampleRate + 0.5;
			if (OggFLAC__seekable_stream_decoder_seek_absolute
			    (decoder, sampleToSeek)) {
				data.time = ((float)sampleToSeek) /
				    dc.audio_format.sampleRate;
				data.position = 0;
				data.chunk_length = 0;
			} else {
				dc.seek_where = DC_SEEK_ERROR;
			}
			dc_action_end();
		}
	}

	if (!dc_intr()) {
		oggflacPrintErroredState
		    (OggFLAC__seekable_stream_decoder_get_state(decoder));
		OggFLAC__seekable_stream_decoder_finish(decoder);
	}
	/* send last little bit */
	if (data.chunk_length > 0 && !dc_intr())
		flacSendChunk(&data);

fail:
	oggflac_cleanup(&data, decoder);

	return ret;
}

static const char *oggflac_Suffixes[] = { "ogg", "oga",NULL };
static const char *oggflac_mime_types[] = { "audio/x-flac+ogg",
					    "application/ogg",
					    "application/x-ogg",
					    NULL };

InputPlugin oggflacPlugin = {
	"oggflac",
	NULL,
	NULL,
	oggflac_try_decode,
	oggflac_decode,
	NULL,
	oggflac_TagDup,
	INPUT_PLUGIN_STREAM_URL | INPUT_PLUGIN_STREAM_FILE,
	oggflac_Suffixes,
	oggflac_mime_types
};

#else /* !HAVE_FLAC */

InputPlugin oggflacPlugin;

#endif /* HAVE_OGGFLAC */