Thread.cxx 14.6 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3
 * http://www.musicpd.org
Warren Dukes's avatar
Warren Dukes committed
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.
Warren Dukes's avatar
Warren Dukes committed
18 19
 */

20
#include "config.h"
21
#include "Control.hxx"
22
#include "Bridge.hxx"
23
#include "DecoderPlugin.hxx"
24
#include "song/DetachedSong.hxx"
25
#include "MusicPipe.hxx"
26
#include "fs/Traits.hxx"
27
#include "fs/AllocatedPath.hxx"
28
#include "DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
29
#include "input/InputStream.hxx"
30
#include "input/Registry.hxx"
31
#include "DecoderList.hxx"
32
#include "system/Error.hxx"
33
#include "util/MimeType.hxx"
Max Kellermann's avatar
Max Kellermann committed
34
#include "util/UriExtract.hxx"
Max Kellermann's avatar
Max Kellermann committed
35
#include "util/UriUtil.hxx"
36
#include "util/RuntimeError.hxx"
37
#include "util/Domain.hxx"
38
#include "util/ScopeExit.hxx"
39
#include "util/StringCompare.hxx"
40
#include "thread/Name.hxx"
41
#include "tag/ApeReplayGain.hxx"
42
#include "Log.hxx"
Warren Dukes's avatar
Warren Dukes committed
43

44
#include <stdexcept>
45
#include <functional>
46
#include <memory>
47

48
static constexpr Domain decoder_thread_domain("decoder_thread");
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
/**
 * Decode a URI with the given decoder plugin.
 *
 * Caller holds DecoderControl::mutex.
 */
static bool
DecoderUriDecode(const DecoderPlugin &plugin,
		 DecoderBridge &bridge, const char *uri)
{
	assert(plugin.uri_decode != nullptr);
	assert(bridge.stream_tag == nullptr);
	assert(bridge.decoder_tag == nullptr);
	assert(uri != nullptr);
	assert(bridge.dc.state == DecoderState::START);

65
	FmtDebug(decoder_thread_domain, "probing plugin {}", plugin.name);
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

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

	{
		const ScopeUnlock unlock(bridge.dc.mutex);

		FormatThreadName("decoder:%s", plugin.name);

		plugin.UriDecode(bridge, uri);

		SetThreadName("decoder");
	}

	assert(bridge.dc.state == DecoderState::START ||
	       bridge.dc.state == DecoderState::DECODE);

	return bridge.dc.state != DecoderState::START;
}

86 87 88 89 90
/**
 * Decode a stream with the given decoder plugin.
 *
 * Caller holds DecoderControl::mutex.
 */
91
static bool
92
decoder_stream_decode(const DecoderPlugin &plugin,
93
		      DecoderBridge &bridge,
94 95
		      InputStream &input_stream,
		      std::unique_lock<Mutex> &lock)
96
{
97
	assert(plugin.stream_decode != nullptr);
98 99
	assert(bridge.stream_tag == nullptr);
	assert(bridge.decoder_tag == nullptr);
100
	assert(input_stream.IsReady());
101
	assert(bridge.dc.state == DecoderState::START);
102

103
	FmtDebug(decoder_thread_domain, "probing plugin {}", plugin.name);
104

105
	if (bridge.dc.command == DecoderCommand::STOP)
106
		throw StopDecoder();
107

108
	/* rewind the stream, so each plugin gets a fresh start */
109
	try {
110
		input_stream.Rewind(lock);
111
	} catch (...) {
112
	}
113

114
	{
115
		const ScopeUnlock unlock(bridge.dc.mutex);
116

117
		FormatThreadName("decoder:%s", plugin.name);
118

119
		plugin.StreamDecode(bridge, input_stream);
120

121 122
		SetThreadName("decoder");
	}
123

124 125
	assert(bridge.dc.state == DecoderState::START ||
	       bridge.dc.state == DecoderState::DECODE);
126

127
	return bridge.dc.state != DecoderState::START;
128 129
}

