DecoderAPI.cxx 14.2 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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 "util/ConstBuffer.hxx"
35
#include "Log.hxx"
36

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

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

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

59 60
	dc.in_audio_format = audio_format;
	dc.out_audio_format = getOutputAudioFormat(audio_format);
61

62
	dc.seekable = seekable;
63
	dc.total_time = duration;
64

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

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

		decoder.convert = new PcmConvert();
75 76 77 78 79 80

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

83
	const ScopeLock protect(dc.mutex);
84 85
	dc.state = DecoderState::DECODE;
	dc.client_cond.signal();
86
}
Max Kellermann's avatar
Max Kellermann committed
87

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

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

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

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

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

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

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

128
		decoder.initial_seek_pending = false;
129 130
	}

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

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

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

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

153
	return dc.command;
154 155
}

156 157 158 159 160 161 162 163
gcc_pure
static DecoderCommand
decoder_lock_get_virtual_command(Decoder &decoder)
{
	const ScopeLock protect(decoder.dc.mutex);
	return decoder_get_virtual_command(decoder);
}

164
DecoderCommand
165
decoder_get_command(Decoder &decoder)
166 167 168 169
{
	return decoder_get_virtual_command(decoder);
}

170
void
171
decoder_command_finished(Decoder &decoder)
172
{
173
	DecoderControl &dc = decoder.dc;
174

175
	const ScopeLock protect(dc.mutex);
176

177
	assert(dc.command != DecoderCommand::NONE ||
178
	       decoder.initial_seek_running);
179
	assert(dc.command != DecoderCommand::SEEK ||
180 181
	       decoder.initial_seek_running ||
	       dc.seek_error || decoder.seeking);
182
	assert(dc.pipe != nullptr);
183

184 185 186
	if (decoder.initial_seek_running) {
		assert(!decoder.seeking);
		assert(decoder.chunk == nullptr);
187
		assert(dc.pipe->IsEmpty());
188

189
		decoder.initial_seek_running = false;
190
		decoder.timestamp = dc.start_time.ToDoubleS();
191 192 193
		return;
	}

194 195
	if (decoder.seeking) {
		decoder.seeking = false;
196

197
		/* delete frames from the old song position */
198

199 200 201
		if (decoder.chunk != nullptr) {
			dc.buffer->Return(decoder.chunk);
			decoder.chunk = nullptr;
202 203
		}

204
		dc.pipe->Clear(*dc.buffer);
205

206
		decoder.timestamp = dc.seek_time.ToDoubleS();
207
	}
208

209 210
	dc.command = DecoderCommand::NONE;
	dc.client_cond.signal();
211 212
}

213 214
SongTime
decoder_seek_time(Decoder &decoder)
215
{
216
	const DecoderControl &dc = decoder.dc;
217

218
	assert(dc.pipe != nullptr);
219

220
	if (decoder.initial_seek_running)
221
		return dc.start_time;
222

223
	assert(dc.command == DecoderCommand::SEEK);
224

225
	decoder.seeking = true;
226

227
	return dc.seek_time;
228 229
}

230 231 232 233 234
uint64_t
decoder_seek_where_frame(Decoder &decoder)
{
	const DecoderControl &dc = decoder.dc;

235
	return decoder_seek_time(decoder).ToScale<uint64_t>(dc.in_audio_format.sample_rate);
236 237
}

238
void decoder_seek_error(Decoder & decoder)
239
{
240
	DecoderControl &dc = decoder.dc;
241

242
	assert(dc.pipe != nullptr);
243

244
	if (decoder.initial_seek_running) {
245 246
		/* d'oh, we can't seek to the sub-song start position,
		   what now? - no idea, ignoring the problem for now. */
247
		decoder.initial_seek_running = false;
248
		return;
249
	}
250

251
	assert(dc.command == DecoderCommand::SEEK);
252

253
	dc.seek_error = true;
254
	decoder.seeking = false;
255

256 257 258
	decoder_command_finished(decoder);
}

259
InputStreamPtr
260 261 262 263 264 265 266 267 268
decoder_open_uri(Decoder &decoder, const char *uri, Error &error)
{
	assert(decoder.dc.state == DecoderState::START ||
	       decoder.dc.state == DecoderState::DECODE);

	DecoderControl &dc = decoder.dc;
	Mutex &mutex = dc.mutex;
	Cond &cond = dc.cond;

269 270
	auto is = InputStream::Open(uri, mutex, cond, error);
	if (!is)
271 272
		return nullptr;

273
	const ScopeLock lock(mutex);
274 275
	while (true) {
		is->Update();
276
		if (is->IsReady())
277 278
			return is;

279
		if (dc.command == DecoderCommand::STOP)
280 281 282 283 284 285
			return nullptr;

		cond.wait(mutex);
	}
}

286 287 288 289
/**
 * Should be read operation be cancelled?  That is the case when the
 * player thread has sent a command such as "STOP".
 */
