Bridge.cxx 14.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "Bridge.hxx"
21
#include "DecoderAPI.hxx"
22 23
#include "Domain.hxx"
#include "Control.hxx"
24
#include "lib/fmt/AudioFormatFormatter.hxx"
25
#include "song/DetachedSong.hxx"
26
#include "pcm/Convert.hxx"
27 28 29
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
30
#include "tag/Tag.hxx"
31 32
#include "Log.hxx"
#include "input/InputStream.hxx"
33
#include "input/LocalOpen.hxx"
34 35
#include "input/cache/Manager.hxx"
#include "input/cache/Stream.hxx"
36
#include "fs/Path.hxx"
37
#include "util/ConstBuffer.hxx"
38
#include "util/StringBuffer.hxx"
39

40
#include <cassert>
41
#include <cmath>
42
#include <stdexcept>
43

44
#include <string.h>
45

46
DecoderBridge::DecoderBridge(DecoderControl &_dc, bool _initial_seek_pending,
Max Kellermann's avatar
Max Kellermann committed
47
			     bool _initial_seek_essential,
48 49 50
			     std::unique_ptr<Tag> _tag) noexcept
	:dc(_dc),
	 initial_seek_pending(_initial_seek_pending),
Max Kellermann's avatar
Max Kellermann committed
51
	 initial_seek_essential(_initial_seek_essential),
52 53
	 song_tag(std::move(_tag)) {}

Max Kellermann's avatar
Max Kellermann committed
54

55
DecoderBridge::~DecoderBridge() noexcept
56 57
{
	/* caller must flush the chunk */
58
	assert(current_chunk == nullptr);
59 60
}

61
InputStreamPtr
62
DecoderBridge::OpenLocal(Path path_fs, const char *uri_utf8)
63
{
64 65 66 67 68 69 70 71 72 73
	if (dc.input_cache != nullptr) {
		auto lease = dc.input_cache->Get(uri_utf8, true);
		if (lease) {
			auto is = std::make_unique<CacheInputStream>(std::move(lease),
								     dc.mutex);
			is->SetHandler(&dc);
			return is;
		}
	}

74 75 76
	auto is = OpenLocalInputStream(path_fs, dc.mutex);
	is->SetHandler(&dc);
	return is;
77 78
}

79
bool
80
DecoderBridge::CheckCancelRead() const noexcept
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
{
	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;
}

99 100 101 102
/**
 * All chunks are full of decoded data; wait for the player to free
 * one.
 */
103
static DecoderCommand
104
NeedChunks(DecoderControl &dc, std::unique_lock<Mutex> &lock) noexcept
105
{
106
	if (dc.command == DecoderCommand::NONE)
107
		dc.Wait(lock);
108

109
	return dc.command;
110 111
}

112
static DecoderCommand
113
LockNeedChunks(DecoderControl &dc) noexcept
114
{
115 116
	std::unique_lock<Mutex> lock(dc.mutex);
	return NeedChunks(dc, lock);
117 118
}

119
MusicChunk *
120
DecoderBridge::GetChunk() noexcept
121
{
122
	DecoderCommand cmd;
123

124
	if (current_chunk != nullptr)
125
		return current_chunk.get();
126

127
	do {
128
		current_chunk = dc.buffer->Allocate();
129 130
		if (current_chunk != nullptr) {
			current_chunk->replay_gain_serial = replay_gain_serial;
131
			if (replay_gain_serial != 0)
132
				current_chunk->replay_gain_info = replay_gain_info;
133

134
			return current_chunk.get();
135
		}
136

137
		cmd = LockNeedChunks(dc);
138
	} while (cmd == DecoderCommand::NONE);
139

140
	return nullptr;
141 142
}

143
void
144
DecoderBridge::FlushChunk() noexcept
145
{
Max Kellermann's avatar
Max Kellermann committed
146 147 148
	assert(!seeking);
	assert(!initial_seek_running);
	assert(!initial_seek_pending);
149
	assert(current_chunk != nullptr);
150

151 152 153
	auto chunk = std::move(current_chunk);
	if (!chunk->IsEmpty())
		dc.pipe->Push(std::move(chunk));
154

155
	const std::scoped_lock<Mutex> protect(dc.mutex);
156
	dc.client_cond.notify_one();
157
}
158 159

