DecoderThread.cxx 13.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 "DecoderThread.hxx"
22
#include "DecoderControl.hxx"
23
#include "Bridge.hxx"
24 25
#include "DecoderError.hxx"
#include "DecoderPlugin.hxx"
26
#include "DetachedSong.hxx"
27
#include "MusicPipe.hxx"
28
#include "fs/Traits.hxx"
29
#include "fs/AllocatedPath.hxx"
30
#include "DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
31
#include "input/InputStream.hxx"
32
#include "input/LocalOpen.hxx"
33
#include "DecoderList.hxx"
34
#include "system/Error.hxx"
35
#include "util/MimeType.hxx"
Max Kellermann's avatar
Max Kellermann committed
36
#include "util/UriUtil.hxx"
37
#include "util/RuntimeError.hxx"
38
#include "util/Domain.hxx"
39
#include "util/ScopeExit.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
	auto is = InputStream::Open(uri, dc.mutex, dc.cond);
60 61 62 63

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

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

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

71
		dc.Wait();
72

73
		is->Update();
74 75
	}

76
	is->Check();
77

78
	return is;
79 80
}

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

	assert(is->IsReady());

	return is;
}

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

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

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

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

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

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

123
		plugin.StreamDecode(bridge, input_stream);
124

125 126
		SetThreadName("decoder");
	}
127

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

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

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

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

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

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

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

160
		plugin.FileDecode(bridge, path);
161

162 163
		SetThreadName("decoder");
	}
164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	LoadReplayGain(bridge, is);
}

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

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

291
	MaybeLoadReplayGain(bridge, *input_stream);
292

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

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

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

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

320
	DecoderControl &dc = bridge.dc;
321

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

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
/**
 * 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;
349
	const std::lock_guard<Mutex> protect(dc.mutex);
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
	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);
				   });
}

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

382 383 384 385 386 387 388 389 390 391 392 393 394 395
	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;
	}

396
	assert(input_stream);
397

398
	MaybeLoadReplayGain(bridge, *input_stream);
399

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

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

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

435 436 437 438 439
/**
 * Decode a song addressed by a #DetachedSong.
 *
 * Caller holds DecoderControl::mutex.
 */
440
static void
441
decoder_run_song(DecoderControl &dc,
442
		 const DetachedSong &song, const char *uri, Path path_fs)
Avuton Olrich's avatar
Avuton Olrich committed
443
{
444 445 446 447 448 449 450
	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*/
			     song.IsFile() ? new Tag(song.GetTag()) : nullptr);
451

452
	dc.state = DecoderState::START;
453
	dc.CommandFinishedLocked();
454

455
	bool success;
456 457
	{
		const ScopeUnlock unlock(dc.mutex);
Warren Dukes's avatar
Warren Dukes committed
458

459
		AtScopeExit(&bridge) {
460
			/* flush the last chunk */
461 462
			if (bridge.current_chunk != nullptr)
				bridge.FlushChunk();
463
		};
464

465
		success = DecoderUnlockedRunUri(bridge, uri, path_fs);
466

467
	}
468

469
	if (bridge.error) {
470
		/* copy the Error from struct Decoder to
471
		   DecoderControl */
472
		std::rethrow_exception(bridge.error);
473
	} else if (success)
474
		dc.state = DecoderState::STOP;
475
	else {
476
		const char *error_uri = song.GetURI();
477 478 479
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
480

481
		throw FormatRuntimeError("Failed to decode %s", error_uri);
482
	}
483

484
	dc.client_cond.signal();
485 486
}

487 488 489 490
/**
 *
 * Caller holds DecoderControl::mutex.
 */
491
static void
492
decoder_run(DecoderControl &dc)
493
try {
494
	dc.ClearError();
495

496
	assert(dc.song != nullptr);
497
	const DetachedSong &song = *dc.song;
498

499
	const char *const uri_utf8 = song.GetRealURI();
500

501 502
	Path path_fs = Path::Null();
	AllocatedPath path_buffer = AllocatedPath::Null();
503
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
504
		path_buffer = AllocatedPath::FromUTF8Throw(uri_utf8);
505
		path_fs = path_buffer;
506 507
	}

508
	decoder_run_song(dc, song, uri_utf8, path_fs);
509 510
} catch (...) {
	dc.state = DecoderState::ERROR;
511
	dc.command = DecoderCommand::NONE;
512 513
	dc.error = std::current_exception();
	dc.client_cond.signal();
514 515
}

516 517
void
DecoderControl::RunThread()
Avuton Olrich's avatar
Avuton Olrich committed
518
{
519 520
	SetThreadName("decoder");

521
	const std::lock_guard<Mutex> protect(mutex);
522

523
	do {
524 525
		assert(state == DecoderState::STOP ||
		       state == DecoderState::ERROR);
526

527
		switch (command) {
528
		case DecoderCommand::START:
529 530 531
			CycleMixRamp();
			replay_gain_prev_db = replay_gain_db;
			replay_gain_db = 0;
532

533
			decoder_run(*this);
534

535
			if (state == DecoderState::ERROR) {
536
				try {
537
					std::rethrow_exception(error);
538 539 540 541 542
				} catch (const std::exception &e) {
					LogError(e);
				} catch (...) {
				}
			}
543

544
			break;
545

546
		case DecoderCommand::SEEK:
547 548 549 550 551 552
			/* 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 */
553
			pipe->Clear(*buffer);
554

555
			decoder_run(*this);
556 557
			break;

558
		case DecoderCommand::STOP:
559
			CommandFinishedLocked();
560 561
			break;

562
		case DecoderCommand::NONE:
563
			Wait();
564
			break;
Warren Dukes's avatar
Warren Dukes committed
565
		}
566
	} while (command != DecoderCommand::NONE || !quit);
567
}
Warren Dukes's avatar
Warren Dukes committed
568

569
void
570
decoder_thread_start(DecoderControl &dc)
571
{
572
	assert(!dc.thread.IsDefined());
573

574
	dc.quit = false;
575
	dc.thread.Start();
Warren Dukes's avatar
Warren Dukes committed
576
}