290
gcc_pure
291
static inline bool
292
decoder_check_cancel_read(const Decoder *decoder)
293
{
294
	if (decoder == nullptr)
295 296
		return false;

297
	const DecoderControl &dc = decoder->dc;
298
	if (dc.command == DecoderCommand::NONE)
299 300 301 302
		return false;

	/* ignore the SEEK command during initialization, the plugin
	   should handle that after it has initialized successfully */
303 304
	if (dc.command == DecoderCommand::SEEK &&
	    (dc.state == DecoderState::START || decoder->seeking))
305 306 307 308 309
		return false;

	return true;
}

310 311
size_t
decoder_read(Decoder *decoder,
312
	     InputStream &is,
313
	     void *buffer, size_t length)
Max Kellermann's avatar
Max Kellermann committed
314
{
315
	/* XXX don't allow decoder==nullptr */
Max Kellermann's avatar
Max Kellermann committed
316

317
	assert(decoder == nullptr ||
318 319
	       decoder->dc.state == DecoderState::START ||
	       decoder->dc.state == DecoderState::DECODE);
320
	assert(buffer != nullptr);
Max Kellermann's avatar
Max Kellermann committed
321

322 323 324
	if (length == 0)
		return 0;

325
	ScopeLock lock(is.mutex);
326 327

	while (true) {
328
		if (decoder_check_cancel_read(decoder))
329 330
			return 0;

331
		if (is.IsAvailable())
332 333
			break;

334
		is.cond.wait(is.mutex);
335
	}
336

337
	Error error;
338
	size_t nbytes = is.Read(buffer, length, error);
339
	assert(nbytes == 0 || !error.IsDefined());
340
	assert(nbytes > 0 || error.IsDefined() || is.IsEOF());
Max Kellermann's avatar
Max Kellermann committed
341

342
	lock.Unlock();
343

344
	if (gcc_unlikely(nbytes == 0 && error.IsDefined()))
345
		LogError(error);
346 347

	return nbytes;
Max Kellermann's avatar
Max Kellermann committed
348 349
}

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
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;
}

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
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;
}

384
void
385
decoder_timestamp(Decoder &decoder, double t)
386 387 388
{
	assert(t >= 0);

389
	decoder.timestamp = t;
390 391
}

Max Kellermann's avatar
Max Kellermann committed
392
/**
393 394
 * 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
395
 */
396
static DecoderCommand
397
do_send_tag(Decoder &decoder, const Tag &tag)
Max Kellermann's avatar
Max Kellermann committed
398
{
399
	MusicChunk *chunk;
Max Kellermann's avatar
Max Kellermann committed
400

401
	if (decoder.chunk != nullptr) {
402 403
		/* there is a partial chunk - flush it, we want the
		   tag in a new chunk */
404
		decoder.FlushChunk();
405 406
	}

407
	assert(decoder.chunk == nullptr);
408

409
	chunk = decoder.GetChunk();
410
	if (chunk == nullptr) {
411 412
		assert(decoder.dc.command != DecoderCommand::NONE);
		return decoder.dc.command;
413 414
	}

Max Kellermann's avatar
Max Kellermann committed
415
	chunk->tag = new Tag(tag);
416
	return DecoderCommand::NONE;
417 418
}

419
static bool
420
update_stream_tag(Decoder &decoder, InputStream *is)
421
{
Max Kellermann's avatar
Max Kellermann committed
422
	Tag *tag;
423

424
	tag = is != nullptr
425
		? is->LockReadTag()
426 427
		: nullptr;
	if (tag == nullptr) {
428
		tag = decoder.song_tag;
429
		if (tag == nullptr)
430 431 432 433
			return false;

		/* no stream tag present - submit the song tag
		   instead */
434 435 436 437 438
	} else
		/* discard the song tag; we don't need it */
		delete decoder.song_tag;

	decoder.song_tag = nullptr;
439

440 441
	delete decoder.stream_tag;
	decoder.stream_tag = tag;
442 443 444
	return true;
}

445
DecoderCommand
446
decoder_data(Decoder &decoder,
447
	     InputStream *is,
448
	     const void *data, size_t length,
449
	     uint16_t kbit_rate)
