Thread.cxx 13.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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 "thread/Name.hxx"
40
#include "tag/ApeReplayGain.hxx"
41
#include "Log.hxx"
Warren Dukes's avatar
Warren Dukes committed
42

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

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

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

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

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

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

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

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

82
		plugin.StreamDecode(bridge, input_stream);
83

84 85
		SetThreadName("decoder");
	}
86

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

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

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

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

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

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

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

119
		plugin.FileDecode(bridge, path);
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
gcc_pure
131
static bool
132 133
decoder_check_plugin_mime(const DecoderPlugin &plugin,
			  const InputStream &is) noexcept
134
{
135
	assert(plugin.stream_decode != nullptr);
136

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

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

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

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

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

172
	bridge.Reset();
173

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

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

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

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

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

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

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

	LoadReplayGain(bridge, is);
}

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

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

254
	MaybeLoadReplayGain(bridge, *input_stream);
255

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

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

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

281
	bridge.Reset();
282

283
	DecoderControl &dc = bridge.dc;
284

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

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

310
	bridge.Reset();
311 312

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

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

346 347 348
	InputStreamPtr input_stream;

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

360
	assert(input_stream);
361

362
	MaybeLoadReplayGain(bridge, *input_stream);
363

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

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

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

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

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

426 427 428 429 430 431
	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*/
432
			     !SongHasVolatileTags(song) ? std::make_unique<Tag>(song.GetTag()) : nullptr);
433

434
	dc.state = DecoderState::START;
435
	dc.CommandFinishedLocked();
436

437
	bool success;
438 439
	{
		const ScopeUnlock unlock(dc.mutex);
Warren Dukes's avatar
Warren Dukes committed
440

441
		AtScopeExit(&bridge) {
442
			/* flush the last chunk */
443
			bridge.CheckFlushChunk();
444
		};
445

446
		success = DecoderUnlockedRunUri(bridge, uri, path_fs);
447

448
	}
449

450 451 452
	bridge.CheckRethrowError();

	if (success)
453
		dc.state = DecoderState::STOP;
454
	else {
455
		const char *error_uri = song.GetURI();
456 457 458
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
459

460
		throw FormatRuntimeError("Failed to decode %s", error_uri);
461
	}
462

463
	dc.client_cond.notify_one();
464 465
}

466 467 468 469
/**
 *
 * Caller holds DecoderControl::mutex.
 */
470
static void
471
decoder_run(DecoderControl &dc) noexcept
472
try {
473
	dc.ClearError();
474

475
	assert(dc.song != nullptr);
476
	const DetachedSong &song = *dc.song;
477

478
	const char *const uri_utf8 = song.GetRealURI();
479

480
	Path path_fs = nullptr;
481
	AllocatedPath path_buffer = nullptr;
482
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
483
		path_buffer = AllocatedPath::FromUTF8Throw(uri_utf8);
484
		path_fs = path_buffer;
485 486
	}

487
	decoder_run_song(dc, song, uri_utf8, path_fs);
488 489
} catch (...) {
	dc.state = DecoderState::ERROR;
490
	dc.command = DecoderCommand::NONE;
491
	dc.error = std::current_exception();
492
	dc.client_cond.notify_one();
493 494
}

495
void
496
DecoderControl::RunThread() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
497
{
498 499
	SetThreadName("decoder");

500
	std::unique_lock<Mutex> lock(mutex);
501

502
	do {
503 504
		assert(state == DecoderState::STOP ||
		       state == DecoderState::ERROR);
505

506
		switch (command) {
507
		case DecoderCommand::START:
508 509 510
			CycleMixRamp();
			replay_gain_prev_db = replay_gain_db;
			replay_gain_db = 0;
511

512
			decoder_run(*this);
513

514
			if (state == DecoderState::ERROR) {
515
				try {
516
					std::rethrow_exception(error);
517
				} catch (...) {
518
					LogError(std::current_exception());
519 520
				}
			}
521

522
			break;
523

524
		case DecoderCommand::SEEK:
525 526 527 528 529 530
			/* 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 */
531
			pipe->Clear();
532

533
			decoder_run(*this);
534 535
			break;

536
		case DecoderCommand::STOP:
537
			CommandFinishedLocked();
538 539
			break;

540
		case DecoderCommand::NONE:
541
			Wait(lock);
542
			break;
Warren Dukes's avatar
Warren Dukes committed
543
		}
544
	} while (command != DecoderCommand::NONE || !quit);
545
}