bool
160
DecoderBridge::PrepareInitialSeek() noexcept
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
{
	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
200
DecoderBridge::GetVirtualCommand() noexcept
201 202 203 204 205 206 207 208 209 210 211 212 213 214
{
	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
215
DecoderBridge::LockGetVirtualCommand() noexcept
216
{
217
	const std::scoped_lock<Mutex> protect(dc.mutex);
218 219 220 221
	return GetVirtualCommand();
}

DecoderCommand
222
DecoderBridge::DoSendTag(const Tag &tag) noexcept
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
{
	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;
	}

238
	chunk->tag = std::make_unique<Tag>(tag);
239 240 241 242
	return DecoderCommand::NONE;
}

bool
243
DecoderBridge::UpdateStreamTag(InputStream *is) noexcept
244
{
245 246
	auto tag = is != nullptr
		? is->LockReadTag()
247 248
		: nullptr;
	if (tag == nullptr) {
249
		tag = std::move(song_tag);
250 251 252 253 254 255 256
		if (tag == nullptr)
			return false;

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

259
	stream_tag = std::move(tag);
260 261 262 263 264
	return true;
}

void
DecoderBridge::Ready(const AudioFormat audio_format,
265
		     bool seekable, SignedSongTime duration) noexcept
266 267 268 269 270 271
{
	assert(convert == nullptr);
	assert(stream_tag == nullptr);
	assert(decoder_tag == nullptr);
	assert(!seeking);

272 273 274
	FmtDebug(decoder_domain, "audio_format={}, seekable={}",
		 audio_format,
		 seekable);
275

276
	{
277
		const std::scoped_lock<Mutex> protect(dc.mutex);
278 279 280
		dc.SetReady(audio_format, seekable, duration);
	}

281
	if (dc.in_audio_format != dc.out_audio_format) {
282
		FmtDebug(decoder_domain, "converting to {}",
283
			 dc.out_audio_format);
284 285

		try {
286 287
			convert = std::make_unique<PcmConvert>(dc.in_audio_format,
							       dc.out_audio_format);
288 289 290 291 292 293 294
		} catch (...) {
			error = std::current_exception();
		}
	}
}

DecoderCommand
295
DecoderBridge::GetCommand() noexcept
296 297 298 299 300
{
	return LockGetVirtualCommand();
}

void
301
DecoderBridge::CommandFinished() noexcept
302
{
303
	const std::scoped_lock<Mutex> protect(dc.mutex);
304 305 306 307 308 309 310 311 312 313 314 315 316

	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;
317
		timestamp = std::chrono::duration_cast<FloatDuration>(dc.start_time);
318
		absolute_frame = dc.start_time.ToScale<uint64_t>(dc.in_audio_format.sample_rate);
319 320 321 322 323 324 325 326
		return;
	}

	if (seeking) {
		seeking = false;

		/* delete frames from the old song position */

327
		current_chunk.reset();
328

329
		dc.pipe->Clear();
330

331 332 333
		if (convert != nullptr)
			convert->Reset();

334
		timestamp = std::chrono::duration_cast<FloatDuration>(dc.seek_time);
335
		absolute_frame = dc.seek_time.ToScale<uint64_t>(dc.in_audio_format.sample_rate);
336 337 338
	}

	dc.command = DecoderCommand::NONE;
339
	dc.client_cond.notify_one();
340 341 342
}

SongTime
343
DecoderBridge::GetSeekTime() noexcept
344 345 346 347 348 349 350 351 352 353 354 355 356 357
{
	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
358
DecoderBridge::GetSeekFrame() noexcept
359 360 361 362 363
{
	return GetSeekTime().ToScale<uint64_t>(dc.in_audio_format.sample_rate);
}

void
364
DecoderBridge::SeekError() noexcept
365 366 367 368 369 370 371
{
	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;
372 373 374 375

		if (initial_seek_essential)
			error = std::make_exception_ptr(std::runtime_error("Decoder failed to seek"));

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
		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;

396 397
	auto is = InputStream::Open(uri, mutex);
	is->SetHandler(&dc);
398

399
	std::unique_lock<Mutex> lock(mutex);
400
	while (true) {
401 402 403
		if (dc.command == DecoderCommand::STOP)
			throw StopDecoder();

404
		is->Update();
405 406
		if (is->IsReady()) {
			is->Check();
407
			return is;
408
		}
409

410
		cond.wait(lock);
411 412 413
	}
}

414
size_t
415
DecoderBridge::Read(InputStream &is, void *buffer, size_t length) noexcept
416 417 418 419 420 421 422 423
try {
	assert(buffer != nullptr);
	assert(dc.state == DecoderState::START ||
	       dc.state == DecoderState::DECODE);

	if (length == 0)
		return 0;

424
	std::unique_lock<Mutex> lock(is.mutex);
425 426 427 428 429 430 431 432

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

		if (is.IsAvailable())
			break;

433
		dc.cond.wait(lock);
434 435
	}

436
	size_t nbytes = is.Read(lock, buffer, length);
437 438 439
	assert(nbytes > 0 || is.IsEOF());

	return nbytes;
440
} catch (...) {
441 442 443 444
	error = std::current_exception();
	return 0;
}

445
void
446
DecoderBridge::SubmitTimestamp(FloatDuration t) noexcept
447
{
448
	assert(t.count() >= 0);
449 450

	timestamp = t;
451
	absolute_frame = uint64_t(t.count() * dc.in_audio_format.sample_rate);
452 453 454 455 456
}

DecoderCommand
DecoderBridge::SubmitData(InputStream *is,
			  const void *data, size_t length,
457
			  uint16_t kbit_rate) noexcept
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
{
	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)) {
475
		if (decoder_tag != nullptr)
476
			/* merge with tag from decoder plugin */
477 478
			cmd = DoSendTag(Tag::Merge(*decoder_tag,
						   *stream_tag));
479
		else
480 481 482 483 484 485 486
			/* send only the stream tag */
			cmd = DoSendTag(*stream_tag);

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

487 488 489 490 491 492 493 494
	cmd = DecoderCommand::NONE;

	const size_t frame_size = dc.in_audio_format.GetFrameSize();
	size_t data_frames = length / frame_size;

	if (dc.end_time.IsPositive()) {
		/* enforce the given end time */

Max Kellermann's avatar
Max Kellermann committed
495
		const auto end_frame =
496 497 498 499 500 501 502 503 504 505 506 507 508 509
			dc.end_time.ToScale<uint64_t>(dc.in_audio_format.sample_rate);
		if (absolute_frame >= end_frame)
			return DecoderCommand::STOP;

		const uint64_t remaining_frames = end_frame - absolute_frame;
		if (data_frames >= remaining_frames) {
			/* past the end of the range: truncate this
			   data submission and stop the decoder */
			data_frames = remaining_frames;
			length = data_frames * frame_size;
			cmd = DecoderCommand::STOP;
		}
	}

510 511 512 513 514 515 516
	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;
517
		} catch (...) {
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
			/* 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,
539
				     SongTime::Cast(timestamp) -
540 541
				     dc.song->GetStartTime(),
				     kbit_rate);
542
		if (dest.empty()) {
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
			/* 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;

565
		timestamp += dc.out_audio_format.SizeToTime<FloatDuration>(nbytes);
566 567
	}

568 569 570
	absolute_frame += data_frames;

	return cmd;
571 572 573
}

DecoderCommand
574
DecoderBridge::SubmitTag(InputStream *is, Tag &&tag) noexcept
575 576 577 578 579 580 581 582
{
	DecoderCommand cmd;

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

	/* save the tag */

583
	decoder_tag = std::make_unique<Tag>(std::move(tag));
584 585 586 587 588 589 590 591 592

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

593 594 595 596
	/* check for a new stream tag */

	UpdateStreamTag(is);

597 598
	/* send tag to music pipe */

599
	if (stream_tag != nullptr)
600
		/* merge with tag from input stream */
601
		cmd = DoSendTag(Tag::Merge(*stream_tag, *decoder_tag));
602
	else
603 604 605 606 607 608 609
		/* send only the decoder tag */
		cmd = DoSendTag(*decoder_tag);

	return cmd;
}

void
610
DecoderBridge::SubmitReplayGain(const ReplayGainInfo *new_replay_gain_info) noexcept
611 612 613 614 615 616
{
	if (new_replay_gain_info != nullptr) {
		static unsigned serial;
		if (++serial == 0)
			serial = 1;

617 618
		if (ReplayGainMode::OFF != dc.replay_gain_mode) {
			ReplayGainMode rgm = dc.replay_gain_mode;
619 620
			if (rgm != ReplayGainMode::ALBUM)
				rgm = ReplayGainMode::TRACK;
621

622
			const auto &tuple = new_replay_gain_info->Get(rgm);
623
			const auto scale =
624
				tuple.CalculateScale(dc.replay_gain_config);
Rosen Penev's avatar
Rosen Penev committed
625
			dc.replay_gain_db = 20.0f * std::log10(scale);
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
		}

		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
642
DecoderBridge::SubmitMixRamp(MixRampInfo &&mix_ramp) noexcept
643 644 645
{
	dc.SetMixRamp(std::move(mix_ramp));
}