DecoderAPI.cxx 13.1 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
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.
18 19
 */

20
#include "config.h"
21
#include "DecoderAPI.hxx"
22
#include "DecoderError.hxx"
23
#include "pcm/PcmConvert.hxx"
24
#include "AudioConfig.hxx"
25
#include "ReplayGainConfig.hxx"
26 27 28
#include "MusicChunk.hxx"
#include "MusicBuffer.hxx"
#include "MusicPipe.hxx"
29 30
#include "DecoderControl.hxx"
#include "DecoderInternal.hxx"
31
#include "DetachedSong.hxx"
Max Kellermann's avatar
Max Kellermann committed
32
#include "input/InputStream.hxx"
33
#include "util/Error.hxx"
34
#include "Log.hxx"
35

36
#include <assert.h>
Max Kellermann's avatar
Max Kellermann committed
37
#include <string.h>
38
#include <math.h>
39

40
void
41
decoder_initialized(Decoder &decoder,
42
		    const AudioFormat audio_format,
43
		    bool seekable, float total_time)
44
{
45
	DecoderControl &dc = decoder.dc;
46
	struct audio_format_string af_string;
47

48 49
	assert(dc.state == DecoderState::START);
	assert(dc.pipe != nullptr);
50
	assert(decoder.convert == nullptr);
51 52 53
	assert(decoder.stream_tag == nullptr);
	assert(decoder.decoder_tag == nullptr);
	assert(!decoder.seeking);
54 55
	assert(audio_format.IsDefined());
	assert(audio_format.IsValid());
56

57 58
	dc.in_audio_format = audio_format;
	dc.out_audio_format = getOutputAudioFormat(audio_format);
59

60 61
	dc.seekable = seekable;
	dc.total_time = total_time;
62

63
	FormatDebug(decoder_domain, "audio_format=%s, seekable=%s",
64
		    audio_format_to_string(dc.in_audio_format, &af_string),
65
		    seekable ? "true" : "false");
66

67
	if (dc.in_audio_format != dc.out_audio_format) {
68
		FormatDebug(decoder_domain, "converting to %s",
69
			    audio_format_to_string(dc.out_audio_format,
70
						   &af_string));
71 72

		decoder.convert = new PcmConvert();
73 74 75 76 77 78

		Error error;
		if (!decoder.convert->Open(dc.in_audio_format,
					   dc.out_audio_format,
					   error))
			decoder.error = std::move(error);
79 80 81 82 83 84
	}

	dc.Lock();
	dc.state = DecoderState::DECODE;
	dc.client_cond.signal();
	dc.Unlock();
85
}
Max Kellermann's avatar
Max Kellermann committed
86

87
/**
88 89
 * Checks if we need an "initial seek".  If so, then the initial seek
 * is prepared, and the function returns true.
90
 */
91
gcc_pure
92
static bool
93
decoder_prepare_initial_seek(Decoder &decoder)
94
{
95
	const DecoderControl &dc = decoder.dc;
96
	assert(dc.pipe != nullptr);
97

98
	if (dc.state != DecoderState::DECODE)
99 100 101 102 103
		/* wait until the decoder has finished initialisation
		   (reading file headers etc.) before emitting the
		   virtual "SEEK" command */
		return false;

104
	if (decoder.initial_seek_running)
105 106 107
		/* initial seek has already begun - override any other
		   command */
		return true;
108

109
	if (decoder.initial_seek_pending) {
110
		if (!dc.seekable) {
111
			/* seeking is not possible */
112
			decoder.initial_seek_pending = false;
113 114 115
			return false;
		}

116
		if (dc.command == DecoderCommand::NONE) {
117 118
			/* begin initial seek */

119 120
			decoder.initial_seek_pending = false;
			decoder.initial_seek_running = true;
121
			return true;
122 123
		}

124 125 126
		/* skip initial seek when there's another command
		   (e.g. STOP) */

127
		decoder.initial_seek_pending = false;
128 129
	}

130 131 132 133 134 135 136 137
	return false;
}

/**
 * Returns the current decoder command.  May return a "virtual"
 * synthesized command, e.g. to seek to the beginning of the CUE
 * track.
 */
138
gcc_pure
139
static DecoderCommand
140
decoder_get_virtual_command(Decoder &decoder)
141
{
142 143 144 145
	if (decoder.error.IsDefined())
		/* an error has occurred: stop the decoder plugin */
		return DecoderCommand::STOP;

146
	const DecoderControl &dc = decoder.dc;
147
	assert(dc.pipe != nullptr);
148 149

	if (decoder_prepare_initial_seek(decoder))
150
		return DecoderCommand::SEEK;
151

152
	return dc.command;
153 154
}