130 131 132 133 134
/**
 * Decode a file with the given decoder plugin.
 *
 * Caller holds DecoderControl::mutex.
 */
135
static bool
136
decoder_file_decode(const DecoderPlugin &plugin,
137
		    DecoderBridge &bridge, Path path)
138
{
139
	assert(plugin.file_decode != nullptr);
140 141
	assert(bridge.stream_tag == nullptr);
	assert(bridge.decoder_tag == nullptr);
142 143
	assert(!path.IsNull());
	assert(path.IsAbsolute());
144
	assert(bridge.dc.state == DecoderState::START);
145

146
	FmtDebug(decoder_thread_domain, "probing plugin {}", plugin.name);
147

148
	if (bridge.dc.command == DecoderCommand::STOP)
149
		throw StopDecoder();
150

151
	{
152
		const ScopeUnlock unlock(bridge.dc.mutex);
153

154
		FormatThreadName("decoder:%s", plugin.name);
155

156
		plugin.FileDecode(bridge, path);
157

158 159
		SetThreadName("decoder");
	}
160

161 162
	assert(bridge.dc.state == DecoderState::START ||
	       bridge.dc.state == DecoderState::DECODE);
163

164
	return bridge.dc.state != DecoderState::START;
165 166
}

167
gcc_pure
168
static bool
169 170
decoder_check_plugin_mime(const DecoderPlugin &plugin,
			  const InputStream &is) noexcept
171
{
172
	assert(plugin.stream_decode != nullptr);
173

174
	const char *mime_type = is.GetMimeType();
175
	return mime_type != nullptr &&
176
		plugin.SupportsMimeType(GetMimeTypeBase(mime_type));
177
}
178

179 180
gcc_pure
static bool
181
decoder_check_plugin_suffix(const DecoderPlugin &plugin,
182
			    std::string_view suffix) noexcept
183 184
{
	assert(plugin.stream_decode != nullptr);
185

186
	return !suffix.empty() && plugin.SupportsSuffix(suffix);
187 188
}

189
gcc_pure
190
static bool
191
decoder_check_plugin(const DecoderPlugin &plugin, const InputStream &is,
192
		     std::string_view suffix) noexcept
193
{
194 195 196 197
	return plugin.stream_decode != nullptr &&
		(decoder_check_plugin_mime(plugin, is) ||
		 decoder_check_plugin_suffix(plugin, suffix));
}
198

199
static bool
200
decoder_run_stream_plugin(DecoderBridge &bridge, InputStream &is,
201
			  std::unique_lock<Mutex> &lock,
202
			  std::string_view suffix,
203 204 205 206
			  const DecoderPlugin &plugin,
			  bool &tried_r)
{
	if (!decoder_check_plugin(plugin, is, suffix))
207 208
		return false;

209
	bridge.Reset();
210

211
	tried_r = true;
212
	return decoder_stream_decode(plugin, bridge, is, lock);
213
}
214

215
static bool
216
decoder_run_stream_locked(DecoderBridge &bridge, InputStream &is,
217
			  std::unique_lock<Mutex> &lock,
218 219
			  const char *uri, bool &tried_r)
{
220
	const auto suffix = uri_get_suffix(uri);
221

222 223 224
	const auto f = [&,suffix](const auto &plugin)
		{ return decoder_run_stream_plugin(bridge, is, lock, suffix, plugin, tried_r); };

225
	return decoder_plugins_try(f);
226 227 228 229 230 231
}

/**
 * Try decoding a stream, using the fallback plugin.
 */
static bool
232 233
decoder_run_stream_fallback(DecoderBridge &bridge, InputStream &is,
			    std::unique_lock<Mutex> &lock)
234
{
235
	const struct DecoderPlugin *plugin;
236

237
#ifdef ENABLE_FFMPEG
238 239
	plugin = decoder_plugin_from_name("ffmpeg");
#else
240
	plugin = decoder_plugin_from_name("mad");
241
#endif
242
	return plugin != nullptr && plugin->stream_decode != nullptr &&
243
		decoder_stream_decode(*plugin, bridge, is, lock);
244 245
}

