Bridge.cxx 12.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13
 * http://www.musicpd.org
 *
 * 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 "Bridge.hxx"
22 23
#include "DecoderAPI.hxx"
#include "DecoderError.hxx"
24
#include "DecoderControl.hxx"
25
#include "DetachedSong.hxx"
26
#include "pcm/PcmConvert.hxx"
27 28 29
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
30
#include "pcm/PcmConvert.hxx"
31
#include "tag/Tag.hxx"
32 33 34
#include "Log.hxx"
#include "input/InputStream.hxx"
#include "util/ConstBuffer.hxx"
35
#include "util/StringBuffer.hxx"
36 37

#include <assert.h>
38 39
#include <string.h>
#include <math.h>
40

41
DecoderBridge::~DecoderBridge()
42 43
{
	/* caller must flush the chunk */
44
	assert(current_chunk == nullptr);
45

46 47 48 49
	if (convert != nullptr) {
		convert->Close();
		delete convert;
	}
50 51
}

52
bool
53
DecoderBridge::CheckCancelRead() const noexcept
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
{
	if (error)
		/* this translates to DecoderCommand::STOP */
		return true;

	if (dc.command == DecoderCommand::NONE)
		return false;

	/* ignore the SEEK command during initialization, the plugin
	   should handle that after it has initialized successfully */
	if (dc.command == DecoderCommand::SEEK &&
	    (dc.state == DecoderState::START || seeking ||
	     initial_seek_running))
		return false;

	return true;
}

72 73 74 75
/**
 * All chunks are full of decoded data; wait for the player to free
 * one.
 */
76
static DecoderCommand
77
need_chunks(DecoderControl &dc) noexcept
78
{
79
	if (dc.command == DecoderCommand::NONE)
80
		dc.Wait();
81

82
	return dc.command;
83 84
}

85
static DecoderCommand
86
LockNeedChunks(DecoderControl &dc) noexcept
87
{
88
	const std::lock_guard<Mutex> protect(dc.mutex);
89 90 91
	return need_chunks(dc);
}

92
MusicChunk *
93
DecoderBridge::GetChunk() noexcept
94
{
95
	DecoderCommand cmd;
96

97 98
	if (current_chunk != nullptr)
		return current_chunk;
99

100
	do {
101 102 103
		current_chunk = dc.buffer->Allocate();
		if (current_chunk != nullptr) {
			current_chunk->replay_gain_serial = replay_gain_serial;
104
			if (replay_gain_serial != 0)
105
				current_chunk->replay_gain_info = replay_gain_info;
106

107
			return current_chunk;
108
		}
109

110
		cmd = LockNeedChunks(dc);
111
	} while (cmd == DecoderCommand::NONE);
112

113
	return nullptr;
114 115
}

116
void
117
DecoderBridge::FlushChunk()
118
{
Max Kellermann's avatar
Max Kellermann committed
119 120 121
	assert(!seeking);
	assert(!initial_seek_running);
	assert(!initial_seek_pending);
122
	assert(current_chunk != nullptr);
123

124
	auto *chunk = std::exchange(current_chunk, nullptr);
125 126
	if (chunk->IsEmpty())
		dc.buffer->Return(chunk);
127
	else
128
		dc.pipe->Push(chunk);
129

130
	const std::lock_guard<Mutex> protect(dc.mutex);
131 132
	if (dc.client_is_waiting)
		dc.client_cond.signal();
133
}
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

bool
DecoderBridge::PrepareInitialSeek()
{
	assert(dc.pipe != nullptr);

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

	if (initial_seek_running)
		/* initial seek has already begun - override any other
		   command */
		return true;

	if (initial_seek_pending) {
		if (!dc.seekable) {
			/* seeking is not possible */
			initial_seek_pending = false;
			return false;
		}

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

			initial_seek_pending = false;
			initial_seek_running = true;
			return true;
		}

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

		initial_seek_pending = false;
	}

	return false;
}

DecoderCommand
176
DecoderBridge::GetVirtualCommand() noexcept
177 178 179 180 181 182 183 184 185 186 187 188 189 190
{
	if (error)
		/* an error has occurred: stop the decoder plugin */
		return DecoderCommand::STOP;

	assert(dc.pipe != nullptr);

	if (PrepareInitialSeek())
		return DecoderCommand::SEEK;

	return dc.command;
}

DecoderCommand
191
DecoderBridge::LockGetVirtualCommand() noexcept
192
{
193
	const std::lock_guard<Mutex> protect(dc.mutex);
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	return GetVirtualCommand();
}

DecoderCommand
DecoderBridge::DoSendTag(const Tag &tag)
{
	if (current_chunk != nullptr) {
		/* there is a partial chunk - flush it, we want the
		   tag in a new chunk */
		FlushChunk();
	}

	assert(current_chunk == nullptr);

	auto *chunk = GetChunk();
	if (chunk == nullptr) {
		assert(dc.command != DecoderCommand::NONE);
		return dc.command;
	}

214
	chunk->tag = std::make_unique<Tag>(tag);
215 216 217 218 219 220
	return DecoderCommand::NONE;
}

