DecoderThread.cxx 11.2 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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 23
#include "DecoderControl.hxx"
#include "DecoderInternal.hxx"
24 25
#include "DecoderError.hxx"
#include "DecoderPlugin.hxx"
26
#include "DetachedSong.hxx"
27
#include "system/FatalError.hxx"
28
#include "MusicPipe.hxx"
29
#include "fs/Traits.hxx"
30
#include "fs/AllocatedPath.hxx"
31
#include "DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
32
#include "input/InputStream.hxx"
33
#include "input/LocalOpen.hxx"
34
#include "DecoderList.hxx"
Max Kellermann's avatar
Max Kellermann committed
35
#include "util/UriUtil.hxx"
36
#include "util/Error.hxx"
37
#include "util/Domain.hxx"
38
#include "thread/Name.hxx"
39
#include "tag/ApeReplayGain.hxx"
40
#include "Log.hxx"
Warren Dukes's avatar
Warren Dukes committed
41

42 43
#include <functional>

44
static constexpr Domain decoder_thread_domain("decoder_thread");
45

46 47 48 49
/**
 * Marks the current decoder command as "finished" and notifies the
 * player thread.
 *
50
 * @param dc the #DecoderControl object; must be locked
51 52
 */
static void
53
decoder_command_finished_locked(DecoderControl &dc)
54
{
55
	assert(dc.command != DecoderCommand::NONE);
56

57
	dc.command = DecoderCommand::NONE;
58

59
	dc.client_cond.signal();
60 61
}

62
/**
63
 * Opens the input stream with input_stream::Open(), and waits until
64 65 66 67 68 69
 * the stream gets ready.  If a decoder STOP command is received
 * during that, it cancels the operation (but does not close the
 * stream).
 *
 * Unlock the decoder before calling this function.
 *
70
 * @return an input_stream on success or if #DecoderCommand::STOP is
71
 * received, nullptr on error
72
 */
73
static InputStream *
74
decoder_input_stream_open(DecoderControl &dc, const char *uri)
75
{
76
	Error error;
77

78
	InputStream *is = InputStream::Open(uri, dc.mutex, dc.cond, error);
79
	if (is == nullptr) {
80
		if (error.IsDefined())
81
			LogError(error);
82

83
		return nullptr;
84
	}
85 86 87 88

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

89
	dc.Lock();
90

91
	is->Update();
92
	while (!is->IsReady() &&
93 94
	       dc.command != DecoderCommand::STOP) {
		dc.Wait();
95

96
		is->Update();
97 98
	}

99
	if (!is->Check(error)) {
100
		dc.Unlock();
101

102
		LogError(error);
103
		return nullptr;
104 105
	}

106
	dc.Unlock();
107

108
	return is;
109 110
}

111 112 113 114 115 116 117
static InputStream *
decoder_input_stream_open(DecoderControl &dc, Path path)
{
	Error error;

	InputStream *is = OpenLocalInputStream(path, dc.mutex, dc.cond, error);
	if (is == nullptr) {
118
		LogError(error);
119 120 121 122 123 124 125 126
		return nullptr;
	}

	assert(is->IsReady());

	return is;
}

127
static bool
128
decoder_stream_decode(const DecoderPlugin &plugin,
129
		      Decoder &decoder,
130
		      InputStream &input_stream)
131
{
132
	assert(plugin.stream_decode != nullptr);
133 134
	assert(decoder.stream_tag == nullptr);
	assert(decoder.decoder_tag == nullptr);
135
	assert(input_stream.IsReady());
136
	assert(decoder.dc.state == DecoderState::START);
137

138
	FormatDebug(decoder_thread_domain, "probing plugin %s", plugin.name);
139

140
	if (decoder.dc.command == DecoderCommand::STOP)
141 142
		return true;

143
	/* rewind the stream, so each plugin gets a fresh start */
144
	input_stream.Rewind(IgnoreError());
145

146
	decoder.dc.Unlock();
147

148 149
	FormatThreadName("decoder:%s", plugin.name);

150
	plugin.StreamDecode(decoder, input_stream);
151

152 153
	SetThreadName("decoder");

154
	decoder.dc.Lock();
155

156 157
	assert(decoder.dc.state == DecoderState::START ||
	       decoder.dc.state == DecoderState::DECODE);
158

159
	return decoder.dc.state != DecoderState::START;
160 161 162
}

static bool
163
decoder_file_decode(const DecoderPlugin &plugin,
164
		    Decoder &decoder, Path path)
165
{
166
	assert(plugin.file_decode != nullptr);
167 168
	assert(decoder.stream_tag == nullptr);
	assert(decoder.decoder_tag == nullptr);
169 170
	assert(!path.IsNull());
	assert(path.IsAbsolute());
171
	assert(decoder.dc.state == DecoderState::START);
172

173
	FormatDebug(decoder_thread_domain, "probing plugin %s", plugin.name);
174

175
	if (decoder.dc.command == DecoderCommand::STOP)
176 177
		return true;

178
	decoder.dc.Unlock();
179

180 181
	FormatThreadName("decoder:%s", plugin.name);

182
	plugin.FileDecode(decoder, path);
183

184 185
	SetThreadName("decoder");

186
	decoder.dc.Lock();
187

188 189
	assert(decoder.dc.state == DecoderState::START ||
	       decoder.dc.state == DecoderState::DECODE);
190

191
	return decoder.dc.state != DecoderState::START;
192 193
}

