Thread.cxx 13 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 52 53 54
/**
 * Decode a stream with the given decoder plugin.
 *
 * Caller holds DecoderControl::mutex.
 */
55
static bool
56
decoder_stream_decode(const DecoderPlugin &plugin,
57
		      DecoderBridge &bridge,
58 59
		      InputStream &input_stream,
		      std::unique_lock<Mutex> &lock)
60
{
61
	assert(plugin.stream_decode != nullptr);
62 63
	assert(bridge.stream_tag == nullptr);
	assert(bridge.decoder_tag == nullptr);
64
	assert(input_stream.IsReady());
65
	assert(bridge.dc.state == DecoderState::START);
66

67
	FormatDebug(decoder_thread_domain, "probing plugin %s", plugin.name);
68

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

72
	/* rewind the stream, so each plugin gets a fresh start */
73
	try {
74
		input_stream.Rewind(lock);
75
	} catch (...) {
76
	}
77

78
	{
79
		const ScopeUnlock unlock(bridge.dc.mutex);
80

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

83
		plugin.StreamDecode(bridge, input_stream);
84

85 86
		SetThreadName("decoder");
	}
87

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

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

94 95 96 97 98
/**
 * Decode a file with the given decoder plugin.
 *
 * Caller holds DecoderControl::mutex.
 */
99
static bool
100
decoder_file_decode(const DecoderPlugin &plugin,
101
		    DecoderBridge &bridge, Path path)
102
{
103
	assert(plugin.file_decode != nullptr);
104 105
	assert(bridge.stream_tag == nullptr);
	assert(bridge.decoder_tag == nullptr);
106 107
	assert(!path.IsNull());
	assert(path.IsAbsolute());
108
	assert(bridge.dc.state == DecoderState::START);
109

110
	FormatDebug(decoder_thread_domain, "probing plugin %s", plugin.name);
111

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

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

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

120
		plugin.FileDecode(bridge, path);
121

122 123
		SetThreadName("decoder");
	}
124

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

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

131
gcc_pure
132
static bool
133 134
decoder_check_plugin_mime(const DecoderPlugin &plugin,
			  const InputStream &is) noexcept
135
{
136
	assert(plugin.stream_decode != nullptr);
137

138
	const char *mime_type = is.GetMimeType();
139 140
	return mime_type != nullptr &&
		plugin.SupportsMimeType(GetMimeTypeBase(mime_type).c_str());
141
}
142

143 144
gcc_pure
static bool
145 146
decoder_check_plugin_suffix(const DecoderPlugin &plugin,
			    const char *suffix) noexcept
147 148
{
	assert(plugin.stream_decode != nullptr);
149

150
	return suffix != nullptr && plugin.SupportsSuffix(suffix);
151 152
}

153
gcc_pure
154
static bool
155
decoder_check_plugin(const DecoderPlugin &plugin, const InputStream &is,
156
		     const char *suffix) noexcept
157
{
158 159 160 161
	return plugin.stream_decode != nullptr &&
		(decoder_check_plugin_mime(plugin, is) ||
		 decoder_check_plugin_suffix(plugin, suffix));
}
162

163
static bool
164
decoder_run_stream_plugin(DecoderBridge &bridge, InputStream &is,
165
			  std::unique_lock<Mutex> &lock,
166 167 168 169 170
			  const char *suffix,
			  const DecoderPlugin &plugin,
			  bool &tried_r)
{
	if (!decoder_check_plugin(plugin, is, suffix))
171 172
		return false;

173
	bridge.Reset();
174

175
	tried_r = true;
176
	return decoder_stream_decode(plugin, bridge, is, lock);
177
}
178

179
static bool
180
decoder_run_stream_locked(DecoderBridge &bridge, InputStream &is,
181
			  std::unique_lock<Mutex> &lock,
182 183
			  const char *uri, bool &tried_r)
{
184 185
	UriSuffixBuffer suffix_buffer;
	const char *const suffix = uri_get_suffix(uri, suffix_buffer);
186

187 188
	using namespace std::placeholders;
	const auto f = std::bind(decoder_run_stream_plugin,
189 190
				 std::ref(bridge), std::ref(is), std::ref(lock),
				 suffix,
191 192
				 _1, std::ref(tried_r));
	return decoder_plugins_try(f);
193 194 195 196 197 198
}

/**
 * Try decoding a stream, using the fallback plugin.
 */
static bool
199 200
decoder_run_stream_fallback(DecoderBridge &bridge, InputStream &is,
			    std::unique_lock<Mutex> &lock)
201
{
202
	const struct DecoderPlugin *plugin;
203

204
#ifdef ENABLE_FFMPEG
205 206
	plugin = decoder_plugin_from_name("ffmpeg");
#else
207
	plugin = decoder_plugin_from_name("mad");
208
#endif
209
	return plugin != nullptr && plugin->stream_decode != nullptr &&
210
		decoder_stream_decode(*plugin, bridge, is, lock);
211 212
}

213 214
/**
 * Attempt to load replay gain data, and pass it to
215
 * DecoderClient::SubmitReplayGain().
216 217
 */
static void
218
LoadReplayGain(DecoderClient &client, InputStream &is)
219 220 221
{
	ReplayGainInfo info;
	if (replay_gain_ape_read(is, info))
222
		client.SubmitReplayGain(&info);
223 224
}

225 226 227 228 229 230 231 232
/**
 * 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)
{
	{
233
		const std::lock_guard<Mutex> protect(bridge.dc.mutex);
234 235 236 237 238 239 240 241
		if (bridge.dc.replay_gain_mode == ReplayGainMode::OFF)
			/* ReplayGain is disabled */
			return;
	}

	LoadReplayGain(bridge, is);
}

