FingerprintCommands.cxx 8.24 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 * http://www.musicpd.org
 *
 * 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.
 *
 * 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.
 */

#include "config.h"
#include "FingerprintCommands.hxx"
#include "Request.hxx"
#include "LocateUri.hxx"
#include "lib/chromaprint/DecoderClient.hxx"
#include "decoder/DecoderAPI.hxx"
#include "decoder/DecoderList.hxx"
#include "storage/StorageInterface.hxx"
#include "client/Client.hxx"
#include "client/Response.hxx"
#include "client/ThreadBackgroundCommand.hxx"
#include "input/InputStream.hxx"
#include "input/LocalOpen.hxx"
#include "input/Handler.hxx"
#include "thread/Mutex.hxx"
#include "thread/Cond.hxx"
#include "system/Error.hxx"
#include "util/MimeType.hxx"
Max Kellermann's avatar
Max Kellermann committed
38
#include "util/UriExtract.hxx"
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

class GetChromaprintCommand final
	: public ThreadBackgroundCommand, ChromaprintDecoderClient, InputStreamHandler
{
	Mutex mutex;
	Cond cond;

	const std::string uri;
	const AllocatedPath path;

	bool cancel = false;

public:
	GetChromaprintCommand(Client &_client, std::string &&_uri,
			      AllocatedPath &&_path)  noexcept
		:ThreadBackgroundCommand(_client),
		 uri(std::move(_uri)), path(std::move(_path))
	{
	}

protected:
	void Run() override;

	void SendResponse(Response &r) noexcept override {
		r.Format("chromaprint: %s\n",
			 GetFingerprint().c_str());
	}

	void CancelThread() noexcept override {
		const std::lock_guard<Mutex> lock(mutex);
		cancel = true;
70
		cond.notify_one();
71 72 73 74
	}

private:
	void DecodeStream(InputStream &is, const DecoderPlugin &plugin);
75
	bool DecodeStream(InputStream &is, std::string_view suffix,
76 77
			  const DecoderPlugin &plugin);
	void DecodeStream(InputStream &is);
78 79 80
	bool DecodeContainer(std::string_view suffix, const DecoderPlugin &plugin);
	bool DecodeContainer(std::string_view suffix);
	bool DecodeFile(std::string_view suffix, InputStream &is,
81 82 83 84 85
			const DecoderPlugin &plugin);
	void DecodeFile();

	/* virtual methods from class DecoderClient */
	InputStreamPtr OpenUri(const char *uri) override;
86 87
	size_t Read(InputStream &is,
		    void *buffer, size_t length) noexcept override;
88 89 90

	/* virtual methods from class InputStreamHandler */
	void OnInputStreamReady() noexcept override {
91
		cond.notify_one();
92 93 94
	}

	void OnInputStreamAvailable() noexcept override {
95
		cond.notify_one();
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
	}
};

inline void
GetChromaprintCommand::DecodeStream(InputStream &input_stream,
				    const DecoderPlugin &plugin)
{
	assert(plugin.stream_decode != nullptr);
	assert(input_stream.IsReady());

	if (cancel)
		throw StopDecoder();

	/* rewind the stream, so each plugin gets a fresh start */
	try {
111
		input_stream.LockRewind();
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	} catch (...) {
	}

	plugin.StreamDecode(*this, input_stream);
}

gcc_pure
static bool
decoder_check_plugin_mime(const DecoderPlugin &plugin,
			  const InputStream &is) noexcept
{
	assert(plugin.stream_decode != nullptr);

	const char *mime_type = is.GetMimeType();
	return mime_type != nullptr &&
127
		plugin.SupportsMimeType(GetMimeTypeBase(mime_type));
128 129 130 131 132
}

gcc_pure
static bool
decoder_check_plugin_suffix(const DecoderPlugin &plugin,
133
			    std::string_view suffix) noexcept
134 135 136
{
	assert(plugin.stream_decode != nullptr);

137
	return !suffix.empty() && plugin.SupportsSuffix(suffix);
138 139 140 141 142
}

gcc_pure
static bool
decoder_check_plugin(const DecoderPlugin &plugin, const InputStream &is,
143
		     std::string_view suffix) noexcept
144 145 146 147 148 149 150 151
{
	return plugin.stream_decode != nullptr &&
		(decoder_check_plugin_mime(plugin, is) ||
		 decoder_check_plugin_suffix(plugin, suffix));
}

inline bool
GetChromaprintCommand::DecodeStream(InputStream &is,
152
				    std::string_view suffix,
153 154 155 156 157 158 159 160 161 162 163 164 165 166
				    const DecoderPlugin &plugin)
{
	if (!decoder_check_plugin(plugin, is, suffix))
		return false;

	ChromaprintDecoderClient::Reset();

	DecodeStream(is, plugin);
	return true;
}

inline void
GetChromaprintCommand::DecodeStream(InputStream &is)
{
167
	const auto suffix = uri_get_suffix(uri);
168 169 170 171 172 173 174

	decoder_plugins_try([this, &is, suffix](const DecoderPlugin &plugin){
		return DecodeStream(is, suffix, plugin);
	});
}

