Thread.cxx 14.3 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 "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 54 55 56 57 58 59 60 61 62 63
/**
 * 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);

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

	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;
}

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

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

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

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

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

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

118
		plugin.StreamDecode(bridge, input_stream);
119

120 121
		SetThreadName("decoder");
	}
122

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

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

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

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

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

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

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

155
		plugin.FileDecode(bridge, path);
156

157 158
		SetThreadName("decoder");
	}
159

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

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

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

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

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

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

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

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

208
	bridge.Reset();
209

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

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

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

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

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

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

245 246
/**
 * Attempt to load replay gain data, and pass it to
247
 * DecoderClient::SubmitReplayGain().
248 249
 */
static void
250
LoadReplayGain(DecoderClient &client, InputStream &is)
251 252 253
{
	ReplayGainInfo info;
	if (replay_gain_ape_read(is, info))
254
		client.SubmitReplayGain(&info);
255 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
		const std::lock_guard<Mutex> protect(bridge.dc.mutex);
266 267 268 269 270 271 272 273
		if (bridge.dc.replay_gain_mode == ReplayGainMode::OFF)
			/* ReplayGain is disabled */
			return;
	}

	LoadReplayGain(bridge, is);
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
/**
 * 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);
	});
}

292 293
/**
 * Try decoding a stream.
294
 *
295
 * DecoderControl::mutex is not locked by caller.
296 297
 */
static bool
298
decoder_run_stream(DecoderBridge &bridge, const char *uri)
299
{
300 301 302
	if (TryUriDecode(bridge, uri))
		return true;

303
	DecoderControl &dc = bridge.dc;
304

305
	auto input_stream = bridge.OpenUri(uri);
306
	assert(input_stream);
307

308
	MaybeLoadReplayGain(bridge, *input_stream);
309

310
	std::unique_lock<Mutex> lock(dc.mutex);
311

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

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

335
	bridge.Reset();
336

337
	DecoderControl &dc = bridge.dc;
338

339
	if (plugin.file_decode != nullptr) {
340
		const std::lock_guard<Mutex> protect(dc.mutex);
341
		return decoder_file_decode(plugin, bridge, path_fs);
342
	} else if (plugin.stream_decode != nullptr) {
343 344 345
		std::unique_lock<Mutex> lock(dc.mutex);
		return decoder_stream_decode(plugin, bridge, input_stream,
					     lock);
346 347
	} else
		return false;
348 349
}

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

365
	bridge.Reset();
366 367

	DecoderControl &dc = bridge.dc;
368
	const std::lock_guard<Mutex> protect(dc.mutex);
369 370 371 372 373 374 375 376 377
	return decoder_file_decode(plugin, bridge, path_fs);
}

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

390 391
/**
 * Try decoding a file.
392
 *
393
 * DecoderControl::mutex is not locked by caller.
394 395
 */
static bool
396
decoder_run_file(DecoderBridge &bridge, const char *uri_utf8, Path path_fs)
397
{
398 399
	const auto suffix = uri_get_suffix(uri_utf8);
	if (suffix.empty())
400
		return false;
401

402 403 404
	InputStreamPtr input_stream;

	try {
405
		input_stream = bridge.OpenLocal(path_fs, uri_utf8);
406 407 408 409 410 411 412 413 414 415
	} 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;
	}

416
	assert(input_stream);
417

418
	MaybeLoadReplayGain(bridge, *input_stream);
419

420
	auto &is = *input_stream;
421
	return decoder_plugins_try([&bridge, path_fs, suffix,
422
				    &is](const DecoderPlugin &plugin){
423
					   return TryDecoderFile(bridge,
424 425
								 path_fs,
								 suffix,
426
								 is,
427 428
								 plugin);
				   });
429 430
}

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

451 452
	std::throw_with_nested(FormatRuntimeError("Failed to decode %s",
						  error_uri));
453 454
}