242 243
/**
 * Try decoding a stream.
244
 *
245
 * DecoderControl::mutex is not locked by caller.
246 247
 */
static bool
248
decoder_run_stream(DecoderBridge &bridge, const char *uri)
249
{
250
	DecoderControl &dc = bridge.dc;
251

252
	auto input_stream = bridge.OpenUri(uri);
253
	assert(input_stream);
254

255
	MaybeLoadReplayGain(bridge, *input_stream);
256

257
	std::unique_lock<Mutex> lock(dc.mutex);
258

259
	bool tried = false;
260
	return dc.command == DecoderCommand::STOP ||
261
		decoder_run_stream_locked(bridge, *input_stream, lock, uri,
262
					  tried) ||
263 264
		/* fallback to mp3: this is needed for bastard streams
		   that don't have a suffix or set the mimeType */
265
		(!tried &&
266
		 decoder_run_stream_fallback(bridge, *input_stream, lock));
267 268
}

269 270 271
/**
 * Decode a file with the given decoder plugin.
 *
272
 * DecoderControl::mutex is not locked by caller.
273
 */
274
static bool
275
TryDecoderFile(DecoderBridge &bridge, Path path_fs, const char *suffix,
276
	       InputStream &input_stream,
277
	       const DecoderPlugin &plugin)
278
{
279 280 281
	if (!plugin.SupportsSuffix(suffix))
		return false;

282
	bridge.Reset();
283

284
	DecoderControl &dc = bridge.dc;
285

286
	if (plugin.file_decode != nullptr) {
287
		const std::lock_guard<Mutex> protect(dc.mutex);
288
		return decoder_file_decode(plugin, bridge, path_fs);
289
	} else if (plugin.stream_decode != nullptr) {
290 291 292
		std::unique_lock<Mutex> lock(dc.mutex);
		return decoder_stream_decode(plugin, bridge, input_stream,
					     lock);
293 294
	} else
		return false;
295 296
}

297 298 299 300 301 302 303 304 305 306 307 308 309 310
/**
 * 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;

311
	bridge.Reset();
312 313

	DecoderControl &dc = bridge.dc;
314
	const std::lock_guard<Mutex> protect(dc.mutex);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
	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);
				   });
}

335 336
/**
 * Try decoding a file.
337
 *
338
 * DecoderControl::mutex is not locked by caller.
339 340
 */
static bool
341
decoder_run_file(DecoderBridge &bridge, const char *uri_utf8, Path path_fs)
342
{
343
	const char *suffix = uri_get_suffix(uri_utf8);
344 345
	if (suffix == nullptr)
		return false;
346

347 348 349
	InputStreamPtr input_stream;

	try {
350
		input_stream = OpenLocalInputStream(path_fs, bridge.dc.mutex);
351 352 353 354 355 356 357 358 359 360
	} 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;
	}

361
	assert(input_stream);
362

363
	MaybeLoadReplayGain(bridge, *input_stream);
364

365
	auto &is = *input_stream;
366
	return decoder_plugins_try([&bridge, path_fs, suffix,
367
				    &is](const DecoderPlugin &plugin){
368
					   return TryDecoderFile(bridge,
369 370
								 path_fs,
								 suffix,
371
								 is,
372 373
								 plugin);
				   });
374 375
}