246 247
/**
 * Attempt to load replay gain data, and pass it to
248
 * DecoderClient::SubmitReplayGain().
249 250
 */
static void
251
LoadReplayGain(DecoderClient &client, InputStream &is)
252 253 254
{
	ReplayGainInfo info;
	if (replay_gain_ape_read(is, info))
255
		client.SubmitReplayGain(&info);
256 257
}

258 259 260 261 262 263 264
/**
 * Call LoadReplayGain() unless ReplayGain is disabled.  This saves
 * the I/O overhead when the user is not interested in the feature.
 */
static void
MaybeLoadReplayGain(DecoderBridge &bridge, InputStream &is)
{
265 266 267
	if (!bridge.dc.LockIsReplayGainEnabled())
		/* ReplayGain is disabled */
		return;
268

269 270 271 272 273 274 275
	if (is.HasMimeType() &&
	    StringStartsWith(is.GetMimeType(), "audio/x-mpd-"))
		/* skip for (virtual) files (e.g. from the
		   cdio_paranoia input plugin) which cannot possibly
		   contain tags */
		return;

276 277 278
	LoadReplayGain(bridge, is);
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
/**
 * Try decoding a URI.
 *
 * DecoderControl::mutex is not be locked by caller.
 */
static bool
TryUriDecode(DecoderBridge &bridge, const char *uri)
{
	return decoder_plugins_try([&bridge, uri](const DecoderPlugin &plugin){
		if (!plugin.SupportsUri(uri))
			return false;

		std::unique_lock<Mutex> lock(bridge.dc.mutex);
		bridge.Reset();
		return DecoderUriDecode(plugin, bridge, uri);
	});
}

297 298
/**
 * Try decoding a stream.
299
 *
300
 * DecoderControl::mutex is not locked by caller.
301 302
 */
static bool
303
decoder_run_stream(DecoderBridge &bridge, const char *uri)
304
{
305 306 307
	if (TryUriDecode(bridge, uri))
		return true;

308
	DecoderControl &dc = bridge.dc;
309

310
	auto input_stream = bridge.OpenUri(uri);
311
	assert(input_stream);
312

313
	MaybeLoadReplayGain(bridge, *input_stream);
314

315
	std::unique_lock<Mutex> lock(dc.mutex);
316

317
	bool tried = false;
318
	return dc.command == DecoderCommand::STOP ||
319
		decoder_run_stream_locked(bridge, *input_stream, lock, uri,
320
					  tried) ||
321 322
		/* fallback to mp3: this is needed for bastard streams
		   that don't have a suffix or set the mimeType */
323
		(!tried &&
324
		 decoder_run_stream_fallback(bridge, *input_stream, lock));
325 326
}

327 328 329
/**
 * Decode a file with the given decoder plugin.
 *
330
 * DecoderControl::mutex is not locked by caller.
331
 */
332
static bool
333
TryDecoderFile(DecoderBridge &bridge, Path path_fs, std::string_view suffix,
334
	       InputStream &input_stream,
335
	       const DecoderPlugin &plugin)
336
{
337 338 339
	if (!plugin.SupportsSuffix(suffix))
		return false;

340
	bridge.Reset();
341

342
	DecoderControl &dc = bridge.dc;
343

344
	if (plugin.file_decode != nullptr) {
345
		const std::scoped_lock<Mutex> protect(dc.mutex);
346
		return decoder_file_decode(plugin, bridge, path_fs);
347
	} else if (plugin.stream_decode != nullptr) {
348 349 350
		std::unique_lock<Mutex> lock(dc.mutex);
		return decoder_stream_decode(plugin, bridge, input_stream,
					     lock);
351 352
	} else
		return false;
353 354
}

355 356 357 358 359 360
/**
 * Decode a container file with the given decoder plugin.
 *
 * DecoderControl::mutex is not locked by caller.
 */
static bool
361 362
TryContainerDecoder(DecoderBridge &bridge, Path path_fs,
		    std::string_view suffix,
363 364 365 366 367 368 369
		    const DecoderPlugin &plugin)
{
	if (plugin.container_scan == nullptr ||
	    plugin.file_decode == nullptr ||
	    !plugin.SupportsSuffix(suffix))
		return false;

370
	bridge.Reset();
371 372

	DecoderControl &dc = bridge.dc;
373
	const std::scoped_lock<Mutex> protect(dc.mutex);
374 375 376 377 378 379 380 381 382
	return decoder_file_decode(plugin, bridge, path_fs);
}

/**
 * Decode a container file.
 *
 * DecoderControl::mutex is not locked by caller.
 */
static bool
383 384
TryContainerDecoder(DecoderBridge &bridge, Path path_fs,
		    std::string_view suffix)
385 386 387 388 389 390 391 392 393 394
{
	return decoder_plugins_try([&bridge, path_fs,
				    suffix](const DecoderPlugin &plugin){
					   return TryContainerDecoder(bridge,
								      path_fs,
								      suffix,
								      plugin);
				   });
}

395 396
/**
 * Try decoding a file.
397
 *
398
 * DecoderControl::mutex is not locked by caller.
399 400
 */
static bool
401
decoder_run_file(DecoderBridge &bridge, const char *uri_utf8, Path path_fs)
402
{
403 404
	const char *_suffix = PathTraitsUTF8::GetFilenameSuffix(uri_utf8);
	if (_suffix == nullptr)
405
		return false;
406

407 408
	const std::string_view suffix{_suffix};

409 410 411
	InputStreamPtr input_stream;

	try {
412
		input_stream = bridge.OpenLocal(path_fs, uri_utf8);
413 414 415 416 417 418 419 420 421 422
	} catch (const std::system_error &e) {
		if (IsPathNotFound(e) &&
		    /* ENOTDIR means this may be a path inside a
		       "container" file */
		    TryContainerDecoder(bridge, path_fs, suffix))
			return true;

		throw;
	}

423
	assert(input_stream);
424

425
	MaybeLoadReplayGain(bridge, *input_stream);
426

427
	auto &is = *input_stream;
428
	return decoder_plugins_try([&bridge, path_fs, suffix,
429
				    &is](const DecoderPlugin &plugin){
430
					   return TryDecoderFile(bridge,
431 432
								 path_fs,
								 suffix,
433
								 is,
434 435
								 plugin);
				   });
436 437
}

438 439 440 441 442 443
/**
 * Decode a song.
 *
 * DecoderControl::mutex is not locked.
 */
static bool
444 445
DecoderUnlockedRunUri(DecoderBridge &bridge,
		      const char *real_uri, Path path_fs)
446
try {
447
	return !path_fs.IsNull()
448 449
		? decoder_run_file(bridge, real_uri, path_fs)
		: decoder_run_stream(bridge, real_uri);
450 451
} catch (StopDecoder) {
	return true;
452
} catch (...) {
453 454 455 456 457
	const char *error_uri = real_uri;
	const std::string allocated = uri_remove_auth(error_uri);
	if (!allocated.empty())
		error_uri = allocated.c_str();

458 459
	std::throw_with_nested(FormatRuntimeError("Failed to decode %s",
						  error_uri));
460 461
}

462 463 464 465 466 467 468 469 470 471
/**
 * Try to guess whether tags attached to the given song are
 * "volatile", e.g. if they have been received by a live stream, but
 * are only kept as a cache to be displayed by the client; they shall
 * not be sent to the output.
 */
gcc_pure
static bool
SongHasVolatileTags(const DetachedSong &song) noexcept
{
472
	return !song.IsFile() && !HasRemoteTagScanner(song.GetRealURI());
473 474
}

475 476 477 478 479
/**
 * Decode a song addressed by a #DetachedSong.
 *
 * Caller holds DecoderControl::mutex.
 */
480
static void
481
decoder_run_song(DecoderControl &dc,
482
		 const DetachedSong &song, const char *uri, Path path_fs)
Avuton Olrich's avatar
Avuton Olrich committed
483
{
484 485 486 487 488
	if (dc.command == DecoderCommand::SEEK)
		/* if the SEEK command arrived too late, start the
		   decoder at the seek position */
		dc.start_time = dc.seek_time;

489
	DecoderBridge bridge(dc, dc.start_time.IsPositive(),
490
			     dc.initial_seek_essential,
491 492 493 494 495
			     /* pass the song tag only if it's
				authoritative, i.e. if it's a local
				file - tags on "stream" songs are just
				remembered from the last time we
				played it*/
496
			     !SongHasVolatileTags(song) ? std::make_unique<Tag>(song.GetTag()) : nullptr);
497

498
	dc.state = DecoderState::START;
499
	dc.CommandFinishedLocked();
500

501
	bool success;
502 503
	{
		const ScopeUnlock unlock(dc.mutex);
Warren Dukes's avatar
Warren Dukes committed
504

505
		AtScopeExit(&bridge) {
506
			/* flush the last chunk */
507
			bridge.CheckFlushChunk();
508
		};
509

510
		success = DecoderUnlockedRunUri(bridge, uri, path_fs);
511

512
	}
513

514 515 516
	bridge.CheckRethrowError();

	if (success)
517
		dc.state = DecoderState::STOP;
518
	else {
519
		const char *error_uri = song.GetURI();
520 521 522
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
523

524
		throw FormatRuntimeError("Failed to decode %s", error_uri);
525
	}
526

527
	dc.client_cond.notify_one();
528 529
}

530 531 532 533
/**
 *
 * Caller holds DecoderControl::mutex.
 */
534
static void
535
decoder_run(DecoderControl &dc) noexcept
536
try {
537
	dc.ClearError();
538

539
	assert(dc.song != nullptr);
540
	const DetachedSong &song = *dc.song;
541

542
	const char *const uri_utf8 = song.GetRealURI();
543

544
	Path path_fs = nullptr;
545
	AllocatedPath path_buffer = nullptr;
546
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
547
		path_buffer = AllocatedPath::FromUTF8Throw(uri_utf8);
548
		path_fs = path_buffer;
549 550
	}

551
	decoder_run_song(dc, song, uri_utf8, path_fs);
552 553
} catch (...) {
	dc.state = DecoderState::ERROR;
554
	dc.command = DecoderCommand::NONE;
555
	dc.error = std::current_exception();
556
	dc.client_cond.notify_one();
557 558
}

