DecoderAPI.cxx 13.7 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
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);
	}
}

275 276 277 278
/**
 * Should be read operation be cancelled?  That is the case when the
 * player thread has sent a command such as "STOP".
 */
279
gcc_pure
280
static inline bool
281
decoder_check_cancel_read(const Decoder *decoder)
282
{
283
	if (decoder == nullptr)
284 285
		return false;

286
	const DecoderControl &dc = decoder->dc;
287
	if (dc.command == DecoderCommand::NONE)
288 289 290 291
		return false;

	/* ignore the SEEK command during initialization, the plugin
	   should handle that after it has initialized successfully */
292 293
	if (dc.command == DecoderCommand::SEEK &&
	    (dc.state == DecoderState::START || decoder->seeking))
294 295 296 297 298
		return false;

	return true;
}

299 300
size_t
decoder_read(Decoder *decoder,
301
	     InputStream &is,
302
	     void *buffer, size_t length)
Max Kellermann's avatar
Max Kellermann committed
303
{
304
	/* XXX don't allow decoder==nullptr */
Max Kellermann's avatar
Max Kellermann committed
305

306
	assert(decoder == nullptr ||
307 308
	       decoder->dc.state == DecoderState::START ||
	       decoder->dc.state == DecoderState::DECODE);
309
	assert(buffer != nullptr);
Max Kellermann's avatar
Max Kellermann committed
310

311 312 313
	if (length == 0)
		return 0;

314
	is.Lock();
315 316 317

	while (true) {
		if (decoder_check_cancel_read(decoder)) {
318
			is.Unlock();
319 320 321
			return 0;
		}

322
		if (is.IsAvailable())
323 324
			break;

325
		is.cond.wait(is.mutex);
326
	}
327

328
	Error error;
329
	size_t nbytes = is.Read(buffer, length, error);
330
	assert(nbytes == 0 || !error.IsDefined());
331
	assert(nbytes > 0 || error.IsDefined() || is.IsEOF());
Max Kellermann's avatar
Max Kellermann committed
332

333 334
	is.Unlock();

335
	if (gcc_unlikely(nbytes == 0 && error.IsDefined()))
336
		LogError(error);
337 338

	return nbytes;
Max Kellermann's avatar
Max Kellermann committed
339 340
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
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;
}

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
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;
}

375
void
376
decoder_timestamp(Decoder &decoder, double t)
377 378 379
{
	assert(t >= 0);

380
	decoder.timestamp = t;
381 382
}

Max Kellermann's avatar
Max Kellermann committed
383
/**
384 385
 * 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
386
 */
387
static DecoderCommand
388
do_send_tag(Decoder &decoder, const Tag &tag)
Max Kellermann's avatar
Max Kellermann committed
389
{
390
	struct music_chunk *chunk;
Max Kellermann's avatar
Max Kellermann committed
391

392
	if (decoder.chunk != nullptr) {
393 394
		/* there is a partial chunk - flush it, we want the
		   tag in a new chunk */
395
		decoder.FlushChunk();
396 397
	}

398
	assert(decoder.chunk == nullptr);
399

400
	chunk = decoder.GetChunk();
401
	if (chunk == nullptr) {
402 403
		assert(decoder.dc.command != DecoderCommand::NONE);
		return decoder.dc.command;
404 405
	}

Max Kellermann's avatar
Max Kellermann committed
406
	chunk->tag = new Tag(tag);
407
	return DecoderCommand::NONE;
408 409
}

410
static bool
411
update_stream_tag(Decoder &decoder, InputStream *is)
412
{
Max Kellermann's avatar
Max Kellermann committed
413
	Tag *tag;
414

415
	tag = is != nullptr
416
		? is->LockReadTag()
417 418
		: nullptr;
	if (tag == nullptr) {
419
		tag = decoder.song_tag;
420
		if (tag == nullptr)
421 422 423 424
			return false;

		/* no stream tag present - submit the song tag
		   instead */
425
		decoder.song_tag = nullptr;
426
	}
427

428 429
	delete decoder.stream_tag;
	decoder.stream_tag = tag;
430 431 432
	return true;
}

433
DecoderCommand
434
decoder_data(Decoder &decoder,
435
	     InputStream *is,
436
	     const void *data, size_t length,
437
	     uint16_t kbit_rate)