bool
DecoderBridge::UpdateStreamTag(InputStream *is)
{
221 222
	auto tag = is != nullptr
		? is->LockReadTag()
223 224
		: nullptr;
	if (tag == nullptr) {
225
		tag = std::move(song_tag);
226 227 228 229 230 231 232
		if (tag == nullptr)
			return false;

		/* no stream tag present - submit the song tag
		   instead */
	} else
		/* discard the song tag; we don't need it */
233
		song_tag.reset();
234

235
	stream_tag = std::move(tag);
236 237 238 239 240 241 242 243 244 245 246 247 248
	return true;
}

void
DecoderBridge::Ready(const AudioFormat audio_format,
		     bool seekable, SignedSongTime duration)
{
	assert(convert == nullptr);
	assert(stream_tag == nullptr);
	assert(decoder_tag == nullptr);
	assert(!seeking);

	FormatDebug(decoder_domain, "audio_format=%s, seekable=%s",
249
		    ToString(audio_format).c_str(),
250 251
		    seekable ? "true" : "false");

252
	{
253
		const std::lock_guard<Mutex> protect(dc.mutex);
254 255 256
		dc.SetReady(audio_format, seekable, duration);
	}

257 258
	if (dc.in_audio_format != dc.out_audio_format) {
		FormatDebug(decoder_domain, "converting to %s",
259
			    ToString(dc.out_audio_format).c_str());
260 261 262 263 264 265 266 267 268 269 270 271 272

		convert = new PcmConvert();

		try {
			convert->Open(dc.in_audio_format,
					      dc.out_audio_format);
		} catch (...) {
			error = std::current_exception();
		}
	}
}

DecoderCommand
273
DecoderBridge::GetCommand() noexcept
274 275 276 277 278 279 280
{
	return LockGetVirtualCommand();
}

void
DecoderBridge::CommandFinished()
{
281
	const std::lock_guard<Mutex> protect(dc.mutex);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

	assert(dc.command != DecoderCommand::NONE || initial_seek_running);
	assert(dc.command != DecoderCommand::SEEK ||
	       initial_seek_running ||
	       dc.seek_error || seeking);
	assert(dc.pipe != nullptr);

	if (initial_seek_running) {
		assert(!seeking);
		assert(current_chunk == nullptr);
		assert(dc.pipe->IsEmpty());

		initial_seek_running = false;
		timestamp = dc.start_time.ToDoubleS();
		return;
	}

	if (seeking) {
		seeking = false;

		/* delete frames from the old song position */

		if (current_chunk != nullptr) {
			dc.buffer->Return(current_chunk);
			current_chunk = nullptr;
		}

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

311 312 313
		if (convert != nullptr)
			convert->Reset();

314 315 316 317 318 319 320 321
		timestamp = dc.seek_time.ToDoubleS();
	}

	dc.command = DecoderCommand::NONE;
	dc.client_cond.signal();
}

SongTime
322
DecoderBridge::GetSeekTime() noexcept
323 324 325 326 327 328 329 330 331 332 333 334 335 336
{
	assert(dc.pipe != nullptr);

	if (initial_seek_running)
		return dc.start_time;

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

	seeking = true;

	return dc.seek_time;
}

uint64_t
337
DecoderBridge::GetSeekFrame() noexcept
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
{
	return GetSeekTime().ToScale<uint64_t>(dc.in_audio_format.sample_rate);
}

void
DecoderBridge::SeekError()
{
	assert(dc.pipe != nullptr);

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

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

	dc.seek_error = true;
	seeking = false;

	CommandFinished();
}

InputStreamPtr
DecoderBridge::OpenUri(const char *uri)
{
	assert(dc.state == DecoderState::START ||
	       dc.state == DecoderState::DECODE);

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

	auto is = InputStream::Open(uri, mutex, cond);

373
	const std::lock_guard<Mutex> lock(mutex);
374 375 376 377 378 379 380 381 382 383 384 385
	while (true) {
		is->Update();
		if (is->IsReady())
			return is;

		if (dc.command == DecoderCommand::STOP)
			throw StopDecoder();

		cond.wait(mutex);
	}
}

386 387 388 389 390 391 392 393 394 395
size_t
DecoderBridge::Read(InputStream &is, void *buffer, size_t length)
try {
	assert(buffer != nullptr);
	assert(dc.state == DecoderState::START ||
	       dc.state == DecoderState::DECODE);

	if (length == 0)
		return 0;

396
	std::lock_guard<Mutex> lock(is.mutex);
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

	while (true) {
		if (CheckCancelRead())
			return 0;

		if (is.IsAvailable())
			break;

		is.cond.wait(is.mutex);
	}

	size_t nbytes = is.Read(buffer, length);
	assert(nbytes > 0 || is.IsEOF());

	return nbytes;
412
} catch (...) {
413 414 415 416
	error = std::current_exception();
	return 0;
}

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
void
DecoderBridge::SubmitTimestamp(double t)
{
	assert(t >= 0);

	timestamp = t;
}