194
gcc_pure
195
static bool
196
decoder_check_plugin_mime(const DecoderPlugin &plugin, const InputStream &is)
197
{
198
	assert(plugin.stream_decode != nullptr);
199

200 201
	const char *mime_type = is.GetMimeType();
	return mime_type != nullptr && plugin.SupportsMimeType(mime_type);
202
}
203

204 205 206 207 208
gcc_pure
static bool
decoder_check_plugin_suffix(const DecoderPlugin &plugin, const char *suffix)
{
	assert(plugin.stream_decode != nullptr);
209

210
	return suffix != nullptr && plugin.SupportsSuffix(suffix);
211 212
}

213
gcc_pure
214
static bool
215
decoder_check_plugin(const DecoderPlugin &plugin, const InputStream &is,
216
		     const char *suffix)
217
{
218 219 220 221
	return plugin.stream_decode != nullptr &&
		(decoder_check_plugin_mime(plugin, is) ||
		 decoder_check_plugin_suffix(plugin, suffix));
}
222

223
static bool
224
decoder_run_stream_plugin(Decoder &decoder, InputStream &is,
225 226 227 228 229
			  const char *suffix,
			  const DecoderPlugin &plugin,
			  bool &tried_r)
{
	if (!decoder_check_plugin(plugin, is, suffix))
230 231
		return false;

232
	tried_r = true;
233
	return decoder_stream_decode(plugin, decoder, is);
234
}
235

236
static bool
237
decoder_run_stream_locked(Decoder &decoder, InputStream &is,
238 239
			  const char *uri, bool &tried_r)
{
240 241
	UriSuffixBuffer suffix_buffer;
	const char *const suffix = uri_get_suffix(uri, suffix_buffer);
242

243 244 245 246 247
	using namespace std::placeholders;
	const auto f = std::bind(decoder_run_stream_plugin,
				 std::ref(decoder), std::ref(is), suffix,
				 _1, std::ref(tried_r));
	return decoder_plugins_try(f);
248 249 250 251 252 253
}

/**
 * Try decoding a stream, using the fallback plugin.
 */
static bool
254
decoder_run_stream_fallback(Decoder &decoder, InputStream &is)
255
{
256
	const struct DecoderPlugin *plugin;
257 258

	plugin = decoder_plugin_from_name("mad");
259
	return plugin != nullptr && plugin->stream_decode != nullptr &&
260
		decoder_stream_decode(*plugin, decoder, is);
261 262 263 264 265 266
}

/**
 * Try decoding a stream.
 */
static bool
267
decoder_run_stream(Decoder &decoder, const char *uri)
268
{
269
	DecoderControl &dc = decoder.dc;
270
	InputStream *input_stream;
271 272
	bool success;

273
	dc.Unlock();
274

275
	input_stream = decoder_input_stream_open(dc, uri);
276
	if (input_stream == nullptr) {
277
		dc.Lock();
278 279 280
		return false;
	}

281
	dc.Lock();
282

283
	bool tried = false;
284
	success = dc.command == DecoderCommand::STOP ||
285 286
		decoder_run_stream_locked(decoder, *input_stream, uri,
					  tried) ||
287 288
		/* fallback to mp3: this is needed for bastard streams
		   that don't have a suffix or set the mimeType */
289
		(!tried &&
290
		 decoder_run_stream_fallback(decoder, *input_stream));
291

292
	dc.Unlock();
293
	delete input_stream;
294
	dc.Lock();
295 296

	return success;
297 298
}

299 300 301 302 303
/**
 * Attempt to load replay gain data, and pass it to
 * decoder_replay_gain().
 */
static void
304
decoder_load_replay_gain(Decoder &decoder, Path path_fs)
305
{
306
	ReplayGainInfo info;
307
	if (replay_gain_ape_read(path_fs, info))
308 309 310
		decoder_replay_gain(decoder, &info);
}

311
static bool
312
TryDecoderFile(Decoder &decoder, Path path_fs, const char *suffix,
313
	       const DecoderPlugin &plugin)
314
{
315 316 317
	if (!plugin.SupportsSuffix(suffix))
		return false;

318
	DecoderControl &dc = decoder.dc;
319

320 321
	if (plugin.file_decode != nullptr) {
		dc.Lock();
322

323
		if (decoder_file_decode(plugin, decoder, path_fs))
324
			return true;
325

326 327 328
		dc.Unlock();
	} else if (plugin.stream_decode != nullptr) {
		InputStream *input_stream =
329
			decoder_input_stream_open(dc, path_fs);
330 331
		if (input_stream == nullptr)
			return false;
332

333
		dc.Lock();
334

335 336
		bool success = decoder_stream_decode(plugin, decoder,
						     *input_stream);
337

338
		dc.Unlock();
339

340
		delete input_stream;
341

342
		if (success) {
343
			dc.Lock();
344 345 346
			return true;
		}
	}
347

348 349 350 351 352 353 354
	return false;
}

