DecoderAPI.cxx 14.2 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
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 84 85 86
	}

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

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

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

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

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

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

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

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

129
		decoder.initial_seek_pending = false;
130 131
	}

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

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

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

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

154
	return dc.command;
155 156
}

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

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

168
	dc.Lock();
169

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

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

182
		decoder.initial_seek_running = false;
183
		decoder.timestamp = dc.start_time.ToDoubleS();
184
		dc.Unlock();
185 186 187
		return;
	}

188 189
	if (decoder.seeking) {
		decoder.seeking = false;
190

191
		/* delete frames from the old song position */
192

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

198
		dc.pipe->Clear(*dc.buffer);
199

200
		decoder.timestamp = dc.seek_time.ToDoubleS();
201
	}
202

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

208 209
SongTime
decoder_seek_time(Decoder &decoder)
210
{
211
	const DecoderControl &dc = decoder.dc;
212

213
	assert(dc.pipe != nullptr);
214

215
	if (decoder.initial_seek_running)
216
		return dc.start_time;
217

218
	assert(dc.command == DecoderCommand::SEEK);
219

220
	decoder.seeking = true;
221

222
	return dc.seek_time;
223 224
}

225 226 227 228 229
uint64_t
decoder_seek_where_frame(Decoder &decoder)
{
	const DecoderControl &dc = decoder.dc;

230
	return decoder_seek_time(decoder).ToScale<uint64_t>(dc.in_audio_format.sample_rate);
231 232
}

233
void decoder_seek_error(Decoder & decoder)
234
{
235
	DecoderControl &dc = decoder.dc;
236

237
	assert(dc.pipe != nullptr);
238

239
	if (decoder.initial_seek_running) {
240 241
		/* d'oh, we can't seek to the sub-song start position,
		   what now? - no idea, ignoring the problem for now. */
242
		decoder.initial_seek_running = false;
243
		return;
244
	}
245

246
	assert(dc.command == DecoderCommand::SEEK);
247

248
	dc.seek_error = true;
249
	decoder.seeking = false;
250

251 252 253
	decoder_command_finished(decoder);
}

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
InputStream *
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;

	InputStream *is = InputStream::Open(uri, mutex, cond, error);
	if (is == nullptr)
		return nullptr;

	mutex.lock();
	while (true) {
		is->Update();
		if (is->IsReady()) {
			mutex.unlock();
			return is;
		}

		if (dc.command == DecoderCommand::STOP) {
			mutex.unlock();
			delete is;
			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
	is.Lock();
326 327 328

	while (true) {
		if (decoder_check_cancel_read(decoder)) {
329
			is.Unlock();
330 331 332
			return 0;
		}

333
		if (is.IsAvailable())
334 335
			break;

336
		is.cond.wait(is.mutex);
337
	}
338

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

344 345
	is.Unlock();

346
	if (gcc_unlikely(nbytes == 0 && error.IsDefined()))
347
		LogError(error);
348 349

	return nbytes;
Max Kellermann's avatar
Max Kellermann committed
350 351
}

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

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

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

391
	decoder.timestamp = t;
392 393
}

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

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

409
	assert(decoder.chunk == nullptr);
410

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

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

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

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

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

	decoder.song_tag = nullptr;
441

442 443
	delete decoder.stream_tag;
	decoder.stream_tag = tag;
444 445 446
	return true;
}

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

456 457 458
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
	assert(length % dc.in_audio_format.GetFrameSize() == 0);
459

460
	dc.Lock();
461
	cmd = decoder_get_virtual_command(decoder);
462
	dc.Unlock();
463

464
	if (cmd == DecoderCommand::STOP || cmd == DecoderCommand::SEEK ||
465
	    length == 0)
466
		return cmd;
467

468 469 470
	assert(!decoder.initial_seek_pending);
	assert(!decoder.initial_seek_running);

471 472 473
	/* send stream tags */

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

484
		if (cmd != DecoderCommand::NONE)
485
			return cmd;
486 487
	}