155
DecoderCommand
156
decoder_get_command(Decoder &decoder)
157 158 159 160
{
	return decoder_get_virtual_command(decoder);
}

161
void
162
decoder_command_finished(Decoder &decoder)
163
{
164
	DecoderControl &dc = decoder.dc;
165

166
	dc.Lock();
167

168
	assert(dc.command != DecoderCommand::NONE ||
169
	       decoder.initial_seek_running);
170
	assert(dc.command != DecoderCommand::SEEK ||
171 172
	       decoder.initial_seek_running ||
	       dc.seek_error || decoder.seeking);
173
	assert(dc.pipe != nullptr);
174

175 176 177
	if (decoder.initial_seek_running) {
		assert(!decoder.seeking);
		assert(decoder.chunk == nullptr);
178
		assert(dc.pipe->IsEmpty());
179

180 181
		decoder.initial_seek_running = false;
		decoder.timestamp = dc.start_ms / 1000.;
182
		dc.Unlock();
183 184 185
		return;
	}

186 187
	if (decoder.seeking) {
		decoder.seeking = false;
188

189
		/* delete frames from the old song position */
190

191 192 193
		if (decoder.chunk != nullptr) {
			dc.buffer->Return(decoder.chunk);
			decoder.chunk = nullptr;
194 195
		}

196
		dc.pipe->Clear(*dc.buffer);
197

198
		decoder.timestamp = dc.seek_where;
199
	}
200

201 202 203
	dc.command = DecoderCommand::NONE;
	dc.client_cond.signal();
	dc.Unlock();
204 205
}

206
double decoder_seek_where(gcc_unused Decoder & decoder)
207
{
208
	const DecoderControl &dc = decoder.dc;
209

210
	assert(dc.pipe != nullptr);
211

212
	if (decoder.initial_seek_running)
213
		return dc.start_ms / 1000.;
214

215
	assert(dc.command == DecoderCommand::SEEK);
216

217
	decoder.seeking = true;
218

219
	return dc.seek_where;
220 221
}

222
void decoder_seek_error(Decoder & decoder)
223
{
224
	DecoderControl &dc = decoder.dc;
225

226
	assert(dc.pipe != nullptr);
227

228
	if (decoder.initial_seek_running) {
229 230
		/* d'oh, we can't seek to the sub-song start position,
		   what now? - no idea, ignoring the problem for now. */
231
		decoder.initial_seek_running = false;
232
		return;
233
	}
234

235
	assert(dc.command == DecoderCommand::SEEK);
236

237
	dc.seek_error = true;
238
	decoder.seeking = false;
239

240 241 242
	decoder_command_finished(decoder);
}

243 244 245 246
/**
 * Should be read operation be cancelled?  That is the case when the
 * player thread has sent a command such as "STOP".
 */
247
gcc_pure
248
static inline bool
249
decoder_check_cancel_read(const Decoder *decoder)
250
{
251
	if (decoder == nullptr)
252 253
		return false;

254
	const DecoderControl &dc = decoder->dc;
255
	if (dc.command == DecoderCommand::NONE)
256 257 258 259
		return false;

	/* ignore the SEEK command during initialization, the plugin
	   should handle that after it has initialized successfully */
260 261
	if (dc.command == DecoderCommand::SEEK &&
	    (dc.state == DecoderState::START || decoder->seeking))
262 263 264 265 266
		return false;

	return true;
}

267 268
size_t
decoder_read(Decoder *decoder,
269
	     InputStream &is,
270
	     void *buffer, size_t length)
