Thread.cxx 13.8 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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/LocalOpen.hxx"
31
#include "input/Registry.hxx"
32
#include "DecoderList.hxx"
33
#include "system/Error.hxx"
34
#include "util/MimeType.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
 * Opens the input stream with InputStream::Open(), and waits until
52
 * the stream gets ready.
53 54 55
 *
 * Unlock the decoder before calling this function.
 */
56
static InputStreamPtr
57
decoder_input_stream_open(DecoderControl &dc, const char *uri)
58
{
59 60
	auto is = InputStream::Open(uri, dc.mutex);
	is->SetHandler(&dc);
61 62 63 64

	/* wait for the input stream to become ready; its metadata
	   will be available then */

65
	const std::lock_guard<Mutex> protect(dc.mutex);
66

67
	is->Update();
68 69
	while (!is->IsReady()) {
		if (dc.command == DecoderCommand::STOP)
70
			throw StopDecoder();
71

72
		dc.Wait();
73

74
		is->Update();
75 76
	}

77
	is->Check();
78

79
	return is;
80 81
}

82
static InputStreamPtr
83
decoder_input_stream_open(DecoderControl &dc, Path path)
84
{
85
	auto is = OpenLocalInputStream(path, dc.mutex);
86 87 88 89 90 91

	assert(is->IsReady());

	return is;
}

92 93 94 95 96
/**
 * Decode a stream with the given decoder plugin.
 *
 * Caller holds DecoderControl::mutex.
 */
97
static bool
98
decoder_stream_decode(const DecoderPlugin &plugin,
99
		      DecoderBridge &bridge,
100
		      InputStream &input_stream)
101
{
102
	assert(plugin.stream_decode != nullptr);
103 104
	assert(bridge.stream_tag == nullptr);
	assert(bridge.decoder_tag == nullptr);
105
	assert(input_stream.IsReady());
106
	assert(bridge.dc.state == DecoderState::START);
107

108
	FormatDebug(decoder_thread_domain, "probing plugin %s", plugin.name);
109

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

113
	/* rewind the stream, so each plugin gets a fresh start */
114 115
	try {
		input_stream.Rewind();
116
	} catch (...) {
117
	}
118

119
	{
120
		const ScopeUnlock unlock(bridge.dc.mutex);
121

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

124
		plugin.StreamDecode(bridge, input_stream);
125

126 127
		SetThreadName("decoder");
	}
128

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

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

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

151
	FormatDebug(decoder_thread_domain, "probing plugin %s", plugin.name);
152

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

156
	{
157
		const ScopeUnlock unlock(bridge.dc.mutex);
158

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

161
		plugin.FileDecode(bridge, path);
162

163 164
		SetThreadName("decoder");
	}
165

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

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

172
gcc_pure
173
static bool
174 175
decoder_check_plugin_mime(const DecoderPlugin &plugin,
			  const InputStream &is) noexcept
176
{
177
	assert(plugin.stream_decode != nullptr);
178

179
	const char *mime_type = is.GetMimeType();
180 181
	return mime_type != nullptr &&
		plugin.SupportsMimeType(GetMimeTypeBase(mime_type).c_str());
182
}
183

184 185
gcc_pure
static bool
186 187
decoder_check_plugin_suffix(const DecoderPlugin &plugin,
			    const char *suffix) noexcept
188 189
{
	assert(plugin.stream_decode != nullptr);
190

191
	return suffix != nullptr && plugin.SupportsSuffix(suffix);
192 193
}

194
gcc_pure
195
static bool
196
decoder_check_plugin(const DecoderPlugin &plugin, const InputStream &is,
197
		     const char *suffix) noexcept
198
{
199 200 201 202
	return plugin.stream_decode != nullptr &&
		(decoder_check_plugin_mime(plugin, is) ||
		 decoder_check_plugin_suffix(plugin, suffix));
}
203

204
static bool
205
decoder_run_stream_plugin(DecoderBridge &bridge, InputStream &is,
206 207 208 209 210
			  const char *suffix,
			  const DecoderPlugin &plugin,
			  bool &tried_r)
{
	if (!decoder_check_plugin(plugin, is, suffix))
211 212
		return false;

213
	bridge.error = std::exception_ptr();
214

215
	tried_r = true;
216
	return decoder_stream_decode(plugin, bridge, is);
217
}
218

219
static bool
220
decoder_run_stream_locked(DecoderBridge &bridge, InputStream &is,
221 222
			  const char *uri, bool &tried_r)
{
223 224
	UriSuffixBuffer suffix_buffer;
	const char *const suffix = uri_get_suffix(uri, suffix_buffer);
225

226 227
	using namespace std::placeholders;
	const auto f = std::bind(decoder_run_stream_plugin,
228
				 std::ref(bridge), std::ref(is), suffix,
229 230
				 _1, std::ref(tried_r));
	return decoder_plugins_try(f);
231 232 233 234 235 236
}

/**
 * Try decoding a stream, using the fallback plugin.
 */
static bool
237
decoder_run_stream_fallback(DecoderBridge &bridge, InputStream &is)
238
{
239
	const struct DecoderPlugin *plugin;
240

241
#ifdef ENABLE_FFMPEG
242 243
	plugin = decoder_plugin_from_name("ffmpeg");
#else
244
	plugin = decoder_plugin_from_name("mad");
245
#endif
246
	return plugin != nullptr && plugin->stream_decode != nullptr &&
247
		decoder_stream_decode(*plugin, bridge, is);
248 249
}

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

262 263 264 265 266 267 268 269
/**
 * 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)
{
	{
270
		const std::lock_guard<Mutex> protect(bridge.dc.mutex);
271 272 273 274 275 276 277 278
		if (bridge.dc.replay_gain_mode == ReplayGainMode::OFF)
			/* ReplayGain is disabled */
			return;
	}

	LoadReplayGain(bridge, is);
}

