DecoderAPI.cxx 12.6 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 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 "Song.hxx"
32
#include "InputStream.hxx"
33
#include "util/Error.hxx"
34
#include "Log.hxx"
35

36 37
#include <assert.h>
#include <stdlib.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, float total_time)
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(decoder.convert == nullptr);
52 53 54
	assert(decoder.stream_tag == nullptr);
	assert(decoder.decoder_tag == nullptr);
	assert(!decoder.seeking);
55 56
	assert(audio_format.IsDefined());
	assert(audio_format.IsValid());
57

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

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

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

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

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

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

	dc.Lock();
	dc.state = DecoderState::DECODE;
	dc.client_cond.signal();
	dc.Unlock();
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
DecoderCommand
157
decoder_get_command(Decoder &decoder)
158 159 160 161
{
	return decoder_get_virtual_command(decoder);
}

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

167
	dc.Lock();
168

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

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

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

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

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

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

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

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

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

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

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

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

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

218
	decoder.seeking = true;
219

220
	return dc.seek_where;
221 222
}

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

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

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

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

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

241 242 243
	decoder_command_finished(decoder);
}

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

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

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

	return true;
}

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

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

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

283
	is.Lock();
284 285 286

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

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

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

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

302 303
	is.Unlock();

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

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

310
void
311
decoder_timestamp(Decoder &decoder, double t)
312 313 314
{
	assert(t >= 0);

315
	decoder.timestamp = t;
316 317
}

Max Kellermann's avatar
Max Kellermann committed
318
/**
319 320
 * 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
321
 */
322
static DecoderCommand
323
do_send_tag(Decoder &decoder, const Tag &tag)
Max Kellermann's avatar
Max Kellermann committed
324
{
325
	struct music_chunk *chunk;
Max Kellermann's avatar
Max Kellermann committed
326

327
	if (decoder.chunk != nullptr) {
328 329
		/* there is a partial chunk - flush it, we want the
		   tag in a new chunk */
330
		decoder.FlushChunk();
331 332
	}

333
	assert(decoder.chunk == nullptr);
334

335
	chunk = decoder.GetChunk();
336
	if (chunk == nullptr) {
337 338
		assert(decoder.dc.command != DecoderCommand::NONE);
		return decoder.dc.command;
339 340
	}

Max Kellermann's avatar
Max Kellermann committed
341
	chunk->tag = new Tag(tag);
342
	return DecoderCommand::NONE;
343 344
}

345
static bool
346
update_stream_tag(Decoder &decoder, InputStream *is)
347
{
Max Kellermann's avatar
Max Kellermann committed
348
	Tag *tag;
349

350
	tag = is != nullptr
351
		? is->LockReadTag()
352 353
		: nullptr;
	if (tag == nullptr) {
354
		tag = decoder.song_tag;
355
		if (tag == nullptr)
356 357 358 359
			return false;

		/* no stream tag present - submit the song tag
		   instead */
360
		decoder.song_tag = nullptr;
361
	}
362

363 364
	delete decoder.stream_tag;
	decoder.stream_tag = tag;
365 366 367
	return true;
}

368
DecoderCommand
369
decoder_data(Decoder &decoder,
370
	     InputStream *is,
371
	     const void *data, size_t length,
372
	     uint16_t kbit_rate)