559
void
560
DecoderControl::RunThread() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
561
{
562 563
	SetThreadName("decoder");

564
	std::unique_lock<Mutex> lock(mutex);
565

566
	do {
567 568
		assert(state == DecoderState::STOP ||
		       state == DecoderState::ERROR);
569

570
		switch (command) {
571
		case DecoderCommand::START:
572 573 574
			CycleMixRamp();
			replay_gain_prev_db = replay_gain_db;
			replay_gain_db = 0;
575

576
			decoder_run(*this);
577

578
			if (state == DecoderState::ERROR) {
579
				try {
580
					std::rethrow_exception(error);
581
				} catch (...) {
582
					LogError(std::current_exception());
583 584
				}
			}
585

586
			break;
587

588
		case DecoderCommand::SEEK:
589 590 591 592 593 594
			/* this seek was too late, and the decoder had
			   already finished; start a new decoder */

			/* we need to clear the pipe here; usually the
			   PlayerThread is responsible, but it is not
			   aware that the decoder has finished */
595
			pipe->Clear();
596

597
			decoder_run(*this);
598 599
			break;

600
		case DecoderCommand::STOP:
601
			CommandFinishedLocked();
602 603
			break;

604
		case DecoderCommand::NONE:
605
			Wait(lock);
606
			break;
Warren Dukes's avatar
Warren Dukes committed
607
		}
608
	} while (command != DecoderCommand::NONE || !quit);
609
}