DecoderCommand
DecoderBridge::SubmitData(InputStream *is,
			  const void *data, size_t length,
			  uint16_t kbit_rate)
{
	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);
	assert(length % dc.in_audio_format.GetFrameSize() == 0);

	DecoderCommand cmd = LockGetVirtualCommand();

	if (cmd == DecoderCommand::STOP || cmd == DecoderCommand::SEEK ||
	    length == 0)
		return cmd;

	assert(!initial_seek_pending);
	assert(!initial_seek_running);

	/* send stream tags */

	if (UpdateStreamTag(is)) {
446
		if (decoder_tag != nullptr)
447
			/* merge with tag from decoder plugin */
448 449 450
			cmd = DoSendTag(*Tag::Merge(*decoder_tag,
						    *stream_tag));
		else
451 452 453 454 455 456 457 458 459 460 461 462 463 464
			/* send only the stream tag */
			cmd = DoSendTag(*stream_tag);

		if (cmd != DecoderCommand::NONE)
			return cmd;
	}

	if (convert != nullptr) {
		assert(dc.in_audio_format != dc.out_audio_format);

		try {
			auto result = convert->Convert({data, length});
			data = result.data;
			length = result.size;
465
		} catch (...) {
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
			/* the PCM conversion has failed - stop
			   playback, since we have no better way to
			   bail out */
			error = std::current_exception();
			return DecoderCommand::STOP;
		}
	} else {
		assert(dc.in_audio_format == dc.out_audio_format);
	}

	while (length > 0) {
		bool full;

		auto *chunk = GetChunk();
		if (chunk == nullptr) {
			assert(dc.command != DecoderCommand::NONE);
			return dc.command;
		}

		const auto dest =
			chunk->Write(dc.out_audio_format,
				     SongTime::FromS(timestamp) -
				     dc.song->GetStartTime(),
				     kbit_rate);
490
		if (dest.empty()) {
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
			/* the chunk is full, flush it */
			FlushChunk();
			continue;
		}

		const size_t nbytes = std::min(dest.size, length);

		/* copy the buffer */

		memcpy(dest.data, data, nbytes);

		/* expand the music pipe chunk */

		full = chunk->Expand(dc.out_audio_format, nbytes);
		if (full) {
			/* the chunk is full, flush it */
			FlushChunk();
		}

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

		timestamp += (double)nbytes /
			dc.out_audio_format.GetTimeToSize();

		if (dc.end_time.IsPositive() &&
		    timestamp >= dc.end_time.ToDoubleS())
			/* the end of this range has been reached:
			   stop decoding */
			return DecoderCommand::STOP;
	}

	return DecoderCommand::NONE;
}

DecoderCommand
DecoderBridge::SubmitTag(InputStream *is, Tag &&tag)
{
	DecoderCommand cmd;

	assert(dc.state == DecoderState::DECODE);
	assert(dc.pipe != nullptr);

	/* save the tag */

536
	decoder_tag = std::make_unique<Tag>(std::move(tag));
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

	/* check for a new stream tag */

	UpdateStreamTag(is);

	/* check if we're seeking */

	if (PrepareInitialSeek())
		/* during initial seek, no music chunk must be created
		   until seeking is finished; skip the rest of the
		   function here */
		return DecoderCommand::SEEK;

	/* send tag to music pipe */

552
	if (stream_tag != nullptr)
553
		/* merge with tag from input stream */
554 555
		cmd = DoSendTag(*Tag::Merge(*stream_tag, *decoder_tag));
	else
556 557 558 559 560 561 562 563 564 565 566 567 568 569
		/* send only the decoder tag */
		cmd = DoSendTag(*decoder_tag);

	return cmd;
}

void
DecoderBridge::SubmitReplayGain(const ReplayGainInfo *new_replay_gain_info)
{
	if (new_replay_gain_info != nullptr) {
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

570 571
		if (ReplayGainMode::OFF != dc.replay_gain_mode) {
			ReplayGainMode rgm = dc.replay_gain_mode;
572 573
			if (rgm != ReplayGainMode::ALBUM)
				rgm = ReplayGainMode::TRACK;
574

575
			const auto &tuple = new_replay_gain_info->Get(rgm);
576
			const auto scale =
577
				tuple.CalculateScale(dc.replay_gain_config);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
			dc.replay_gain_db = 20.0 * log10f(scale);
		}

		replay_gain_info = *new_replay_gain_info;
		replay_gain_serial = serial;

		if (current_chunk != nullptr) {
			/* flush the current chunk because the new
			   replay gain values affect the following
			   samples */
			FlushChunk();
		}
	} else
		replay_gain_serial = 0;
}

void
DecoderBridge::SubmitMixRamp(MixRampInfo &&mix_ramp)
{
	dc.SetMixRamp(std::move(mix_ramp));
}