279 280
/**
 * Try decoding a stream.
281
 *
282
 * DecoderControl::mutex is not locked by caller.
283 284
 */
static bool
285
decoder_run_stream(DecoderBridge &bridge, const char *uri)
286
{
287
	DecoderControl &dc = bridge.dc;
288

289 290
	auto input_stream = decoder_input_stream_open(dc, uri);
	assert(input_stream);
291

292
	MaybeLoadReplayGain(bridge, *input_stream);
293

294
	const std::lock_guard<Mutex> protect(dc.mutex);
295

296
	bool tried = false;
297
	return dc.command == DecoderCommand::STOP ||
298
		decoder_run_stream_locked(bridge, *input_stream, uri,
299
					  tried) ||
300 301
		/* fallback to mp3: this is needed for bastard streams
		   that don't have a suffix or set the mimeType */
302
		(!tried &&
303
		 decoder_run_stream_fallback(bridge, *input_stream));
304 305
}

306 307 308
/**
 * Decode a file with the given decoder plugin.
 *
309
 * DecoderControl::mutex is not locked by caller.
310
 */
311
static bool
312
TryDecoderFile(DecoderBridge &bridge, Path path_fs, const char *suffix,
313
	       InputStream &input_stream,
314
	       const DecoderPlugin &plugin)
315
{
316 317 318
	if (!plugin.SupportsSuffix(suffix))
		return false;

319
	bridge.error = std::exception_ptr();
320

321
	DecoderControl &dc = bridge.dc;
322

323
	if (plugin.file_decode != nullptr) {
324
		const std::lock_guard<Mutex> protect(dc.mutex);
325
		return decoder_file_decode(plugin, bridge, path_fs);
326
	} else if (plugin.stream_decode != nullptr) {
327
		const std::lock_guard<Mutex> protect(dc.mutex);
328
		return decoder_stream_decode(plugin, bridge, input_stream);
329 330
	} else
		return false;
331 332
}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
/**
 * Decode a container file with the given decoder plugin.
 *
 * DecoderControl::mutex is not locked by caller.
 */
static bool
TryContainerDecoder(DecoderBridge &bridge, Path path_fs, const char *suffix,
		    const DecoderPlugin &plugin)
{
	if (plugin.container_scan == nullptr ||
	    plugin.file_decode == nullptr ||
	    !plugin.SupportsSuffix(suffix))
		return false;

	bridge.error = nullptr;

	DecoderControl &dc = bridge.dc;
350
	const std::lock_guard<Mutex> protect(dc.mutex);
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
	return decoder_file_decode(plugin, bridge, path_fs);
}

/**
 * Decode a container file.
 *
 * DecoderControl::mutex is not locked by caller.
 */
static bool
TryContainerDecoder(DecoderBridge &bridge, Path path_fs, const char *suffix)
{
	return decoder_plugins_try([&bridge, path_fs,
				    suffix](const DecoderPlugin &plugin){
					   return TryContainerDecoder(bridge,
								      path_fs,
								      suffix,
								      plugin);
				   });
}

371 372
/**
 * Try decoding a file.
373
 *
374
 * DecoderControl::mutex is not locked by caller.
375 376
 */
static bool
377
decoder_run_file(DecoderBridge &bridge, const char *uri_utf8, Path path_fs)
378
{
379
	const char *suffix = uri_get_suffix(uri_utf8);
380 381
	if (suffix == nullptr)
		return false;
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396
	InputStreamPtr input_stream;

	try {
		input_stream = decoder_input_stream_open(bridge.dc, path_fs);
	} 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;
	}

397
	assert(input_stream);
398

399
	MaybeLoadReplayGain(bridge, *input_stream);
400

401
	auto &is = *input_stream;
402
	return decoder_plugins_try([&bridge, path_fs, suffix,
403
				    &is](const DecoderPlugin &plugin){
404
					   return TryDecoderFile(bridge,
405 406
								 path_fs,
								 suffix,
407
								 is,
408 409
								 plugin);
				   });