/**
 * Try decoding a file.
 */
static bool
355
decoder_run_file(Decoder &decoder, const char *uri_utf8, Path path_fs)
356
{
357
	const char *suffix = uri_get_suffix(uri_utf8);
358 359
	if (suffix == nullptr)
		return false;
360

361 362
	DecoderControl &dc = decoder.dc;
	dc.Unlock();
363

364
	decoder_load_replay_gain(decoder, path_fs);
365

366 367 368 369
	if (decoder_plugins_try([&decoder, path_fs,
				 suffix](const DecoderPlugin &plugin){
				return TryDecoderFile(decoder,
						      path_fs, suffix,
370 371 372
						      plugin);
			}))
		return true;
373

374
	dc.Lock();
375 376 377
	return false;
}

378
static void
379
decoder_run_song(DecoderControl &dc,
380
		 const DetachedSong &song, const char *uri, Path path_fs)
Avuton Olrich's avatar
Avuton Olrich committed
381
{
382
	Decoder decoder(dc, dc.start_time.IsPositive(),
383
			new Tag(song.GetTag()));
384
	int ret;
385

386
	dc.state = DecoderState::START;
387

388
	decoder_command_finished_locked(dc);
389

390 391
	ret = !path_fs.IsNull()
		? decoder_run_file(decoder, uri, path_fs)
392
		: decoder_run_stream(decoder, uri);
Warren Dukes's avatar
Warren Dukes committed
393

394
	dc.Unlock();
395

396
	/* flush the last chunk */
397

398
	if (decoder.chunk != nullptr)
399
		decoder.FlushChunk();
400

401
	dc.Lock();
402

403 404 405 406 407 408
	if (decoder.error.IsDefined()) {
		/* copy the Error from sruct Decoder to
		   DecoderControl */
		dc.state = DecoderState::ERROR;
		dc.error = std::move(decoder.error);
	} else if (ret)
409
		dc.state = DecoderState::STOP;
410
	else {
411
		dc.state = DecoderState::ERROR;
412

413
		const char *error_uri = song.GetURI();
414 415 416
		const std::string allocated = uri_remove_auth(error_uri);
		if (!allocated.empty())
			error_uri = allocated.c_str();
417

418
		dc.error.Format(decoder_domain,
419
				 "Failed to decode %s", error_uri);
420
	}
421

422
	dc.client_cond.signal();
423 424
}

425
static void
426
decoder_run(DecoderControl &dc)
427
{
428
	dc.ClearError();
429

430
	assert(dc.song != nullptr);
431
	const DetachedSong &song = *dc.song;
432

433
	const char *const uri_utf8 = song.GetRealURI();
434

435 436
	Path path_fs = Path::Null();
	AllocatedPath path_buffer = AllocatedPath::Null();
437 438
	if (PathTraitsUTF8::IsAbsolute(uri_utf8)) {
		path_buffer = AllocatedPath::FromUTF8(uri_utf8, dc.error);
439 440 441 442 443
		if (path_buffer.IsNull()) {
			dc.state = DecoderState::ERROR;
			decoder_command_finished_locked(dc);
			return;
		}
444

445
		path_fs = path_buffer;
446 447
	}

448
	decoder_run_song(dc, song, uri_utf8, path_fs);
449 450 451

}

452 453
static void
decoder_task(void *arg)
Avuton Olrich's avatar
Avuton Olrich committed
454
{
455
	DecoderControl &dc = *(DecoderControl *)arg;
456

457 458
	SetThreadName("decoder");

459
	dc.Lock();
460

461
	do {
462 463
		assert(dc.state == DecoderState::STOP ||
		       dc.state == DecoderState::ERROR);
464

465
		switch (dc.command) {
466
		case DecoderCommand::START:
467
			dc.CycleMixRamp();
468 469
			dc.replay_gain_prev_db = dc.replay_gain_db;
			dc.replay_gain_db = 0;
470

471 472
			decoder_run(dc);
			break;
473

474
		case DecoderCommand::SEEK:
475 476 477 478 479 480 481 482
			/* 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 */
			dc.pipe->Clear(*dc.buffer);

483
			decoder_run(dc);
484 485
			break;

486
		case DecoderCommand::STOP:
487
			decoder_command_finished_locked(dc);
488 489
			break;

490
		case DecoderCommand::NONE:
491
			dc.Wait();
492
			break;
Warren Dukes's avatar
Warren Dukes committed
493
		}
494
	} while (dc.command != DecoderCommand::NONE || !dc.quit);
495

496
	dc.Unlock();
497
}
Warren Dukes's avatar
Warren Dukes committed
498

499
void
500
decoder_thread_start(DecoderControl &dc)
501
{
502
	assert(!dc.thread.IsDefined());
503

504
	dc.quit = false;
505

506
	Error error;
507
	if (!dc.thread.Start(decoder_task, &dc, error))
508
		FatalError(error);
Warren Dukes's avatar
Warren Dukes committed
509
}