Max Kellermann's avatar
Max Kellermann committed
450
{
451
	DecoderControl &dc = decoder.dc;
Max Kellermann's avatar
Max Kellermann committed
452

453 454 455
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
	assert(length % dc.in_audio_format.GetFrameSize() == 0);
456

457
	DecoderCommand cmd = decoder_lock_get_virtual_command(decoder);
458

459
	if (cmd == DecoderCommand::STOP || cmd == DecoderCommand::SEEK ||
460
	    length == 0)
461
		return cmd;
462

463 464 465
	assert(!decoder.initial_seek_pending);
	assert(!decoder.initial_seek_running);

466 467 468
	/* send stream tags */

	if (update_stream_tag(decoder, is)) {
469
		if (decoder.decoder_tag != nullptr) {
470
			/* merge with tag from decoder plugin */
471 472
			Tag *tag = Tag::Merge(*decoder.decoder_tag,
					      *decoder.stream_tag);
Max Kellermann's avatar
Max Kellermann committed
473 474
			cmd = do_send_tag(decoder, *tag);
			delete tag;
475 476
		} else
			/* send only the stream tag */
477
			cmd = do_send_tag(decoder, *decoder.stream_tag);
478

479
		if (cmd != DecoderCommand::NONE)
480
			return cmd;
481 482
	}

483 484 485
	if (decoder.convert != nullptr) {
		assert(dc.in_audio_format != dc.out_audio_format);

486
		Error error;
487 488
		auto result = decoder.convert->Convert({data, length},
						       error);
489
		if (data == nullptr) {
490 491 492
			/* the PCM conversion has failed - stop
			   playback, since we have no better way to
			   bail out */
493
			LogError(error);
494
			return DecoderCommand::STOP;
495
		}
496 497 498

		data = result.data;
		length = result.size;
499 500
	} else {
		assert(dc.in_audio_format == dc.out_audio_format);
Max Kellermann's avatar
Max Kellermann committed
501 502
	}

503
	while (length > 0) {
504
		MusicChunk *chunk;
505 506
		bool full;

507
		chunk = decoder.GetChunk();
508
		if (chunk == nullptr) {
509 510
			assert(dc.command != DecoderCommand::NONE);
			return dc.command;
511 512
		}

513 514
		const auto dest =
			chunk->Write(dc.out_audio_format,
515 516
				     SongTime::FromS(decoder.timestamp) -
				     dc.song->GetStartTime(),
517
				     kbit_rate);
518
		if (dest.IsEmpty()) {
519
			/* the chunk is full, flush it */
520
			decoder.FlushChunk();
521
			continue;
Max Kellermann's avatar
Max Kellermann committed
522
		}
523

524
		const size_t nbytes = std::min(dest.size, length);
525 526 527

		/* copy the buffer */

528
		memcpy(dest.data, data, nbytes);
529 530 531

		/* expand the music pipe chunk */

532
		full = chunk->Expand(dc.out_audio_format, nbytes);
533 534
		if (full) {
			/* the chunk is full, flush it */
535
			decoder.FlushChunk();
536
		}
537

538
		data = (const uint8_t *)data + nbytes;
539
		length -= nbytes;
540

541
		decoder.timestamp += (double)nbytes /
542
			dc.out_audio_format.GetTimeToSize();
543

544 545
		if (dc.end_time.IsPositive() &&
		    decoder.timestamp >= dc.end_time.ToDoubleS())
546 547
			/* the end of this range has been reached:
			   stop decoding */
548
			return DecoderCommand::STOP;
Max Kellermann's avatar
Max Kellermann committed
549 550
	}

551
	return DecoderCommand::NONE;
Max Kellermann's avatar
Max Kellermann committed
552
}
553

554
DecoderCommand
555
decoder_tag(Decoder &decoder, InputStream *is,
556
	    Tag &&tag)
557
{
558
	gcc_unused const DecoderControl &dc = decoder.dc;
559
	DecoderCommand cmd;
560

561 562
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
563 564 565

	/* save the tag */

566
	delete decoder.decoder_tag;
567
	decoder.decoder_tag = new Tag(std::move(tag));
568 569

	/* check for a new stream tag */
570

571
	update_stream_tag(decoder, is);
572

573 574
	/* check if we're seeking */

575
	if (decoder_prepare_initial_seek(decoder))
576 577 578
		/* during initial seek, no music chunk must be created
		   until seeking is finished; skip the rest of the
		   function here */
579
		return DecoderCommand::SEEK;
580

581
	/* send tag to music pipe */
582

583
	if (decoder.stream_tag != nullptr) {
584
		/* merge with tag from input stream */
Max Kellermann's avatar
Max Kellermann committed
585
		Tag *merged;
586

587 588
		merged = Tag::Merge(*decoder.stream_tag,
				    *decoder.decoder_tag);
Max Kellermann's avatar
Max Kellermann committed
589 590
		cmd = do_send_tag(decoder, *merged);
		delete merged;
591 592
	} else
		/* send only the decoder tag */
593
		cmd = do_send_tag(decoder, *decoder.decoder_tag);
594

595
	return cmd;
596
}
597

598
void
599
decoder_replay_gain(Decoder &decoder,
600
		    const ReplayGainInfo *replay_gain_info)
601
{
602
	if (replay_gain_info != nullptr) {
603 604 605 606
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

607
		if (REPLAY_GAIN_OFF != replay_gain_mode) {
608
			ReplayGainMode rgm = replay_gain_mode;
609 610 611
			if (rgm != REPLAY_GAIN_ALBUM)
				rgm = REPLAY_GAIN_TRACK;

612 613 614 615 616 617
			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);
618 619
		}

620 621
		decoder.replay_gain_info = *replay_gain_info;
		decoder.replay_gain_serial = serial;
622

623
		if (decoder.chunk != nullptr) {
624 625 626
			/* flush the current chunk because the new
			   replay gain values affect the following
			   samples */
627
			decoder.FlushChunk();
628 629
		}
	} else
630
		decoder.replay_gain_serial = 0;
631
}
632 633

void
634
decoder_mixramp(Decoder &decoder, MixRampInfo &&mix_ramp)
635
{
636
	DecoderControl &dc = decoder.dc;
637

638
	dc.SetMixRamp(std::move(mix_ramp));
639
}