FlacDecoderPlugin.cxx 9.47 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 The Music Player Daemon Project
3
 * http://www.musicpd.org
Warren Dukes's avatar
Warren Dukes committed
4 5 6 7 8 9 10 11 12 13
 *
 * 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.
14 15 16 17
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Warren Dukes's avatar
Warren Dukes committed
18 19
 */

20
#include "config.h" /* must be first for large file support */
21
#include "FlacDecoderPlugin.h"
22
#include "FlacDomain.hxx"
23 24
#include "FlacCommon.hxx"
#include "FlacMetadata.hxx"
25
#include "OggCodec.hxx"
26
#include "fs/Path.hxx"
27
#include "util/Error.hxx"
28
#include "Log.hxx"
29

30 31 32 33
#if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
#error libFLAC is too old
#endif

34
static void flacPrintErroredState(FLAC__StreamDecoderState state)
35
{
Avuton Olrich's avatar
Avuton Olrich committed
36
	switch (state) {
37 38 39 40 41 42
	case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
	case FLAC__STREAM_DECODER_READ_METADATA:
	case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
	case FLAC__STREAM_DECODER_READ_FRAME:
	case FLAC__STREAM_DECODER_END_OF_STREAM:
		return;
43

44 45 46 47 48
	case FLAC__STREAM_DECODER_OGG_ERROR:
	case FLAC__STREAM_DECODER_SEEK_ERROR:
	case FLAC__STREAM_DECODER_ABORTED:
	case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
	case FLAC__STREAM_DECODER_UNINITIALIZED:
49
		break;
Warren Dukes's avatar
Warren Dukes committed
50
	}
51

52
	LogError(flac_domain, FLAC__StreamDecoderStateString[state]);
Warren Dukes's avatar
Warren Dukes committed
53 54
}

55
static void flacMetadata(gcc_unused const FLAC__StreamDecoder * dec,
Avuton Olrich's avatar
Avuton Olrich committed
56
			 const FLAC__StreamMetadata * block, void *vdata)
57
{
Max Kellermann's avatar
Max Kellermann committed
58
	flac_metadata_common_cb(block, (struct flac_data *) vdata);
Warren Dukes's avatar
Warren Dukes committed
59 60
}

Max Kellermann's avatar
Max Kellermann committed
61
static FLAC__StreamDecoderWriteStatus
62
flac_write_cb(const FLAC__StreamDecoder *dec, const FLAC__Frame *frame,
Max Kellermann's avatar
Max Kellermann committed
63
	      const FLAC__int32 *const buf[], void *vdata)
64
{
Max Kellermann's avatar
Max Kellermann committed
65
	struct flac_data *data = (struct flac_data *) vdata;
66
	FLAC__uint64 nbytes = 0;
Avuton Olrich's avatar
Avuton Olrich committed
67

68 69 70 71 72 73 74 75 76 77 78 79
	if (FLAC__stream_decoder_get_decode_position(dec, &nbytes)) {
		if (data->position > 0 && nbytes > data->position) {
			nbytes -= data->position;
			data->position += nbytes;
		} else {
			data->position = nbytes;
			nbytes = 0;
		}
	} else
		nbytes = 0;

	return flac_common_write(data, frame, buf, nbytes);
Warren Dukes's avatar
Warren Dukes committed
80 81
}