410 411
}

412 413 414 415 416 417
/**
 * Decode a song.
 *
 * DecoderControl::mutex is not locked.
 */
static bool
418 419
DecoderUnlockedRunUri(DecoderBridge &bridge,
		      const char *real_uri, Path path_fs)
420
try {
421
	return !path_fs.IsNull()
422 423
		? decoder_run_file(bridge, real_uri, path_fs)
		: decoder_run_stream(bridge, real_uri);
424 425
} catch (StopDecoder) {
	return true;
426
} catch (...) {
427 428 429 430 431
	const char *error_uri = real_uri;
	const std::string allocated = uri_remove_auth(error_uri);
	if (!allocated.empty())
		error_uri = allocated.c_str();

432 433
	std::throw_with_nested(FormatRuntimeError("Failed to decode %s",
						  error_uri));
434 435
}

436 437 438 439 440 441 442 443 444 445
/**
 * 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
{
446
	return !song.IsFile() && !HasRemoteTagScanner(song.GetRealURI());
447 448
}

449 450 451 452 453
/**
 * Decode a song addressed by a #DetachedSong.
 *
 * Caller holds DecoderControl::mutex.
 */
454
static void
455
decoder_run_song(DecoderControl &dc,
456
		 const DetachedSong &song, const char *uri, Path path_fs)
Avuton Olrich's avatar
Avuton Olrich committed
457
{
458 459 460 461 462 463
	DecoderBridge bridge(dc, dc.start_time.IsPositive(),
			     /* 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*/
464
			     !SongHasVolatileTags(song) ? std::make_unique<Tag>(song.GetTag()) : nullptr);
465

466
	dc.state = DecoderState::START;
467
	dc.CommandFinishedLocked();
468

469
	bool success;
470 471
	{
		const ScopeUnlock unlock(dc.mutex);
Warren Dukes's avatar
Warren Dukes committed
472

473
		AtScopeExit(&bridge) {
474
			/* flush the last chunk */
475 476
			if (bridge.current_chunk != nullptr)
				bridge.FlushChunk();
477
		};
478

479
		success = DecoderUnlockedRunUri(bridge, uri, path_fs);
480

481
	}
482

483
	if (bridge.error) {
484
		/* copy the Error from struct Decoder to
485
		   DecoderControl */
486
		std::rethrow_exception(bridge.error);
487
	} else if (success)
488
		dc.state = DecoderState::STOP;
489
	else {
490
		const char *error_uri = song.GetURI();
491 492 493
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
494

495
		throw FormatRuntimeError("Failed to decode %s", error_uri);
496
	}
497

498
	dc.client_cond.signal();
499 500
}

501 502 503 504
/**
 *
 * Caller holds DecoderControl::mutex.
 */
505
static void
506
decoder_run(DecoderControl &dc) noexcept
507
try {
508
	dc.ClearError();
509

510
	assert(dc.song != nullptr);
511
	const DetachedSong &song = *dc.song;
512

513
	const char *const uri_utf8 = song.GetRealURI();
514

515
	Path path_fs = nullptr;
516
	AllocatedPath path_buffer = nullptr;
517
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
518
		path_buffer = AllocatedPath::FromUTF8Throw(uri_utf8);
519
		path_fs = path_buffer;
520 521
	}

522
	decoder_run_song(dc, song, uri_utf8, path_fs);
523 524
} catch (...) {
	dc.state = DecoderState::ERROR;
525
	dc.command = DecoderCommand::NONE;
526 527
	dc.error = std::current_exception();
	dc.client_cond.signal();
528 529
}

530
void
531
DecoderControl::RunThread() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
532
{
533 534
	SetThreadName("decoder");

535
	const std::lock_guard<Mutex> protect(mutex);
536

537
	do {
538 539
		assert(state == DecoderState::STOP ||
		       state == DecoderState::ERROR);
540

541
		switch (command) {
542
		case DecoderCommand::START:
543 544 545
			CycleMixRamp();
			replay_gain_prev_db = replay_gain_db;
			replay_gain_db = 0;
546

547
			decoder_run(*this);
548

549
			if (state == DecoderState::ERROR) {
550
				try {
551
					std::rethrow_exception(error);
552
				} catch (...) {
553
					LogError(std::current_exception());
554 555
				}
			}
556

557
			break;
558

559
		case DecoderCommand::SEEK:
560 561 562 563 564 565
			/* 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 */
566
			pipe->Clear();
567

568
			decoder_run(*this);
569 570
			break;

571
		case DecoderCommand::STOP:
572
			CommandFinishedLocked();
573 574
			break;

575
		case DecoderCommand::NONE:
576
			Wait();
577
			break;
Warren Dukes's avatar
Warren Dukes committed
578
		}
579
	} while (command != DecoderCommand::NONE || !quit);
580
}