inline bool
175
GetChromaprintCommand::DecodeContainer(std::string_view suffix,
176 177 178 179 180 181 182 183 184 185 186 187 188 189
				       const DecoderPlugin &plugin)
{
	if (plugin.container_scan == nullptr ||
	    plugin.file_decode == nullptr ||
	    !plugin.SupportsSuffix(suffix))
		return false;

	ChromaprintDecoderClient::Reset();

	plugin.FileDecode(*this, path);
	return IsReady();
}

inline bool
190
GetChromaprintCommand::DecodeContainer(std::string_view suffix)
191 192 193 194 195 196 197
{
	return decoder_plugins_try([this, suffix](const DecoderPlugin &plugin){
		return DecodeContainer(suffix, plugin);
	});
}

inline bool
198
GetChromaprintCommand::DecodeFile(std::string_view suffix, InputStream &is,
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
				  const DecoderPlugin &plugin)
{
	if (!plugin.SupportsSuffix(suffix))
		return false;

	{
		const std::lock_guard<Mutex> protect(mutex);
		if (cancel)
			throw StopDecoder();
	}

	ChromaprintDecoderClient::Reset();

	if (plugin.file_decode != nullptr) {
		plugin.FileDecode(*this, path);
		return IsReady();
	} else if (plugin.stream_decode != nullptr) {
		plugin.StreamDecode(*this, is);
		return IsReady();
	} else
		return false;
}

inline void
GetChromaprintCommand::DecodeFile()
{
225
	const auto suffix = uri_get_suffix(uri);
226
	if (suffix.empty())
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
		return;

	InputStreamPtr input_stream;

	try {
		input_stream = OpenLocalInputStream(path, mutex);
	} catch (const std::system_error &e) {
		if (IsPathNotFound(e) &&
		    /* ENOTDIR means this may be a path inside a
		       "container" file */
		    DecodeContainer(suffix))
			return;

		throw;
	}

	assert(input_stream);

	auto &is = *input_stream;
	decoder_plugins_try([this, suffix, &is](const DecoderPlugin &plugin){
		return DecodeFile(suffix, is, plugin);
	});
}

void
GetChromaprintCommand::Run()
try {
	if (!path.IsNull())
		DecodeFile();
	else
		DecodeStream(*OpenUri(uri.c_str()));

	ChromaprintDecoderClient::Finish();
} catch (StopDecoder) {
}

InputStreamPtr
GetChromaprintCommand::OpenUri(const char *uri2)
{
	if (cancel)
		throw StopDecoder();

	auto is = InputStream::Open(uri2, mutex);
	is->SetHandler(this);

272
	std::unique_lock<Mutex> lock(mutex);
273 274 275 276 277 278 279 280 281 282
	while (true) {
		if (cancel)
			throw StopDecoder();

		is->Update();
		if (is->IsReady()) {
			is->Check();
			return is;
		}

283
		cond.wait(lock);
284 285 286 287
	}
}

size_t
288 289
GetChromaprintCommand::Read(InputStream &is,
			    void *buffer, size_t length) noexcept
290 291 292 293 294 295 296
{
	/* overriding ChromaprintDecoderClient's implementation to
	   make it cancellable */

	if (length == 0)
		return 0;

297
	std::unique_lock<Mutex> lock(mutex);
298 299 300 301 302 303 304 305

	while (true) {
		if (cancel)
			return 0;

		if (is.IsAvailable())
			break;

306
		cond.wait(lock);
307 308
	}

309 310 311 312 313 314
	try {
		return is.Read(lock, buffer, length);
	} catch (...) {
		ChromaprintDecoderClient::error = std::current_exception();
		return 0;
	}
315 316 317 318 319 320 321
}

CommandResult
handle_getfingerprint(Client &client, Request args, Response &)
{
	const char *_uri = args.front();

322
	auto lu = LocateUri(UriPluginKind::INPUT, _uri, &client
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
#ifdef ENABLE_DATABASE
			    , nullptr
#endif
			    );

	std::string uri = lu.canonical_uri;

	switch (lu.type) {
	case LocatedUri::Type::ABSOLUTE:
		break;

	case LocatedUri::Type::PATH:
		break;

	case LocatedUri::Type::RELATIVE:
#ifdef ENABLE_DATABASE
		{
			const auto *storage = client.GetStorage();
			if (storage == nullptr)
				throw ProtocolError(ACK_ERROR_NO_EXIST, "No database");

			lu.path = storage->MapFS(lu.canonical_uri);
			if (lu.path.IsNull()) {
				uri = storage->MapUTF8(lu.canonical_uri);
347
				if (!uri_has_scheme(uri.c_str()))
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
					throw ProtocolError(ACK_ERROR_NO_EXIST, "No such song");
			}
		}
#else
		throw ProtocolError(ACK_ERROR_NO_EXIST, "No database");
#endif
	}


	auto cmd = std::make_unique<GetChromaprintCommand>(client,
							   std::move(uri),
							   std::move(lu.path));
	cmd->Start();
	client.SetBackgroundCommand(std::move(cmd));
	return CommandResult::BACKGROUND;
}