82
static bool
83
flac_scan_file(Path path_fs,
84
	       const struct tag_handler *handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
85
{
86
	FlacMetadataChain chain;
87
	if (!chain.Read(path_fs.c_str())) {
88 89 90
		FormatDebug(flac_domain,
			    "Failed to read FLAC tags: %s",
			    chain.GetStatusString());
91 92 93 94 95
		return false;
	}

	chain.Scan(handler, handler_ctx);
	return true;
Warren Dukes's avatar
Warren Dukes committed
96 97
}

98
static bool
99
flac_scan_stream(InputStream &is,
100 101
		 const struct tag_handler *handler, void *handler_ctx)
{
102
	FlacMetadataChain chain;
103
	if (!chain.Read(is)) {
104 105 106
		FormatDebug(flac_domain,
			    "Failed to read FLAC tags: %s",
			    chain.GetStatusString());
107 108 109 110 111 112 113
		return false;
	}

	chain.Scan(handler, handler_ctx);
	return true;
}

114 115 116 117 118 119 120
/**
 * Some glue code around FLAC__stream_decoder_new().
 */
static FLAC__StreamDecoder *
flac_decoder_new(void)
{
	FLAC__StreamDecoder *sd = FLAC__stream_decoder_new();
121
	if (sd == nullptr) {
122 123
		LogError(flac_domain,
			 "FLAC__stream_decoder_new() failed");
124
		return nullptr;
125 126 127
	}

	if(!FLAC__stream_decoder_set_metadata_respond(sd, FLAC__METADATA_TYPE_VORBIS_COMMENT))
128 129
		LogDebug(flac_domain,
			 "FLAC__stream_decoder_set_metadata_respond() has failed");
130 131 132 133

	return sd;
}

134 135
static bool
flac_decoder_initialize(struct flac_data *data, FLAC__StreamDecoder *sd,
136
			FLAC__uint64 duration)
137
{
138
	data->total_frames = duration;
139

140
	if (!FLAC__stream_decoder_process_until_end_of_metadata(sd)) {
141
		LogWarning(flac_domain, "problem reading metadata");
142 143 144
		return false;
	}

145
	if (data->initialized) {
146
		/* done */
147
		decoder_initialized(data->decoder, data->audio_format,
148
				    data->input_stream.IsSeekable(),
149 150
				    (float)data->total_frames /
				    (float)data->audio_format.sample_rate);
151
		return true;
152
	}
153

154
	if (data->input_stream.IsSeekable())
155 156 157 158 159 160 161
		/* allow the workaround below only for nonseekable
		   streams*/
		return false;

	/* no stream_info packet found; try to initialize the decoder
	   from the first frame header */
	FLAC__stream_decoder_process_single(sd);
162
	return data->initialized;
163 164
}

165
static void
166
flac_decoder_loop(struct flac_data *data, FLAC__StreamDecoder *flac_dec,
167 168
		  FLAC__uint64 t_start, FLAC__uint64 t_end)
{
169
	Decoder &decoder = data->decoder;
170

171 172
	data->first_frame = t_start;

173
	while (true) {
174
		DecoderCommand cmd;
Max Kellermann's avatar
Max Kellermann committed
175
		if (!data->tag.IsEmpty()) {
176
			cmd = decoder_tag(data->decoder, data->input_stream,
Max Kellermann's avatar
Max Kellermann committed
177 178
					  std::move(data->tag));
			data->tag.Clear();
179 180 181
		} else
			cmd = decoder_get_command(decoder);

182
		if (cmd == DecoderCommand::SEEK) {
183 184
			FLAC__uint64 seek_sample = t_start +
				decoder_seek_where(decoder) *
185
				data->audio_format.sample_rate;
186 187
			if (seek_sample >= t_start &&
			    (t_end == 0 || seek_sample <= t_end) &&
188
			    FLAC__stream_decoder_seek_absolute(flac_dec, seek_sample)) {
189 190 191 192 193
				data->next_frame = seek_sample;
				data->position = 0;
				decoder_command_finished(decoder);
			} else
				decoder_seek_error(decoder);
194
		} else if (cmd == DecoderCommand::STOP ||
195
			   FLAC__stream_decoder_get_state(flac_dec) == FLAC__STREAM_DECODER_END_OF_STREAM)
196 197 198 199 200 201
			break;

		if (t_end != 0 && data->next_frame >= t_end)
			/* end of this sub track */
			break;

202
		if (!FLAC__stream_decoder_process_single(flac_dec) &&
203
		    decoder_get_command(decoder) == DecoderCommand::NONE) {
204 205 206 207
			/* a failure that was not triggered by a
			   decoder command */
			flacPrintErroredState(FLAC__stream_decoder_get_state(flac_dec));
			break;
208 209 210 211
		}
	}
}

212 213 214 215
static FLAC__StreamDecoderInitStatus
stream_init_oggflac(FLAC__StreamDecoder *flac_dec, struct flac_data *data)
{
	return FLAC__stream_decoder_init_ogg_stream(flac_dec,
216 217 218 219 220
						    FlacInput::Read,
						    FlacInput::Seek,
						    FlacInput::Tell,
						    FlacInput::Length,
						    FlacInput::Eof,
221 222
						    flac_write_cb,
						    flacMetadata,
223
						    FlacInput::Error,
224 225 226 227 228 229 230
						    data);
}

static FLAC__StreamDecoderInitStatus
stream_init_flac(FLAC__StreamDecoder *flac_dec, struct flac_data *data)
{
	return FLAC__stream_decoder_init_stream(flac_dec,
231 232 233 234 235
						FlacInput::Read,
						FlacInput::Seek,
						FlacInput::Tell,
						FlacInput::Length,
						FlacInput::Eof,
236
						flac_write_cb,
237
						flacMetadata,
238
						FlacInput::Error,
239 240 241 242 243 244 245 246 247 248 249
						data);
}

static FLAC__StreamDecoderInitStatus
stream_init(FLAC__StreamDecoder *flac_dec, struct flac_data *data, bool is_ogg)
{
	return is_ogg
		? stream_init_oggflac(flac_dec, data)
		: stream_init_flac(flac_dec, data);
}

250
static void
251
flac_decode_internal(Decoder &decoder,
252
		     InputStream &input_stream,
253
		     bool is_ogg)
254
{
255
	FLAC__StreamDecoder *flac_dec;
256

257
	flac_dec = flac_decoder_new();
258
	if (flac_dec == nullptr)
259
		return;
260

261
	struct flac_data data(decoder, input_stream);
262

263 264 265 266
	FLAC__StreamDecoderInitStatus status =
		stream_init(flac_dec, &data, is_ogg);
	if (status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
		FLAC__stream_decoder_delete(flac_dec);
267 268
		LogWarning(flac_domain,
			   FLAC__StreamDecoderInitStatusString[status]);
269
		return;
270 271
	}

272
	if (!flac_decoder_initialize(&data, flac_dec, 0)) {
273
		FLAC__stream_decoder_finish(flac_dec);
274 275
		FLAC__stream_decoder_delete(flac_dec);
		return;
276 277
	}

278
	flac_decoder_loop(&data, flac_dec, 0, 0);
279

280
	FLAC__stream_decoder_finish(flac_dec);
281
	FLAC__stream_decoder_delete(flac_dec);
282 283
}

284
static void
285
flac_decode(Decoder &decoder, InputStream &input_stream)
286
{
Max Kellermann's avatar
Max Kellermann committed
287
	flac_decode_internal(decoder, input_stream, false);
288 289
}

290
static bool
291
oggflac_init(gcc_unused const config_param &param)
292 293 294 295
{
	return !!FLAC_API_SUPPORTS_OGG_FLAC;
}

296
static bool
297
oggflac_scan_file(Path path_fs,
298
		  const struct tag_handler *handler, void *handler_ctx)
299
{
300
	FlacMetadataChain chain;
301
	if (!chain.ReadOgg(path_fs.c_str())) {
302 303 304
		FormatDebug(flac_domain,
			    "Failed to read OggFLAC tags: %s",
			    chain.GetStatusString());
305
		return false;
306 307
	}

308
	chain.Scan(handler, handler_ctx);
309
	return true;
310 311
}

312
static bool
313
oggflac_scan_stream(InputStream &is,
314 315
		    const struct tag_handler *handler, void *handler_ctx)
{
316
	FlacMetadataChain chain;
317
	if (!chain.ReadOgg(is)) {
318 319 320
		FormatDebug(flac_domain,
			    "Failed to read OggFLAC tags: %s",
			    chain.GetStatusString());
321 322 323 324 325 326 327
		return false;
	}

	chain.Scan(handler, handler_ctx);
	return true;
}

328
static void
329
oggflac_decode(Decoder &decoder, InputStream &input_stream)
330
{
331
	if (ogg_codec_detect(&decoder, input_stream) != OGG_CODEC_FLAC)
332
		return;
333

334
	/* rewind the stream, because ogg_codec_detect() has
335
	   moved it */
336
	input_stream.LockRewind(IgnoreError());
337

Max Kellermann's avatar
Max Kellermann committed
338
	flac_decode_internal(decoder, input_stream, true);
339 340
}

341
static const char *const oggflac_suffixes[] = { "ogg", "oga", nullptr };
342 343 344
static const char *const oggflac_mime_types[] = {
	"application/ogg",
	"application/x-ogg",
345 346 347
	"audio/ogg",
	"audio/x-flac+ogg",
	"audio/x-ogg",
348
	nullptr
349
};
350

351
const struct DecoderPlugin oggflac_decoder_plugin = {
352 353 354 355 356 357
	"oggflac",
	oggflac_init,
	nullptr,
	oggflac_decode,
	nullptr,
	oggflac_scan_file,
358
	oggflac_scan_stream,
359 360 361
	nullptr,
	oggflac_suffixes,
	oggflac_mime_types,
362
};
363

364
static const char *const flac_suffixes[] = { "flac", nullptr };
365
static const char *const flac_mime_types[] = {
366 367 368 369
	"application/flac",
	"application/x-flac",
	"audio/flac",
	"audio/x-flac",
370
	nullptr
371
};
Warren Dukes's avatar
Warren Dukes committed
372

373
const struct DecoderPlugin flac_decoder_plugin = {
374 375 376 377 378 379
	"flac",
	nullptr,
	nullptr,
	flac_decode,
	nullptr,
	flac_scan_file,
380
	flac_scan_stream,
381 382 383
	nullptr,
	flac_suffixes,
	flac_mime_types,
Warren Dukes's avatar
Warren Dukes committed
384
};