Max Kellermann's avatar
Max Kellermann committed
373
{
374
	DecoderControl &dc = decoder.dc;
375
	DecoderCommand cmd;
Max Kellermann's avatar
Max Kellermann committed
376

377 378 379
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
	assert(length % dc.in_audio_format.GetFrameSize() == 0);
380

381
	dc.Lock();
382
	cmd = decoder_get_virtual_command(decoder);
383
	dc.Unlock();
384

385
	if (cmd == DecoderCommand::STOP || cmd == DecoderCommand::SEEK ||
386
	    length == 0)
387
		return cmd;
388

389 390 391
	/* send stream tags */

	if (update_stream_tag(decoder, is)) {
392
		if (decoder.decoder_tag != nullptr) {
393
			/* merge with tag from decoder plugin */
394 395
			Tag *tag = Tag::Merge(*decoder.decoder_tag,
					      *decoder.stream_tag);
Max Kellermann's avatar
Max Kellermann committed
396 397
			cmd = do_send_tag(decoder, *tag);
			delete tag;
398 399
		} else
			/* send only the stream tag */
400
			cmd = do_send_tag(decoder, *decoder.stream_tag);
401

402
		if (cmd != DecoderCommand::NONE)
403
			return cmd;
404 405
	}

406 407 408
	if (decoder.convert != nullptr) {
		assert(dc.in_audio_format != dc.out_audio_format);

409
		Error error;
410
		data = decoder.convert->Convert(data, length,
411 412
						&length,
						error);
413
		if (data == nullptr) {
414 415 416
			/* the PCM conversion has failed - stop
			   playback, since we have no better way to
			   bail out */
417
			LogError(error);
418
			return DecoderCommand::STOP;
419
		}
420 421
	} else {
		assert(dc.in_audio_format == dc.out_audio_format);
Max Kellermann's avatar
Max Kellermann committed
422 423
	}

424
	while (length > 0) {
425 426 427
		struct music_chunk *chunk;
		bool full;

428
		chunk = decoder.GetChunk();
429
		if (chunk == nullptr) {
430 431
			assert(dc.command != DecoderCommand::NONE);
			return dc.command;
432 433
		}

434 435 436 437 438 439
		const auto dest =
			chunk->Write(dc.out_audio_format,
				     decoder.timestamp -
				     dc.song->start_ms / 1000.0,
				     kbit_rate);
		if (dest.IsNull()) {
440
			/* the chunk is full, flush it */
441
			decoder.FlushChunk();
442
			continue;
Max Kellermann's avatar
Max Kellermann committed
443
		}
444

445
		size_t nbytes = dest.size;
446 447 448 449 450 451 452
		assert(nbytes > 0);

		if (nbytes > length)
			nbytes = length;

		/* copy the buffer */

453
		memcpy(dest.data, data, nbytes);
454 455 456

		/* expand the music pipe chunk */

457
		full = chunk->Expand(dc.out_audio_format, nbytes);
458 459
		if (full) {
			/* the chunk is full, flush it */
460
			decoder.FlushChunk();
461
		}
462

463
		data = (const uint8_t *)data + nbytes;
464
		length -= nbytes;
465

466
		decoder.timestamp += (double)nbytes /
467
			dc.out_audio_format.GetTimeToSize();
468

469
		if (dc.end_ms > 0 &&
470
		    decoder.timestamp >= dc.end_ms / 1000.0)
471 472
			/* the end of this range has been reached:
			   stop decoding */
473
			return DecoderCommand::STOP;
Max Kellermann's avatar
Max Kellermann committed
474 475
	}

476
	return DecoderCommand::NONE;
Max Kellermann's avatar
Max Kellermann committed
477
}
478

479
DecoderCommand
480
decoder_tag(Decoder &decoder, InputStream *is,
481
	    Tag &&tag)
482
{
483
	gcc_unused const DecoderControl &dc = decoder.dc;
484
	DecoderCommand cmd;
485

486 487
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
488 489 490

	/* save the tag */

491 492
	delete decoder.decoder_tag;
	decoder.decoder_tag = new Tag(tag);
493 494

	/* check for a new stream tag */
495

496
	update_stream_tag(decoder, is);
497

498 499
	/* check if we're seeking */

500
	if (decoder_prepare_initial_seek(decoder))
501 502 503
		/* during initial seek, no music chunk must be created
		   until seeking is finished; skip the rest of the
		   function here */
504
		return DecoderCommand::SEEK;
505

506
	/* send tag to music pipe */
507

508
	if (decoder.stream_tag != nullptr) {
509
		/* merge with tag from input stream */
Max Kellermann's avatar
Max Kellermann committed
510
		Tag *merged;
511

512 513
		merged = Tag::Merge(*decoder.stream_tag,
				    *decoder.decoder_tag);
Max Kellermann's avatar
Max Kellermann committed
514 515
		cmd = do_send_tag(decoder, *merged);
		delete merged;
516 517
	} else
		/* send only the decoder tag */
518
		cmd = do_send_tag(decoder, *decoder.decoder_tag);
519

520
	return cmd;
521
}
522

523
void
524
decoder_replay_gain(Decoder &decoder,
525
		    const ReplayGainInfo *replay_gain_info)
526
{
527
	if (replay_gain_info != nullptr) {
528 529 530 531
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

532
		if (REPLAY_GAIN_OFF != replay_gain_mode) {
533
			ReplayGainMode rgm = replay_gain_mode;
534 535 536
			if (rgm != REPLAY_GAIN_ALBUM)
				rgm = REPLAY_GAIN_TRACK;

537 538 539 540 541 542
			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);
543 544
		}

545 546
		decoder.replay_gain_info = *replay_gain_info;
		decoder.replay_gain_serial = serial;
547

548
		if (decoder.chunk != nullptr) {
549 550 551
			/* flush the current chunk because the new
			   replay gain values affect the following
			   samples */
552
			decoder.FlushChunk();
553 554
		}
	} else
555
		decoder.replay_gain_serial = 0;
556
}
557 558

void
559
decoder_mixramp(Decoder &decoder, MixRampInfo &&mix_ramp)
560
{
561
	DecoderControl &dc = decoder.dc;
562

563
	dc.SetMixRamp(std::move(mix_ramp));
564
}