488 489 490
	if (decoder.convert != nullptr) {
		assert(dc.in_audio_format != dc.out_audio_format);

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

		data = result.data;
		length = result.size;
504 505
	} else {
		assert(dc.in_audio_format == dc.out_audio_format);
Max Kellermann's avatar
Max Kellermann committed
506 507
	}

508
	while (length > 0) {
509
		MusicChunk *chunk;
510 511
		bool full;

512
		chunk = decoder.GetChunk();
513
		if (chunk == nullptr) {
514 515
			assert(dc.command != DecoderCommand::NONE);
			return dc.command;
516 517
		}

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

529
		const size_t nbytes = std::min(dest.size, length);
530 531 532

		/* copy the buffer */

533
		memcpy(dest.data, data, nbytes);
534 535 536

		/* expand the music pipe chunk */

537
		full = chunk->Expand(dc.out_audio_format, nbytes);
538 539
		if (full) {
			/* the chunk is full, flush it */
540
			decoder.FlushChunk();
541
		}
542

543
		data = (const uint8_t *)data + nbytes;
544
		length -= nbytes;
545

546
		decoder.timestamp += (double)nbytes /
547
			dc.out_audio_format.GetTimeToSize();
548

549 550
		if (dc.end_time.IsPositive() &&
		    decoder.timestamp >= dc.end_time.ToDoubleS())
551 552
			/* the end of this range has been reached:
			   stop decoding */
553
			return DecoderCommand::STOP;
Max Kellermann's avatar
Max Kellermann committed
554 555
	}

556
	return DecoderCommand::NONE;
Max Kellermann's avatar
Max Kellermann committed
557
}
558

559
DecoderCommand
560
decoder_tag(Decoder &decoder, InputStream *is,
561
	    Tag &&tag)
562
{
563
	gcc_unused const DecoderControl &dc = decoder.dc;
564
	DecoderCommand cmd;
565

566 567
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
568 569 570

	/* save the tag */

571
	delete decoder.decoder_tag;
572
	decoder.decoder_tag = new Tag(std::move(tag));
573 574

	/* check for a new stream tag */
575

576
	update_stream_tag(decoder, is);
577

578 579
	/* check if we're seeking */

580
	if (decoder_prepare_initial_seek(decoder))
581 582 583
		/* during initial seek, no music chunk must be created
		   until seeking is finished; skip the rest of the
		   function here */
584
		return DecoderCommand::SEEK;
585

586
	/* send tag to music pipe */
587

588
	if (decoder.stream_tag != nullptr) {
589
		/* merge with tag from input stream */
Max Kellermann's avatar
Max Kellermann committed
590
		Tag *merged;
591

592 593
		merged = Tag::Merge(*decoder.stream_tag,
				    *decoder.decoder_tag);
Max Kellermann's avatar
Max Kellermann committed
594 595
		cmd = do_send_tag(decoder, *merged);
		delete merged;
596 597
	} else
		/* send only the decoder tag */
598
		cmd = do_send_tag(decoder, *decoder.decoder_tag);
599

600
	return cmd;
601
}
602

603
void
604
decoder_replay_gain(Decoder &decoder,
605
		    const ReplayGainInfo *replay_gain_info)
606
{
607
	if (replay_gain_info != nullptr) {
608 609 610 611
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

612
		if (REPLAY_GAIN_OFF != replay_gain_mode) {
613
			ReplayGainMode rgm = replay_gain_mode;
614 615 616
			if (rgm != REPLAY_GAIN_ALBUM)
				rgm = REPLAY_GAIN_TRACK;

617 618 619 620 621 622
			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);
623 624
		}

625 626
		decoder.replay_gain_info = *replay_gain_info;
		decoder.replay_gain_serial = serial;
627

628
		if (decoder.chunk != nullptr) {
629 630 631
			/* flush the current chunk because the new
			   replay gain values affect the following
			   samples */
632
			decoder.FlushChunk();
633 634
		}
	} else
635
		decoder.replay_gain_serial = 0;
636
}
637 638

void
639
decoder_mixramp(Decoder &decoder, MixRampInfo &&mix_ramp)
640
{
641
	DecoderControl &dc = decoder.dc;
642

643
	dc.SetMixRamp(std::move(mix_ramp));
644
}