376 377 378 379 380 381
/**
 * Decode a song.
 *
 * DecoderControl::mutex is not locked.
 */
static bool
382 383
DecoderUnlockedRunUri(DecoderBridge &bridge,
		      const char *real_uri, Path path_fs)
384
try {
385
	return !path_fs.IsNull()
386 387
		? decoder_run_file(bridge, real_uri, path_fs)
		: decoder_run_stream(bridge, real_uri);
388 389
} catch (StopDecoder) {
	return true;
390
} catch (...) {
391 392 393 394 395
	const char *error_uri = real_uri;
	const std::string allocated = uri_remove_auth(error_uri);
	if (!allocated.empty())
		error_uri = allocated.c_str();

396 397
	std::throw_with_nested(FormatRuntimeError("Failed to decode %s",
						  error_uri));
398 399
}

400 401 402 403 404 405 406 407 408 409
/**
 * 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
{
410
	return !song.IsFile() && !HasRemoteTagScanner(song.GetRealURI());
411 412
}

413 414 415 416 417
/**
 * Decode a song addressed by a #DetachedSong.
 *
 * Caller holds DecoderControl::mutex.
 */
418
static void
419
decoder_run_song(DecoderControl &dc,
420
		 const DetachedSong &song, const char *uri, Path path_fs)
Avuton Olrich's avatar
Avuton Olrich committed
421
{
422 423 424 425 426 427
	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*/
428
			     !SongHasVolatileTags(song) ? std::make_unique<Tag>(song.GetTag()) : nullptr);
429

430
	dc.state = DecoderState::START;
431
	dc.CommandFinishedLocked();
432

433
	bool success;
434 435
	{
		const ScopeUnlock unlock(dc.mutex);
Warren Dukes's avatar
Warren Dukes committed
436

437
		AtScopeExit(&bridge) {
438
			/* flush the last chunk */
439
			bridge.CheckFlushChunk();
440
		};
441

442
		success = DecoderUnlockedRunUri(bridge, uri, path_fs);
443

444
	}
445

446 447 448
	bridge.CheckRethrowError();

	if (success)
449
		dc.state = DecoderState::STOP;
450
	else {
451
		const char *error_uri = song.GetURI();
452 453 454
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
455

456
		throw FormatRuntimeError("Failed to decode %s", error_uri);
457
	}
458

459
	dc.client_cond.notify_one();
460 461
}

462 463 464 465
/**
 *
 * Caller holds DecoderControl::mutex.
 */
466
static void
467
decoder_run(DecoderControl &dc) noexcept
468
try {
469
	dc.ClearError();
470

471
	assert(dc.song != nullptr);
472
	const DetachedSong &song = *dc.song;
473

474
	const char *const uri_utf8 = song.GetRealURI();
475

476
	Path path_fs = nullptr;
477
	AllocatedPath path_buffer = nullptr;
478
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
479
		path_buffer = AllocatedPath::FromUTF8Throw(uri_utf8);
480
		path_fs = path_buffer;
481 482
	}

483
	decoder_run_song(dc, song, uri_utf8, path_fs);
484 485
} catch (...) {
	dc.state = DecoderState::ERROR;
486
	dc.command = DecoderCommand::NONE;
487
	dc.error = std::current_exception();
488
	dc.client_cond.notify_one();
489 490
}

491
void
492
DecoderControl::RunThread() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
493
{
494 495
	SetThreadName("decoder");

496
	std::unique_lock<Mutex> lock(mutex);
497

498
	do {
499 500
		assert(state == DecoderState::STOP ||
		       state == DecoderState::ERROR);
501

502
		switch (command) {
503
		case DecoderCommand::START:
504 505 506
			CycleMixRamp();
			replay_gain_prev_db = replay_gain_db;
			replay_gain_db = 0;
507

508
			decoder_run(*this);
509

510
			if (state == DecoderState::ERROR) {
511
				try {
512
					std::rethrow_exception(error);
513
				} catch (...) {
514
					LogError(std::current_exception());
515 516
				}
			}
517

518
			break;
519

520
		case DecoderCommand::SEEK:
521 522 523 524 525 526
			/* 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 */
527
			pipe->Clear();
528

529
			decoder_run(*this);
530 531
			break;

532
		case DecoderCommand::STOP:
533
			CommandFinishedLocked();
534 535
			break;

536
		case DecoderCommand::NONE:
537
			Wait(lock);
538
			break;
Warren Dukes's avatar
Warren Dukes committed
539
		}
540
	} while (command != DecoderCommand::NONE || !quit);
541
}