455 456 457 458 459 460 461 462 463 464
/**
 * 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
{
465
	return !song.IsFile() && !HasRemoteTagScanner(song.GetRealURI());
466 467
}

468 469 470 471 472
/**
 * Decode a song addressed by a #DetachedSong.
 *
 * Caller holds DecoderControl::mutex.
 */
473
static void
474
decoder_run_song(DecoderControl &dc,
475
		 const DetachedSong &song, const char *uri, Path path_fs)
Avuton Olrich's avatar
Avuton Olrich committed
476
{
477 478 479 480 481
	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;

482
	DecoderBridge bridge(dc, dc.start_time.IsPositive(),
483
			     dc.initial_seek_essential,
484 485 486 487 488
			     /* 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*/
489
			     !SongHasVolatileTags(song) ? std::make_unique<Tag>(song.GetTag()) : nullptr);
490

491
	dc.state = DecoderState::START;
492
	dc.CommandFinishedLocked();
493

494
	bool success;
495 496
	{
		const ScopeUnlock unlock(dc.mutex);
Warren Dukes's avatar
Warren Dukes committed
497

498
		AtScopeExit(&bridge) {
499
			/* flush the last chunk */
500
			bridge.CheckFlushChunk();
501
		};
502

503
		success = DecoderUnlockedRunUri(bridge, uri, path_fs);
504

505
	}
506

507 508 509
	bridge.CheckRethrowError();

	if (success)
510
		dc.state = DecoderState::STOP;
511
	else {
512
		const char *error_uri = song.GetURI();
513 514 515
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
516

517
		throw FormatRuntimeError("Failed to decode %s", error_uri);
518
	}
519

520
	dc.client_cond.notify_one();
521 522
}

523 524 525 526
/**
 *
 * Caller holds DecoderControl::mutex.
 */
527
static void
528
decoder_run(DecoderControl &dc) noexcept
529
try {
530
	dc.ClearError();
531

532
	assert(dc.song != nullptr);
533
	const DetachedSong &song = *dc.song;
534

535
	const char *const uri_utf8 = song.GetRealURI();
536

537
	Path path_fs = nullptr;
538
	AllocatedPath path_buffer = nullptr;
539
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
540
		path_buffer = AllocatedPath::FromUTF8Throw(uri_utf8);
541
		path_fs = path_buffer;
542 543
	}

544
	decoder_run_song(dc, song, uri_utf8, path_fs);
545 546
} catch (...) {
	dc.state = DecoderState::ERROR;
547
	dc.command = DecoderCommand::NONE;
548
	dc.error = std::current_exception();
549
	dc.client_cond.notify_one();
550 551
}

552
void
553
DecoderControl::RunThread() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
554
{
555 556
	SetThreadName("decoder");

557
	std::unique_lock<Mutex> lock(mutex);
558

559
	do {
560 561
		assert(state == DecoderState::STOP ||
		       state == DecoderState::ERROR);
562

563
		switch (command) {
564
		case DecoderCommand::START:
565 566 567
			CycleMixRamp();
			replay_gain_prev_db = replay_gain_db;
			replay_gain_db = 0;
568

569
			decoder_run(*this);
570

571
			if (state == DecoderState::ERROR) {
572
				try {
573
					std::rethrow_exception(error);
574
				} catch (...) {
575
					LogError(std::current_exception());
576 577
				}
			}
578

579
			break;
580

581
		case DecoderCommand::SEEK:
582 583 584 585 586 587
			/* 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 */
588
			pipe->Clear();
589

590
			decoder_run(*this);
591 592
			break;

593
		case DecoderCommand::STOP:
594
			CommandFinishedLocked();
595 596
			break;

597
		case DecoderCommand::NONE:
598
			Wait(lock);
599
			break;
Warren Dukes's avatar
Warren Dukes committed
600
		}
601
	} while (command != DecoderCommand::NONE || !quit);
602
}