FlacDecoderPlugin.cxx 9.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 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 "fs/NarrowPath.hxx"
28
#include "util/Error.hxx"
29
#include "Log.hxx"
30

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

35
static void flacPrintErroredState(FLAC__StreamDecoderState state)
36
{
Avuton Olrich's avatar
Avuton Olrich committed
37
	switch (state) {
38 39 40 41 42 43
	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;
44

45 46 47 48 49
	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:
50
		break;
Warren Dukes's avatar
Warren Dukes committed
51
	}
52

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

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

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

69 70 71 72 73 74 75 76 77 78 79 80
	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
81 82
}

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

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

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

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

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

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

	return sd;
}

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

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

146
	if (data->initialized) {
147
		/* done */
148 149 150 151 152

		const auto duration2 =
			SongTime::FromScale<uint64_t>(data->total_frames,
						      data->audio_format.sample_rate);

153
		decoder_initialized(data->decoder, data->audio_format,
154
				    data->input_stream.IsSeekable(),
155
				    duration2);
156
		return true;
157
	}
158

159
	if (data->input_stream.IsSeekable())
160 161 162 163 164 165 166
		/* 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);
167
	return data->initialized;
168 169
}

170
static void
171
flac_decoder_loop(struct flac_data *data, FLAC__StreamDecoder *flac_dec,
172 173
		  FLAC__uint64 t_start, FLAC__uint64 t_end)
{
174
	Decoder &decoder = data->decoder;
175

176 177
	data->first_frame = t_start;

178
	while (true) {
179
		DecoderCommand cmd;
Max Kellermann's avatar
Max Kellermann committed
180
		if (!data->tag.IsEmpty()) {
181
			cmd = decoder_tag(data->decoder, data->input_stream,
Max Kellermann's avatar
Max Kellermann committed
182 183
					  std::move(data->tag));
			data->tag.Clear();
184 185 186
		} else
			cmd = decoder_get_command(decoder);

187
		if (cmd == DecoderCommand::SEEK) {
188
			FLAC__uint64 seek_sample = t_start +
189
				decoder_seek_where_frame(decoder);
190 191
			if (seek_sample >= t_start &&
			    (t_end == 0 || seek_sample <= t_end) &&
192
			    FLAC__stream_decoder_seek_absolute(flac_dec, seek_sample)) {
193 194 195 196 197
				data->next_frame = seek_sample;
				data->position = 0;
				decoder_command_finished(decoder);
			} else
				decoder_seek_error(decoder);
198
		} else if (cmd == DecoderCommand::STOP ||
199
			   FLAC__stream_decoder_get_state(flac_dec) == FLAC__STREAM_DECODER_END_OF_STREAM)
200 201 202 203 204 205
			break;

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

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

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

static FLAC__StreamDecoderInitStatus
stream_init_flac(FLAC__StreamDecoder *flac_dec, struct flac_data *data)
{
	return FLAC__stream_decoder_init_stream(flac_dec,
235 236 237 238 239
						FlacInput::Read,
						FlacInput::Seek,
						FlacInput::Tell,
						FlacInput::Length,
						FlacInput::Eof,
240
						flac_write_cb,
241
						flacMetadata,
242
						FlacInput::Error,
243 244 245 246 247 248 249 250 251 252 253
						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);
}

254
static void
255
flac_decode_internal(Decoder &decoder,
256
		     InputStream &input_stream,
257
		     bool is_ogg)
258
{
259
	FLAC__StreamDecoder *flac_dec;
260

261
	flac_dec = flac_decoder_new();
262
	if (flac_dec == nullptr)
263
		return;
264

265
	struct flac_data data(decoder, input_stream);
266

267 268 269 270
	FLAC__StreamDecoderInitStatus status =
		stream_init(flac_dec, &data, is_ogg);
	if (status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
		FLAC__stream_decoder_delete(flac_dec);
271 272
		LogWarning(flac_domain,
			   FLAC__StreamDecoderInitStatusString[status]);
273
		return;
274 275
	}

276
	if (!flac_decoder_initialize(&data, flac_dec, 0)) {
277
		FLAC__stream_decoder_finish(flac_dec);
278 279
		FLAC__stream_decoder_delete(flac_dec);
		return;
280 281
	}

282
	flac_decoder_loop(&data, flac_dec, 0, 0);
283

284
	FLAC__stream_decoder_finish(flac_dec);
285
	FLAC__stream_decoder_delete(flac_dec);
286 287
}

288
static void
289
flac_decode(Decoder &decoder, InputStream &input_stream)
290
{
Max Kellermann's avatar
Max Kellermann committed
291
	flac_decode_internal(decoder, input_stream, false);
292 293
}

294
static bool
295
oggflac_init(gcc_unused const ConfigBlock &block)
296 297 298 299
{
	return !!FLAC_API_SUPPORTS_OGG_FLAC;
}

300
static bool
301
oggflac_scan_file(Path path_fs,
302
		  const TagHandler &handler, void *handler_ctx)
303
{
304
	FlacMetadataChain chain;
305
	if (!chain.ReadOgg(NarrowPath(path_fs))) {
306 307 308
		FormatDebug(flac_domain,
			    "Failed to read OggFLAC tags: %s",
			    chain.GetStatusString());
309
		return false;
310 311
	}

312
	chain.Scan(handler, handler_ctx);
313
	return true;
314 315
}

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

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

332
static void
333
oggflac_decode(Decoder &decoder, InputStream &input_stream)
334
{
335
	if (ogg_codec_detect(&decoder, input_stream) != OGG_CODEC_FLAC)
336
		return;
337

338
	/* rewind the stream, because ogg_codec_detect() has
339
	   moved it */
340
	input_stream.LockRewind(IgnoreError());
341

Max Kellermann's avatar
Max Kellermann committed
342
	flac_decode_internal(decoder, input_stream, true);
343 344
}

345
static const char *const oggflac_suffixes[] = { "ogg", "oga", nullptr };
346 347 348
static const char *const oggflac_mime_types[] = {
	"application/ogg",
	"application/x-ogg",
349 350 351
	"audio/ogg",
	"audio/x-flac+ogg",
	"audio/x-ogg",
352
	nullptr
353
};
354

355
const struct DecoderPlugin oggflac_decoder_plugin = {
356 357 358 359 360 361
	"oggflac",
	oggflac_init,
	nullptr,
	oggflac_decode,
	nullptr,
	oggflac_scan_file,
362
	oggflac_scan_stream,
363 364 365
	nullptr,
	oggflac_suffixes,
	oggflac_mime_types,
366
};
367

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

377
const struct DecoderPlugin flac_decoder_plugin = {
378 379 380 381 382 383
	"flac",
	nullptr,
	nullptr,
	flac_decode,
	nullptr,
	flac_scan_file,
384
	flac_scan_stream,
385 386 387
	nullptr,
	flac_suffixes,
	flac_mime_types,
Warren Dukes's avatar
Warren Dukes committed
388
};