Max Kellermann's avatar
Max Kellermann committed
438
{
439
	DecoderControl &dc = decoder.dc;
440
	DecoderCommand cmd;
Max Kellermann's avatar
Max Kellermann committed
441

442 443 444
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
	assert(length % dc.in_audio_format.GetFrameSize() == 0);
445

446
	dc.Lock();
447
	cmd = decoder_get_virtual_command(decoder);
448
	dc.Unlock();
449

450
	if (cmd == DecoderCommand::STOP || cmd == DecoderCommand::SEEK ||
451
	    length == 0)
452
		return cmd;
453

454 455 456
	/* send stream tags */

	if (update_stream_tag(decoder, is)) {
457
		if (decoder.decoder_tag != nullptr) {
458
			/* merge with tag from decoder plugin */
459 460
			Tag *tag = Tag::Merge(*decoder.decoder_tag,
					      *decoder.stream_tag);
Max Kellermann's avatar
Max Kellermann committed
461 462
			cmd = do_send_tag(decoder, *tag);
			delete tag;
463 464
		} else
			/* send only the stream tag */
465
			cmd = do_send_tag(decoder, *decoder.stream_tag);
466

467
		if (cmd != DecoderCommand::NONE)
468
			return cmd;
469 470
	}

471 472 473
	if (decoder.convert != nullptr) {
		assert(dc.in_audio_format != dc.out_audio_format);

474
		Error error;
475
		data = decoder.convert->Convert(data, length,
476 477
						&length,
						error);
478
		if (data == nullptr) {
479 480 481
			/* the PCM conversion has failed - stop
			   playback, since we have no better way to
			   bail out */
482
			LogError(error);
483
			return DecoderCommand::STOP;
484
		}
485 486
	} else {
		assert(dc.in_audio_format == dc.out_audio_format);
Max Kellermann's avatar
Max Kellermann committed
487 488
	}

489
	while (length > 0) {
490 491 492
		struct music_chunk *chunk;
		bool full;

493
		chunk = decoder.GetChunk();
494
		if (chunk == nullptr) {
495 496
			assert(dc.command != DecoderCommand::NONE);
			return dc.command;
497 498
		}

499 500 501
		const auto dest =
			chunk->Write(dc.out_audio_format,
				     decoder.timestamp -
502
				     dc.song->GetStartMS() / 1000.0,
503 504
				     kbit_rate);
		if (dest.IsNull()) {
505
			/* the chunk is full, flush it */
506
			decoder.FlushChunk();
507
			continue;
Max Kellermann's avatar
Max Kellermann committed
508
		}
509

510
		size_t nbytes = dest.size;
511 512 513 514 515 516 517
		assert(nbytes > 0);

		if (nbytes > length)
			nbytes = length;

		/* copy the buffer */

518
		memcpy(dest.data, data, nbytes);
519 520 521

		/* expand the music pipe chunk */

522
		full = chunk->Expand(dc.out_audio_format, nbytes);
523 524
		if (full) {
			/* the chunk is full, flush it */
525
			decoder.FlushChunk();
526
		}
527

528
		data = (const uint8_t *)data + nbytes;
529
		length -= nbytes;
530

531
		decoder.timestamp += (double)nbytes /
532
			dc.out_audio_format.GetTimeToSize();
533

534
		if (dc.end_ms > 0 &&
535
		    decoder.timestamp >= dc.end_ms / 1000.0)
536 537
			/* the end of this range has been reached:
			   stop decoding */
538
			return DecoderCommand::STOP;
Max Kellermann's avatar
Max Kellermann committed
539 540
	}

541
	return DecoderCommand::NONE;
Max Kellermann's avatar
Max Kellermann committed
542
}
543

544
DecoderCommand
545
decoder_tag(Decoder &decoder, InputStream *is,
546
	    Tag &&tag)
547
{
548
	gcc_unused const DecoderControl &dc = decoder.dc;
549
	DecoderCommand cmd;
550

551 552
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
553 554 555

	/* save the tag */

556 557
	delete decoder.decoder_tag;
	decoder.decoder_tag = new Tag(tag);
558 559

	/* check for a new stream tag */
560

561
	update_stream_tag(decoder, is);
562

563 564
	/* check if we're seeking */

565
	if (decoder_prepare_initial_seek(decoder))
566 567 568
		/* during initial seek, no music chunk must be created
		   until seeking is finished; skip the rest of the
		   function here */
569
		return DecoderCommand::SEEK;
570

571
	/* send tag to music pipe */
572

573
	if (decoder.stream_tag != nullptr) {
574
		/* merge with tag from input stream */
Max Kellermann's avatar
Max Kellermann committed
575
		Tag *merged;
576

577 578
		merged = Tag::Merge(*decoder.stream_tag,
				    *decoder.decoder_tag);
Max Kellermann's avatar
Max Kellermann committed
579 580
		cmd = do_send_tag(decoder, *merged);
		delete merged;
581 582
	} else
		/* send only the decoder tag */
583
		cmd = do_send_tag(decoder, *decoder.decoder_tag);
584

585
	return cmd;
586
}
587

588
void
589
decoder_replay_gain(Decoder &decoder,
590
		    const ReplayGainInfo *replay_gain_info)
591
{
592
	if (replay_gain_info != nullptr) {
593 594 595 596
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

597
		if (REPLAY_GAIN_OFF != replay_gain_mode) {
598
			ReplayGainMode rgm = replay_gain_mode;
599 600 601
			if (rgm != REPLAY_GAIN_ALBUM)
				rgm = REPLAY_GAIN_TRACK;

602 603 604 605 606 607
			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);
608 609
		}

610 611
		decoder.replay_gain_info = *replay_gain_info;
		decoder.replay_gain_serial = serial;
612

613
		if (decoder.chunk != nullptr) {
614 615 616
			/* flush the current chunk because the new
			   replay gain values affect the following
			   samples */
617
			decoder.FlushChunk();
618 619
		}
	} else
620
		decoder.replay_gain_serial = 0;
621
}
622 623

void
624
decoder_mixramp(Decoder &decoder, MixRampInfo &&mix_ramp)
625
{
626
	DecoderControl &dc = decoder.dc;
627

628
	dc.SetMixRamp(std::move(mix_ramp));
629
}