Max Kellermann's avatar
Max Kellermann committed
271
{
272
	/* XXX don't allow decoder==nullptr */
Max Kellermann's avatar
Max Kellermann committed
273

274
	assert(decoder == nullptr ||
275 276
	       decoder->dc.state == DecoderState::START ||
	       decoder->dc.state == DecoderState::DECODE);
277
	assert(buffer != nullptr);
Max Kellermann's avatar
Max Kellermann committed
278

279 280 281
	if (length == 0)
		return 0;

282
	is.Lock();
283 284 285

	while (true) {
		if (decoder_check_cancel_read(decoder)) {
286
			is.Unlock();
287 288 289
			return 0;
		}

290
		if (is.IsAvailable())
291 292
			break;

293
		is.cond.wait(is.mutex);
294
	}
295

296
	Error error;
297
	size_t nbytes = is.Read(buffer, length, error);
298
	assert(nbytes == 0 || !error.IsDefined());
299
	assert(nbytes > 0 || error.IsDefined() || is.IsEOF());
Max Kellermann's avatar
Max Kellermann committed
300

301 302
	is.Unlock();

303
	if (gcc_unlikely(nbytes == 0 && error.IsDefined()))
304
		LogError(error);
305 306

	return nbytes;
Max Kellermann's avatar
Max Kellermann committed
307 308
}

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
bool
decoder_read_full(Decoder *decoder, InputStream &is,
		  void *_buffer, size_t size)
{
	uint8_t *buffer = (uint8_t *)_buffer;

	while (size > 0) {
		size_t nbytes = decoder_read(decoder, is, buffer, size);
		if (nbytes == 0)
			return false;

		buffer += nbytes;
		size -= nbytes;
	}

	return true;
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
bool
decoder_skip(Decoder *decoder, InputStream &is, size_t size)
{
	while (size > 0) {
		char buffer[1024];
		size_t nbytes = decoder_read(decoder, is, buffer,
					     std::min(sizeof(buffer), size));
		if (nbytes == 0)
			return false;

		size -= nbytes;
	}

	return true;
}

343
void
344
decoder_timestamp(Decoder &decoder, double t)
345 346 347
{
	assert(t >= 0);

348
	decoder.timestamp = t;
349 350
}

Max Kellermann's avatar
Max Kellermann committed
351
/**
352 353
 * Sends a #tag as-is to the music pipe.  Flushes the current chunk
 * (decoder.chunk) if there is one.
Max Kellermann's avatar
Max Kellermann committed
354
 */
355
static DecoderCommand
356
do_send_tag(Decoder &decoder, const Tag &tag)
Max Kellermann's avatar
Max Kellermann committed
357
{
358
	struct music_chunk *chunk;
Max Kellermann's avatar
Max Kellermann committed
359

360
	if (decoder.chunk != nullptr) {
361 362
		/* there is a partial chunk - flush it, we want the
		   tag in a new chunk */
363
		decoder.FlushChunk();
364 365
	}

366
	assert(decoder.chunk == nullptr);
367

368
	chunk = decoder.GetChunk();
369
	if (chunk == nullptr) {
370 371
		assert(decoder.dc.command != DecoderCommand::NONE);
		return decoder.dc.command;
372 373
	}

Max Kellermann's avatar
Max Kellermann committed
374
	chunk->tag = new Tag(tag);
375
	return DecoderCommand::NONE;
376 377
}

378
static bool
379
update_stream_tag(Decoder &decoder, InputStream *is)
380
{
Max Kellermann's avatar
Max Kellermann committed
381
	Tag *tag;
382

383
	tag = is != nullptr
384
		? is->LockReadTag()
385 386
		: nullptr;
	if (tag == nullptr) {
387
		tag = decoder.song_tag;
388
		if (tag == nullptr)
389 390 391 392
			return false;

		/* no stream tag present - submit the song tag
		   instead */
393
		decoder.song_tag = nullptr;
394
	}
395

396 397
	delete decoder.stream_tag;
	decoder.stream_tag = tag;
398 399 400
	return true;
}

401
DecoderCommand
402
decoder_data(Decoder &decoder,
403
	     InputStream *is,
404
	     const void *data, size_t length,
405
	     uint16_t kbit_rate)
Max Kellermann's avatar
Max Kellermann committed
406
{
407
	DecoderControl &dc = decoder.dc;
408
	DecoderCommand cmd;
Max Kellermann's avatar
Max Kellermann committed
409

410 411 412
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
	assert(length % dc.in_audio_format.GetFrameSize() == 0);
413

414
	dc.Lock();
415
	cmd = decoder_get_virtual_command(decoder);
416
	dc.Unlock();
417

418
	if (cmd == DecoderCommand::STOP || cmd == DecoderCommand::SEEK ||
419
	    length == 0)
420
		return cmd;
421

422 423 424
	/* send stream tags */

	if (update_stream_tag(decoder, is)) {
425
		if (decoder.decoder_tag != nullptr) {
426
			/* merge with tag from decoder plugin */
427 428
			Tag *tag = Tag::Merge(*decoder.decoder_tag,
					      *decoder.stream_tag);
Max Kellermann's avatar
Max Kellermann committed
429 430
			cmd = do_send_tag(decoder, *tag);
			delete tag;
431 432
		} else
			/* send only the stream tag */
433
			cmd = do_send_tag(decoder, *decoder.stream_tag);
434

435
		if (cmd != DecoderCommand::NONE)
436
			return cmd;
437 438
	}

439 440 441
	if (decoder.convert != nullptr) {
		assert(dc.in_audio_format != dc.out_audio_format);

442
		Error error;
443
		data = decoder.convert->Convert(data, length,
444 445
						&length,
						error);
446
		if (data == nullptr) {
447 448 449
			/* the PCM conversion has failed - stop
			   playback, since we have no better way to
			   bail out */
450
			LogError(error);
451
			return DecoderCommand::STOP;
452
		}
453 454
	} else {
		assert(dc.in_audio_format == dc.out_audio_format);
Max Kellermann's avatar
Max Kellermann committed
455 456
	}

457
	while (length > 0) {
458 459 460
		struct music_chunk *chunk;
		bool full;

461
		chunk = decoder.GetChunk();
462
		if (chunk == nullptr) {
463 464
			assert(dc.command != DecoderCommand::NONE);
			return dc.command;
465 466
		}

467 468 469
		const auto dest =
			chunk->Write(dc.out_audio_format,
				     decoder.timestamp -
470
				     dc.song->GetStartMS() / 1000.0,
471 472
				     kbit_rate);
		if (dest.IsNull()) {
473
			/* the chunk is full, flush it */
474
			decoder.FlushChunk();
475
			continue;
Max Kellermann's avatar
Max Kellermann committed
476
		}
477

478
		size_t nbytes = dest.size;
479 480 481 482 483 484 485
		assert(nbytes > 0);

		if (nbytes > length)
			nbytes = length;

		/* copy the buffer */

486
		memcpy(dest.data, data, nbytes);
487 488 489

		/* expand the music pipe chunk */

490
		full = chunk->Expand(dc.out_audio_format, nbytes);
491 492
		if (full) {
			/* the chunk is full, flush it */
493
			decoder.FlushChunk();
494
		}
495

496
		data = (const uint8_t *)data + nbytes;
497
		length -= nbytes;
498

499
		decoder.timestamp += (double)nbytes /
500
			dc.out_audio_format.GetTimeToSize();
501

502
		if (dc.end_ms > 0 &&
503
		    decoder.timestamp >= dc.end_ms / 1000.0)
504 505
			/* the end of this range has been reached:
			   stop decoding */
506
			return DecoderCommand::STOP;
Max Kellermann's avatar
Max Kellermann committed
507 508
	}

509
	return DecoderCommand::NONE;
Max Kellermann's avatar
Max Kellermann committed
510
}
511

512
DecoderCommand
513
decoder_tag(Decoder &decoder, InputStream *is,
514
	    Tag &&tag)
515
{
516
	gcc_unused const DecoderControl &dc = decoder.dc;
517
	DecoderCommand cmd;
518

519 520
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
521 522 523

	/* save the tag */

524 525
	delete decoder.decoder_tag;
	decoder.decoder_tag = new Tag(tag);
526 527

	/* check for a new stream tag */
528

529
	update_stream_tag(decoder, is);
530

531 532
	/* check if we're seeking */

533
	if (decoder_prepare_initial_seek(decoder))
534 535 536
		/* during initial seek, no music chunk must be created
		   until seeking is finished; skip the rest of the
		   function here */
537
		return DecoderCommand::SEEK;
538

539
	/* send tag to music pipe */
540

541
	if (decoder.stream_tag != nullptr) {
542
		/* merge with tag from input stream */
Max Kellermann's avatar
Max Kellermann committed
543
		Tag *merged;
544

545 546
		merged = Tag::Merge(*decoder.stream_tag,
				    *decoder.decoder_tag);
Max Kellermann's avatar
Max Kellermann committed
547 548
		cmd = do_send_tag(decoder, *merged);
		delete merged;
549 550
	} else
		/* send only the decoder tag */
551
		cmd = do_send_tag(decoder, *decoder.decoder_tag);
552

553
	return cmd;
554
}
555

556
void
557
decoder_replay_gain(Decoder &decoder,
558
		    const ReplayGainInfo *replay_gain_info)
559
{
560
	if (replay_gain_info != nullptr) {
561 562 563 564
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

565
		if (REPLAY_GAIN_OFF != replay_gain_mode) {
566
			ReplayGainMode rgm = replay_gain_mode;
567 568 569
			if (rgm != REPLAY_GAIN_ALBUM)
				rgm = REPLAY_GAIN_TRACK;

570 571 572 573 574 575
			const auto &tuple = replay_gain_info->tuples[rgm];
			const auto scale =
				tuple.CalculateScale(replay_gain_preamp,
						     replay_gain_missing_preamp,
						     replay_gain_limit);
			decoder.dc.replay_gain_db = 20.0 * log10f(scale);
576 577
		}

578 579
		decoder.replay_gain_info = *replay_gain_info;
		decoder.replay_gain_serial = serial;
580

581
		if (decoder.chunk != nullptr) {
582 583 584
			/* flush the current chunk because the new
			   replay gain values affect the following
			   samples */
585
			decoder.FlushChunk();
586 587
		}
	} else
588
		decoder.replay_gain_serial = 0;
589
}
590 591

void
592
decoder_mixramp(Decoder &decoder, MixRampInfo &&mix_ramp)
593
{
594
	DecoderControl &dc = decoder.dc;
595

596
	dc.SetMixRamp(std::move(mix_ramp));
597
}