diff options
Diffstat (limited to 'src/input/plugins')
22 files changed, 3153 insertions, 0 deletions
diff --git a/src/input/plugins/AlsaInputPlugin.cxx b/src/input/plugins/AlsaInputPlugin.cxx new file mode 100644 index 000000000..82b96f7df --- /dev/null +++ b/src/input/plugins/AlsaInputPlugin.cxx @@ -0,0 +1,383 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +/* + * ALSA code based on an example by Paul Davis released under GPL here: + * http://equalarea.com/paul/alsa-audio.html + * and one by Matthias Nagorni, also GPL, here: + * http://alsamodular.sourceforge.net/alsa_programming_howto.html + */ + +#include "config.h" +#include "AlsaInputPlugin.hxx" +#include "../InputPlugin.hxx" +#include "../InputStream.hxx" +#include "util/Domain.hxx" +#include "util/Error.hxx" +#include "util/StringUtil.hxx" +#include "util/ReusableArray.hxx" + +#include "Log.hxx" +#include "event/MultiSocketMonitor.hxx" +#include "event/DeferredMonitor.hxx" +#include "event/Call.hxx" +#include "thread/Mutex.hxx" +#include "thread/Cond.hxx" +#include "IOThread.hxx" + +#include <alsa/asoundlib.h> + +#include <assert.h> +#include <string.h> + +static constexpr Domain alsa_input_domain("alsa"); + +static constexpr const char *default_device = "hw:0,0"; + +// the following defaults are because the PcmDecoderPlugin forces CD format +static constexpr snd_pcm_format_t default_format = SND_PCM_FORMAT_S16; +static constexpr int default_channels = 2; // stereo +static constexpr unsigned int default_rate = 44100; // cd quality + +/** + * This value should be the same as the read buffer size defined in + * PcmDecoderPlugin.cxx:pcm_stream_decode(). + * We use it to calculate how many audio frames to buffer in the alsa driver + * before reading from the device. snd_pcm_readi() blocks until that many + * frames are ready. + */ +static constexpr size_t read_buffer_size = 4096; + +class AlsaInputStream final + : public InputStream, + MultiSocketMonitor, DeferredMonitor { + snd_pcm_t *capture_handle; + size_t frame_size; + int frames_to_read; + bool eof; + + /** + * Is somebody waiting for data? This is set by method + * Available(). + */ + std::atomic_bool waiting; + + ReusableArray<pollfd> pfd_buffer; + +public: + AlsaInputStream(EventLoop &loop, + const char *_uri, Mutex &_mutex, Cond &_cond, + snd_pcm_t *_handle, int _frame_size) + :InputStream(_uri, _mutex, _cond), + MultiSocketMonitor(loop), + DeferredMonitor(loop), + capture_handle(_handle), + frame_size(_frame_size), + eof(false) + { + assert(_uri != nullptr); + assert(_handle != nullptr); + + /* this mime type forces use of the PcmDecoderPlugin. + Needs to be generalised when/if that decoder is + updated to support other audio formats */ + SetMimeType("audio/x-mpd-cdda-pcm"); + InputStream::SetReady(); + + frames_to_read = read_buffer_size / frame_size; + + snd_pcm_start(capture_handle); + + DeferredMonitor::Schedule(); + } + + ~AlsaInputStream() { + snd_pcm_close(capture_handle); + } + + using DeferredMonitor::GetEventLoop; + + static InputStream *Create(const char *uri, Mutex &mutex, Cond &cond, + Error &error); + + /* virtual methods from InputStream */ + + bool IsEOF() override { + return eof; + } + + bool IsAvailable() override { + if (snd_pcm_avail(capture_handle) > frames_to_read) + return true; + + if (!waiting.exchange(true)) + SafeInvalidateSockets(); + + return false; + } + + size_t Read(void *ptr, size_t size, Error &error) override; + +private: + static snd_pcm_t *OpenDevice(const char *device, int rate, + snd_pcm_format_t format, int channels, + Error &error); + + int Recover(int err); + + void SafeInvalidateSockets() { + DeferredMonitor::Schedule(); + } + + virtual void RunDeferred() override { + InvalidateSockets(); + } + + virtual int PrepareSockets() override; + virtual void DispatchSockets() override; +}; + +inline InputStream * +AlsaInputStream::Create(const char *uri, Mutex &mutex, Cond &cond, + Error &error) +{ + const char *const scheme = "alsa://"; + if (!StringStartsWith(uri, scheme)) + return nullptr; + + const char *device = uri + strlen(scheme); + if (strlen(device) == 0) + device = default_device; + + /* placeholders - eventually user-requested audio format will + be passed via the URI. For now we just force the + defaults */ + int rate = default_rate; + snd_pcm_format_t format = default_format; + int channels = default_channels; + + snd_pcm_t *handle = OpenDevice(device, rate, format, channels, + error); + if (handle == nullptr) + return nullptr; + + int frame_size = snd_pcm_format_width(format) / 8 * channels; + return new AlsaInputStream(io_thread_get(), + uri, mutex, cond, + handle, frame_size); +} + +size_t +AlsaInputStream::Read(void *ptr, size_t read_size, Error &error) +{ + assert(ptr != nullptr); + + int num_frames = read_size / frame_size; + int ret; + while ((ret = snd_pcm_readi(capture_handle, ptr, num_frames)) < 0) { + if (Recover(ret) < 0) { + eof = true; + error.Format(alsa_input_domain, + "PCM error - stream aborted"); + return 0; + } + } + + size_t nbytes = ret * frame_size; + offset += nbytes; + return nbytes; +} + +int +AlsaInputStream::PrepareSockets() +{ + if (!waiting) { + ClearSocketList(); + return -1; + } + + int count = snd_pcm_poll_descriptors_count(capture_handle); + if (count < 0) { + ClearSocketList(); + return -1; + } + + struct pollfd *pfds = pfd_buffer.Get(count); + + count = snd_pcm_poll_descriptors(capture_handle, pfds, count); + if (count < 0) + count = 0; + + ReplaceSocketList(pfds, count); + return -1; +} + +void +AlsaInputStream::DispatchSockets() +{ + waiting = false; + + const ScopeLock protect(mutex); + /* wake up the thread that is waiting for more data */ + cond.broadcast(); +} + +inline int +AlsaInputStream::Recover(int err) +{ + switch(err) { + case -EPIPE: + LogDebug(alsa_input_domain, "Buffer Overrun"); + // drop through + case -ESTRPIPE: + case -EINTR: + err = snd_pcm_recover(capture_handle, err, 1); + break; + default: + // something broken somewhere, give up + err = -1; + } + return err; +} + +inline snd_pcm_t * +AlsaInputStream::OpenDevice(const char *device, + int rate, snd_pcm_format_t format, int channels, + Error &error) +{ + snd_pcm_t *capture_handle; + int err; + if ((err = snd_pcm_open(&capture_handle, device, + SND_PCM_STREAM_CAPTURE, 0)) < 0) { + error.Format(alsa_input_domain, "Failed to open device: %s (%s)", device, snd_strerror(err)); + return nullptr; + } + + snd_pcm_hw_params_t *hw_params; + if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) { + error.Format(alsa_input_domain, "Cannot allocate hardware parameter structure (%s)", snd_strerror(err)); + snd_pcm_close(capture_handle); + return nullptr; + } + + if ((err = snd_pcm_hw_params_any(capture_handle, hw_params)) < 0) { + error.Format(alsa_input_domain, "Cannot initialize hardware parameter structure (%s)", snd_strerror(err)); + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + return nullptr; + } + + if ((err = snd_pcm_hw_params_set_access(capture_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { + error.Format(alsa_input_domain, "Cannot set access type (%s)", snd_strerror (err)); + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + return nullptr; + } + + if ((err = snd_pcm_hw_params_set_format(capture_handle, hw_params, format)) < 0) { + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + error.Format(alsa_input_domain, "Cannot set sample format (%s)", snd_strerror (err)); + return nullptr; + } + + if ((err = snd_pcm_hw_params_set_channels(capture_handle, hw_params, channels)) < 0) { + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + error.Format(alsa_input_domain, "Cannot set channels (%s)", snd_strerror (err)); + return nullptr; + } + + if ((err = snd_pcm_hw_params_set_rate(capture_handle, hw_params, rate, 0)) < 0) { + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + error.Format(alsa_input_domain, "Cannot set sample rate (%s)", snd_strerror (err)); + return nullptr; + } + + /* period needs to be big enough so that poll() doesn't fire too often, + * but small enough that buffer overruns don't occur if Read() is not + * invoked often enough. + * the calculation here is empirical; however all measurements were + * done using 44100:16:2. When we extend this plugin to support + * other audio formats then this may need to be revisited */ + snd_pcm_uframes_t period = read_buffer_size * 2; + int direction = -1; + if ((err = snd_pcm_hw_params_set_period_size_near(capture_handle, hw_params, + &period, &direction)) < 0) { + error.Format(alsa_input_domain, "Cannot set period size (%s)", + snd_strerror(err)); + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + return nullptr; + } + + if ((err = snd_pcm_hw_params(capture_handle, hw_params)) < 0) { + error.Format(alsa_input_domain, "Cannot set parameters (%s)", + snd_strerror(err)); + snd_pcm_hw_params_free(hw_params); + snd_pcm_close(capture_handle); + return nullptr; + } + + snd_pcm_hw_params_free (hw_params); + + snd_pcm_sw_params_t *sw_params; + + snd_pcm_sw_params_malloc(&sw_params); + snd_pcm_sw_params_current(capture_handle, sw_params); + + if ((err = snd_pcm_sw_params_set_start_threshold(capture_handle, sw_params, + period)) < 0) { + error.Format(alsa_input_domain, + "unable to set start threshold (%s)", snd_strerror(err)); + snd_pcm_sw_params_free(sw_params); + snd_pcm_close(capture_handle); + return nullptr; + } + + if ((err = snd_pcm_sw_params(capture_handle, sw_params)) < 0) { + error.Format(alsa_input_domain, + "unable to install sw params (%s)", snd_strerror(err)); + snd_pcm_sw_params_free(sw_params); + snd_pcm_close(capture_handle); + return nullptr; + } + + snd_pcm_sw_params_free(sw_params); + + snd_pcm_prepare(capture_handle); + + return capture_handle; +} + +/*######################### Plugin Functions ##############################*/ + +static InputStream * +alsa_input_open(const char *uri, Mutex &mutex, Cond &cond, Error &error) +{ + return AlsaInputStream::Create(uri, mutex, cond, error); +} + +const struct InputPlugin input_plugin_alsa = { + "alsa", + nullptr, + nullptr, + alsa_input_open, +}; diff --git a/src/input/plugins/AlsaInputPlugin.hxx b/src/input/plugins/AlsaInputPlugin.hxx new file mode 100644 index 000000000..dddf7dfd7 --- /dev/null +++ b/src/input/plugins/AlsaInputPlugin.hxx @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_ALSA_INPUT_PLUGIN_HXX +#define MPD_ALSA_INPUT_PLUGIN_HXX + +#include "../InputPlugin.hxx" + +extern const struct InputPlugin input_plugin_alsa; + + +#endif diff --git a/src/input/plugins/ArchiveInputPlugin.cxx b/src/input/plugins/ArchiveInputPlugin.cxx new file mode 100644 index 000000000..b51dc6835 --- /dev/null +++ b/src/input/plugins/ArchiveInputPlugin.cxx @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "ArchiveInputPlugin.hxx" +#include "archive/ArchiveDomain.hxx" +#include "archive/ArchiveLookup.hxx" +#include "archive/ArchiveList.hxx" +#include "archive/ArchivePlugin.hxx" +#include "archive/ArchiveFile.hxx" +#include "../InputPlugin.hxx" +#include "fs/Traits.hxx" +#include "fs/Path.hxx" +#include "util/Alloc.hxx" +#include "Log.hxx" + +#include <stdlib.h> + +/** + * select correct archive plugin to handle the input stream + * may allow stacking of archive plugins. for example for handling + * tar.gz a gzip handler opens file (through inputfile stream) + * then it opens a tar handler and sets gzip inputstream as + * parent_stream so tar plugin fetches file data from gzip + * plugin and gzip fetches file from disk + */ +static InputStream * +input_archive_open(const char *pathname, + Mutex &mutex, Cond &cond, + Error &error) +{ + const ArchivePlugin *arplug; + InputStream *is; + + if (!PathTraitsFS::IsAbsolute(pathname)) + return nullptr; + + char *pname = strdup(pathname); + // archive_lookup will modify pname when true is returned + const char *archive, *filename, *suffix; + if (!archive_lookup(pname, &archive, &filename, &suffix)) { + FormatDebug(archive_domain, + "not an archive, lookup %s failed", pname); + free(pname); + return nullptr; + } + + //check which archive plugin to use (by ext) + arplug = archive_plugin_from_suffix(suffix); + if (!arplug) { + FormatWarning(archive_domain, + "can't handle archive %s", archive); + free(pname); + return nullptr; + } + + auto file = archive_file_open(arplug, Path::FromFS(archive), error); + if (file == nullptr) { + free(pname); + return nullptr; + } + + //setup fileops + is = file->OpenStream(filename, mutex, cond, error); + free(pname); + file->Close(); + + return is; +} + +const InputPlugin input_plugin_archive = { + "archive", + nullptr, + nullptr, + input_archive_open, +}; diff --git a/src/input/plugins/ArchiveInputPlugin.hxx b/src/input/plugins/ArchiveInputPlugin.hxx new file mode 100644 index 000000000..024723726 --- /dev/null +++ b/src/input/plugins/ArchiveInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_INPUT_ARCHIVE_HXX +#define MPD_INPUT_ARCHIVE_HXX + +extern const struct InputPlugin input_plugin_archive; + +#endif diff --git a/src/input/plugins/CdioParanoiaInputPlugin.cxx b/src/input/plugins/CdioParanoiaInputPlugin.cxx new file mode 100644 index 000000000..6f1ea976a --- /dev/null +++ b/src/input/plugins/CdioParanoiaInputPlugin.cxx @@ -0,0 +1,375 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +/** + * CD-Audio handling (requires libcdio_paranoia) + */ + +#include "config.h" +#include "CdioParanoiaInputPlugin.hxx" +#include "../InputStream.hxx" +#include "../InputPlugin.hxx" +#include "util/StringUtil.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" +#include "system/ByteOrder.hxx" +#include "fs/AllocatedPath.hxx" +#include "Log.hxx" +#include "config/ConfigData.hxx" +#include "config/ConfigError.hxx" + +#include <stdio.h> +#include <stdint.h> +#include <stddef.h> +#include <string.h> +#include <stdlib.h> +#include <glib.h> +#include <assert.h> + +#ifdef HAVE_CDIO_PARANOIA_PARANOIA_H +#include <cdio/paranoia/paranoia.h> +#else +#include <cdio/paranoia.h> +#endif + +#include <cdio/cd_types.h> + +class CdioParanoiaInputStream final : public InputStream { + cdrom_drive_t *const drv; + CdIo_t *const cdio; + cdrom_paranoia_t *const para; + + const lsn_t lsn_from, lsn_to; + int lsn_relofs; + + char buffer[CDIO_CD_FRAMESIZE_RAW]; + int buffer_lsn; + + public: + CdioParanoiaInputStream(const char *_uri, Mutex &_mutex, Cond &_cond, + cdrom_drive_t *_drv, CdIo_t *_cdio, + bool reverse_endian, + lsn_t _lsn_from, lsn_t _lsn_to) + :InputStream(_uri, _mutex, _cond), + drv(_drv), cdio(_cdio), para(cdio_paranoia_init(drv)), + lsn_from(_lsn_from), lsn_to(_lsn_to), + lsn_relofs(0), + buffer_lsn(-1) + { + /* Set reading mode for full paranoia, but allow + skipping sectors. */ + paranoia_modeset(para, + PARANOIA_MODE_FULL^PARANOIA_MODE_NEVERSKIP); + + /* seek to beginning of the track */ + cdio_paranoia_seek(para, lsn_from, SEEK_SET); + + seekable = true; + size = (lsn_to - lsn_from + 1) * CDIO_CD_FRAMESIZE_RAW; + + /* hack to make MPD select the "pcm" decoder plugin */ + SetMimeType(reverse_endian + ? "audio/x-mpd-cdda-pcm-reverse" + : "audio/x-mpd-cdda-pcm"); + SetReady(); + } + + ~CdioParanoiaInputStream() { + cdio_paranoia_free(para); + cdio_cddap_close_no_free_cdio(drv); + cdio_destroy(cdio); + } + + /* virtual methods from InputStream */ + bool IsEOF() override; + size_t Read(void *ptr, size_t size, Error &error) override; + bool Seek(offset_type offset, Error &error) override; +}; + +static constexpr Domain cdio_domain("cdio"); + +static bool default_reverse_endian; + +static InputPlugin::InitResult +input_cdio_init(const config_param ¶m, Error &error) +{ + const char *value = param.GetBlockValue("default_byte_order"); + if (value != nullptr) { + if (strcmp(value, "little_endian") == 0) + default_reverse_endian = IsBigEndian(); + else if (strcmp(value, "big_endian") == 0) + default_reverse_endian = IsLittleEndian(); + else { + error.Format(config_domain, 0, + "Unrecognized 'default_byte_order' setting: %s", + value); + return InputPlugin::InitResult::ERROR; + } + } + + return InputPlugin::InitResult::SUCCESS; +} + +struct cdio_uri { + char device[64]; + int track; +}; + +static bool +parse_cdio_uri(struct cdio_uri *dest, const char *src, Error &error) +{ + if (!StringStartsWith(src, "cdda://")) + return false; + + src += 7; + + if (*src == 0) { + /* play the whole CD in the default drive */ + dest->device[0] = 0; + dest->track = -1; + return true; + } + + const char *slash = strrchr(src, '/'); + if (slash == nullptr) { + /* play the whole CD in the specified drive */ + g_strlcpy(dest->device, src, sizeof(dest->device)); + dest->track = -1; + return true; + } + + size_t device_length = slash - src; + if (device_length >= sizeof(dest->device)) + device_length = sizeof(dest->device) - 1; + + memcpy(dest->device, src, device_length); + dest->device[device_length] = 0; + + const char *track = slash + 1; + + char *endptr; + dest->track = strtoul(track, &endptr, 10); + if (*endptr != 0) { + error.Set(cdio_domain, "Malformed track number"); + return false; + } + + if (endptr == track) + /* play the whole CD */ + dest->track = -1; + + return true; +} + +static AllocatedPath +cdio_detect_device(void) +{ + char **devices = cdio_get_devices_with_cap(nullptr, CDIO_FS_AUDIO, + false); + if (devices == nullptr) + return AllocatedPath::Null(); + + AllocatedPath path = AllocatedPath::FromFS(devices[0]); + cdio_free_device_list(devices); + return path; +} + +static InputStream * +input_cdio_open(const char *uri, + Mutex &mutex, Cond &cond, + Error &error) +{ + struct cdio_uri parsed_uri; + if (!parse_cdio_uri(&parsed_uri, uri, error)) + return nullptr; + + /* get list of CD's supporting CD-DA */ + const AllocatedPath device = parsed_uri.device[0] != 0 + ? AllocatedPath::FromFS(parsed_uri.device) + : cdio_detect_device(); + if (device.IsNull()) { + error.Set(cdio_domain, + "Unable find or access a CD-ROM drive with an audio CD in it."); + return nullptr; + } + + /* Found such a CD-ROM with a CD-DA loaded. Use the first drive in the list. */ + const auto cdio = cdio_open(device.c_str(), DRIVER_UNKNOWN); + if (cdio == nullptr) { + error.Set(cdio_domain, "Failed to open CD drive"); + return nullptr; + } + + const auto drv = cdio_cddap_identify_cdio(cdio, 1, nullptr); + if (drv == nullptr) { + error.Set(cdio_domain, "Unable to identify audio CD disc."); + cdio_destroy(cdio); + return nullptr; + } + + cdda_verbose_set(drv, CDDA_MESSAGE_FORGETIT, CDDA_MESSAGE_FORGETIT); + + if (0 != cdio_cddap_open(drv)) { + cdio_cddap_close_no_free_cdio(drv); + cdio_destroy(cdio); + error.Set(cdio_domain, "Unable to open disc."); + return nullptr; + } + + bool reverse_endian; + switch (data_bigendianp(drv)) { + case -1: + LogDebug(cdio_domain, "drive returns unknown audio data"); + reverse_endian = default_reverse_endian; + break; + + case 0: + LogDebug(cdio_domain, "drive returns audio data Little Endian"); + reverse_endian = IsBigEndian(); + break; + + case 1: + LogDebug(cdio_domain, "drive returns audio data Big Endian"); + reverse_endian = IsLittleEndian(); + break; + + default: + error.Format(cdio_domain, "Drive returns unknown data type %d", + data_bigendianp(drv)); + cdio_cddap_close_no_free_cdio(drv); + cdio_destroy(cdio); + return nullptr; + } + + lsn_t lsn_from, lsn_to; + if (parsed_uri.track >= 0) { + lsn_from = cdio_get_track_lsn(cdio, parsed_uri.track); + lsn_to = cdio_get_track_last_lsn(cdio, parsed_uri.track); + } else { + lsn_from = 0; + lsn_to = cdio_get_disc_last_lsn(cdio); + } + + return new CdioParanoiaInputStream(uri, mutex, cond, + drv, cdio, reverse_endian, + lsn_from, lsn_to); +} + +bool +CdioParanoiaInputStream::Seek(offset_type new_offset, Error &error) +{ + if (new_offset < 0 || new_offset > size) { + error.Format(cdio_domain, "Invalid offset to seek %ld (%ld)", + (long int)new_offset, (long int)size); + return false; + } + + /* simple case */ + if (new_offset == offset) + return true; + + /* calculate current LSN */ + lsn_relofs = new_offset / CDIO_CD_FRAMESIZE_RAW; + offset = new_offset; + + cdio_paranoia_seek(para, lsn_from + lsn_relofs, SEEK_SET); + + return true; +} + +size_t +CdioParanoiaInputStream::Read(void *ptr, size_t length, Error &error) +{ + size_t nbytes = 0; + int diff; + size_t len, maxwrite; + int16_t *rbuf; + char *s_err, *s_mess; + char *wptr = (char *) ptr; + + while (length > 0) { + + + /* end of track ? */ + if (lsn_from + lsn_relofs > lsn_to) + break; + + //current sector was changed ? + if (lsn_relofs != buffer_lsn) { + rbuf = cdio_paranoia_read(para, nullptr); + + s_err = cdda_errors(drv); + if (s_err) { + FormatError(cdio_domain, + "paranoia_read: %s", s_err); + free(s_err); + } + s_mess = cdda_messages(drv); + if (s_mess) { + free(s_mess); + } + if (!rbuf) { + error.Set(cdio_domain, + "paranoia read error. Stopping."); + return 0; + } + //store current buffer + memcpy(buffer, rbuf, CDIO_CD_FRAMESIZE_RAW); + buffer_lsn = lsn_relofs; + } else { + //use cached sector + rbuf = (int16_t *)buffer; + } + + //correct offset + diff = offset - lsn_relofs * CDIO_CD_FRAMESIZE_RAW; + + assert(diff >= 0 && diff < CDIO_CD_FRAMESIZE_RAW); + + maxwrite = CDIO_CD_FRAMESIZE_RAW - diff; //# of bytes pending in current buffer + len = (length < maxwrite? length : maxwrite); + + //skip diff bytes from this lsn + memcpy(wptr, ((char*)rbuf) + diff, len); + //update pointer + wptr += len; + nbytes += len; + + //update offset + offset += len; + lsn_relofs = offset / CDIO_CD_FRAMESIZE_RAW; + //update length + length -= len; + } + + return nbytes; +} + +bool +CdioParanoiaInputStream::IsEOF() +{ + return lsn_from + lsn_relofs > lsn_to; +} + +const InputPlugin input_plugin_cdio_paranoia = { + "cdio_paranoia", + input_cdio_init, + nullptr, + input_cdio_open, +}; diff --git a/src/input/plugins/CdioParanoiaInputPlugin.hxx b/src/input/plugins/CdioParanoiaInputPlugin.hxx new file mode 100644 index 000000000..e2804e8c7 --- /dev/null +++ b/src/input/plugins/CdioParanoiaInputPlugin.hxx @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_CDIO_PARANOIA_INPUT_PLUGIN_HXX +#define MPD_CDIO_PARANOIA_INPUT_PLUGIN_HXX + +/** + * An input plugin based on libcdio_paranoia library. + */ +extern const struct InputPlugin input_plugin_cdio_paranoia; + +#endif diff --git a/src/input/plugins/CurlInputPlugin.cxx b/src/input/plugins/CurlInputPlugin.cxx new file mode 100644 index 000000000..4d7671cc2 --- /dev/null +++ b/src/input/plugins/CurlInputPlugin.cxx @@ -0,0 +1,848 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "CurlInputPlugin.hxx" +#include "../AsyncInputStream.hxx" +#include "../IcyInputStream.hxx" +#include "../InputPlugin.hxx" +#include "config/ConfigGlobal.hxx" +#include "config/ConfigData.hxx" +#include "tag/Tag.hxx" +#include "tag/TagBuilder.hxx" +#include "event/SocketMonitor.hxx" +#include "event/TimeoutMonitor.hxx" +#include "event/Call.hxx" +#include "IOThread.hxx" +#include "util/ASCII.hxx" +#include "util/CharUtil.hxx" +#include "util/NumberParser.hxx" +#include "util/CircularBuffer.hxx" +#include "util/HugeAllocator.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" +#include "Log.hxx" + +#include <assert.h> +#include <string.h> + +#include <curl/curl.h> + +#if LIBCURL_VERSION_NUM < 0x071200 +#error libcurl is too old +#endif + +/** + * Do not buffer more than this number of bytes. It should be a + * reasonable limit that doesn't make low-end machines suffer too + * much, but doesn't cause stuttering on high-latency lines. + */ +static const size_t CURL_MAX_BUFFERED = 512 * 1024; + +/** + * Resume the stream at this number of bytes after it has been paused. + */ +static const size_t CURL_RESUME_AT = 384 * 1024; + +struct CurlInputStream final : public AsyncInputStream { + /* some buffers which were passed to libcurl, which we have + too free */ + char range[32]; + struct curl_slist *request_headers; + + /** the curl handles */ + CURL *easy; + + /** error message provided by libcurl */ + char error_buffer[CURL_ERROR_SIZE]; + + /** parser for icy-metadata */ + IcyInputStream *icy; + + CurlInputStream(const char *_url, Mutex &_mutex, Cond &_cond, + void *_buffer) + :AsyncInputStream(_url, _mutex, _cond, + _buffer, CURL_MAX_BUFFERED, + CURL_RESUME_AT), + request_headers(nullptr), + icy(new IcyInputStream(this)) {} + + ~CurlInputStream(); + + CurlInputStream(const CurlInputStream &) = delete; + CurlInputStream &operator=(const CurlInputStream &) = delete; + + static InputStream *Open(const char *url, Mutex &mutex, Cond &cond, + Error &error); + + bool InitEasy(Error &error); + + /** + * Frees the current "libcurl easy" handle, and everything + * associated with it. + * + * Runs in the I/O thread. + */ + void FreeEasy(); + + /** + * Frees the current "libcurl easy" handle, and everything associated + * with it. + * + * The mutex must not be locked. + */ + void FreeEasyIndirect(); + + void HeaderReceived(const char *name, std::string &&value); + + size_t DataReceived(const void *ptr, size_t size); + + /** + * A HTTP request is finished. + * + * Runs in the I/O thread. The caller must not hold locks. + */ + void RequestDone(CURLcode result, long status); + + /* virtual methods from AsyncInputStream */ + virtual void DoResume() override; + virtual void DoSeek(offset_type new_offset) override; +}; + +class CurlMulti; + +/** + * Monitor for one socket created by CURL. + */ +class CurlSocket final : SocketMonitor { + CurlMulti &multi; + +public: + CurlSocket(CurlMulti &_multi, EventLoop &_loop, int _fd) + :SocketMonitor(_fd, _loop), multi(_multi) {} + + ~CurlSocket() { + /* TODO: sometimes, CURL uses CURL_POLL_REMOVE after + closing the socket, and sometimes, it uses + CURL_POLL_REMOVE just to move the (still open) + connection to the pool; in the first case, + Abandon() would be most appropriate, but it breaks + the second case - is that a CURL bug? is there a + better solution? */ + } + + /** + * Callback function for CURLMOPT_SOCKETFUNCTION. + */ + static int SocketFunction(CURL *easy, + curl_socket_t s, int action, + void *userp, void *socketp); + + virtual bool OnSocketReady(unsigned flags) override; + +private: + static constexpr int FlagsToCurlCSelect(unsigned flags) { + return (flags & (READ | HANGUP) ? CURL_CSELECT_IN : 0) | + (flags & WRITE ? CURL_CSELECT_OUT : 0) | + (flags & ERROR ? CURL_CSELECT_ERR : 0); + } + + gcc_const + static unsigned CurlPollToFlags(int action) { + switch (action) { + case CURL_POLL_NONE: + return 0; + + case CURL_POLL_IN: + return READ; + + case CURL_POLL_OUT: + return WRITE; + + case CURL_POLL_INOUT: + return READ|WRITE; + } + + assert(false); + gcc_unreachable(); + } +}; + +/** + * Manager for the global CURLM object. + */ +class CurlMulti final : private TimeoutMonitor { + CURLM *const multi; + +public: + CurlMulti(EventLoop &_loop, CURLM *_multi); + + ~CurlMulti() { + curl_multi_cleanup(multi); + } + + bool Add(CurlInputStream *c, Error &error); + void Remove(CurlInputStream *c); + + /** + * Check for finished HTTP responses. + * + * Runs in the I/O thread. The caller must not hold locks. + */ + void ReadInfo(); + + void Assign(curl_socket_t fd, CurlSocket &cs) { + curl_multi_assign(multi, fd, &cs); + } + + void SocketAction(curl_socket_t fd, int ev_bitmask); + + void InvalidateSockets() { + SocketAction(CURL_SOCKET_TIMEOUT, 0); + } + + /** + * This is a kludge to allow pausing/resuming a stream with + * libcurl < 7.32.0. Read the curl_easy_pause manpage for + * more information. + */ + void ResumeSockets() { + int running_handles; + curl_multi_socket_all(multi, &running_handles); + } + +private: + static int TimerFunction(CURLM *multi, long timeout_ms, void *userp); + + virtual void OnTimeout() override; +}; + +/** + * libcurl version number encoded in a 24 bit integer. + */ +static unsigned curl_version_num; + +/** libcurl should accept "ICY 200 OK" */ +static struct curl_slist *http_200_aliases; + +/** HTTP proxy settings */ +static const char *proxy, *proxy_user, *proxy_password; +static unsigned proxy_port; + +static bool verify_peer, verify_host; + +static CurlMulti *curl_multi; + +static constexpr Domain http_domain("http"); +static constexpr Domain curl_domain("curl"); +static constexpr Domain curlm_domain("curlm"); + +CurlMulti::CurlMulti(EventLoop &_loop, CURLM *_multi) + :TimeoutMonitor(_loop), multi(_multi) +{ + curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, + CurlSocket::SocketFunction); + curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, this); + + curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, TimerFunction); + curl_multi_setopt(multi, CURLMOPT_TIMERDATA, this); +} + +/** + * Find a request by its CURL "easy" handle. + * + * Runs in the I/O thread. No lock needed. + */ +gcc_pure +static CurlInputStream * +input_curl_find_request(CURL *easy) +{ + assert(io_thread_inside()); + + void *p; + CURLcode code = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); + if (code != CURLE_OK) + return nullptr; + + return (CurlInputStream *)p; +} + +void +CurlInputStream::DoResume() +{ + assert(io_thread_inside()); + + mutex.unlock(); + + curl_easy_pause(easy, CURLPAUSE_CONT); + + if (curl_version_num < 0x072000) + /* libcurl older than 7.32.0 does not update + its sockets after curl_easy_pause(); force + libcurl to do it now */ + curl_multi->ResumeSockets(); + + curl_multi->InvalidateSockets(); + + mutex.lock(); +} + +int +CurlSocket::SocketFunction(gcc_unused CURL *easy, + curl_socket_t s, int action, + void *userp, void *socketp) { + CurlMulti &multi = *(CurlMulti *)userp; + CurlSocket *cs = (CurlSocket *)socketp; + + assert(io_thread_inside()); + + if (action == CURL_POLL_REMOVE) { + delete cs; + return 0; + } + + if (cs == nullptr) { + cs = new CurlSocket(multi, io_thread_get(), s); + multi.Assign(s, *cs); + } else { +#ifdef USE_EPOLL + /* when using epoll, we need to unregister the socket + each time this callback is invoked, because older + CURL versions may omit the CURL_POLL_REMOVE call + when the socket has been closed and recreated with + the same file number (bug found in CURL 7.26, CURL + 7.33 not affected); in that case, epoll refuses the + EPOLL_CTL_MOD because it does not know the new + socket yet */ + cs->Cancel(); +#endif + } + + unsigned flags = CurlPollToFlags(action); + if (flags != 0) + cs->Schedule(flags); + return 0; +} + +bool +CurlSocket::OnSocketReady(unsigned flags) +{ + assert(io_thread_inside()); + + multi.SocketAction(Get(), FlagsToCurlCSelect(flags)); + return true; +} + +/** + * Runs in the I/O thread. No lock needed. + */ +inline bool +CurlMulti::Add(CurlInputStream *c, Error &error) +{ + assert(io_thread_inside()); + assert(c != nullptr); + assert(c->easy != nullptr); + + CURLMcode mcode = curl_multi_add_handle(multi, c->easy); + if (mcode != CURLM_OK) { + error.Format(curlm_domain, mcode, + "curl_multi_add_handle() failed: %s", + curl_multi_strerror(mcode)); + return false; + } + + InvalidateSockets(); + return true; +} + +/** + * Call input_curl_easy_add() in the I/O thread. May be called from + * any thread. Caller must not hold a mutex. + */ +static bool +input_curl_easy_add_indirect(CurlInputStream *c, Error &error) +{ + assert(c != nullptr); + assert(c->easy != nullptr); + + bool result; + BlockingCall(io_thread_get(), [c, &error, &result](){ + result = curl_multi->Add(c, error); + }); + return result; +} + +inline void +CurlMulti::Remove(CurlInputStream *c) +{ + curl_multi_remove_handle(multi, c->easy); +} + +void +CurlInputStream::FreeEasy() +{ + assert(io_thread_inside()); + + if (easy == nullptr) + return; + + curl_multi->Remove(this); + + curl_easy_cleanup(easy); + easy = nullptr; + + curl_slist_free_all(request_headers); + request_headers = nullptr; +} + +void +CurlInputStream::FreeEasyIndirect() +{ + BlockingCall(io_thread_get(), [this](){ + FreeEasy(); + curl_multi->InvalidateSockets(); + }); + + assert(easy == nullptr); +} + +inline void +CurlInputStream::RequestDone(CURLcode result, long status) +{ + assert(io_thread_inside()); + assert(!postponed_error.IsDefined()); + + FreeEasy(); + AsyncInputStream::SetClosed(); + + const ScopeLock protect(mutex); + + if (result != CURLE_OK) { + postponed_error.Format(curl_domain, result, + "curl failed: %s", error_buffer); + } else if (status < 200 || status >= 300) { + postponed_error.Format(http_domain, status, + "got HTTP status %ld", + status); + } + + if (IsSeekPending()) + SeekDone(); + else if (!IsReady()) + SetReady(); +} + +static void +input_curl_handle_done(CURL *easy_handle, CURLcode result) +{ + CurlInputStream *c = input_curl_find_request(easy_handle); + assert(c != nullptr); + + long status = 0; + curl_easy_getinfo(easy_handle, CURLINFO_RESPONSE_CODE, &status); + + c->RequestDone(result, status); +} + +void +CurlMulti::SocketAction(curl_socket_t fd, int ev_bitmask) +{ + int running_handles; + CURLMcode mcode = curl_multi_socket_action(multi, fd, ev_bitmask, + &running_handles); + if (mcode != CURLM_OK) + FormatError(curlm_domain, + "curl_multi_socket_action() failed: %s", + curl_multi_strerror(mcode)); + + ReadInfo(); +} + +/** + * Check for finished HTTP responses. + * + * Runs in the I/O thread. The caller must not hold locks. + */ +inline void +CurlMulti::ReadInfo() +{ + assert(io_thread_inside()); + + CURLMsg *msg; + int msgs_in_queue; + + while ((msg = curl_multi_info_read(multi, + &msgs_in_queue)) != nullptr) { + if (msg->msg == CURLMSG_DONE) + input_curl_handle_done(msg->easy_handle, msg->data.result); + } +} + +int +CurlMulti::TimerFunction(gcc_unused CURLM *_multi, long timeout_ms, void *userp) +{ + CurlMulti &multi = *(CurlMulti *)userp; + assert(_multi == multi.multi); + + if (timeout_ms < 0) { + multi.Cancel(); + return 0; + } + + if (timeout_ms >= 0 && timeout_ms < 10) + /* CURL 7.21.1 likes to report "timeout=0", which + means we're running in a busy loop. Quite a bad + idea to waste so much CPU. Let's use a lower limit + of 10ms. */ + timeout_ms = 10; + + multi.Schedule(timeout_ms); + return 0; +} + +void +CurlMulti::OnTimeout() +{ + SocketAction(CURL_SOCKET_TIMEOUT, 0); +} + +/* + * InputPlugin methods + * + */ + +static InputPlugin::InitResult +input_curl_init(const config_param ¶m, Error &error) +{ + CURLcode code = curl_global_init(CURL_GLOBAL_ALL); + if (code != CURLE_OK) { + error.Format(curl_domain, code, + "curl_global_init() failed: %s", + curl_easy_strerror(code)); + return InputPlugin::InitResult::UNAVAILABLE; + } + + const auto version_info = curl_version_info(CURLVERSION_FIRST); + if (version_info != nullptr) { + FormatDebug(curl_domain, "version %s", version_info->version); + if (version_info->features & CURL_VERSION_SSL) + FormatDebug(curl_domain, "with %s", + version_info->ssl_version); + + curl_version_num = version_info->version_num; + } + + http_200_aliases = curl_slist_append(http_200_aliases, "ICY 200 OK"); + + proxy = param.GetBlockValue("proxy"); + proxy_port = param.GetBlockValue("proxy_port", 0u); + proxy_user = param.GetBlockValue("proxy_user"); + proxy_password = param.GetBlockValue("proxy_password"); + + if (proxy == nullptr) { + /* deprecated proxy configuration */ + proxy = config_get_string(CONF_HTTP_PROXY_HOST, nullptr); + proxy_port = config_get_positive(CONF_HTTP_PROXY_PORT, 0); + proxy_user = config_get_string(CONF_HTTP_PROXY_USER, nullptr); + proxy_password = config_get_string(CONF_HTTP_PROXY_PASSWORD, + ""); + } + + verify_peer = param.GetBlockValue("verify_peer", true); + verify_host = param.GetBlockValue("verify_host", true); + + CURLM *multi = curl_multi_init(); + if (multi == nullptr) { + curl_slist_free_all(http_200_aliases); + curl_global_cleanup(); + error.Set(curl_domain, 0, "curl_multi_init() failed"); + return InputPlugin::InitResult::UNAVAILABLE; + } + + curl_multi = new CurlMulti(io_thread_get(), multi); + return InputPlugin::InitResult::SUCCESS; +} + +static void +input_curl_finish(void) +{ + BlockingCall(io_thread_get(), [](){ + delete curl_multi; + }); + + curl_slist_free_all(http_200_aliases); + + curl_global_cleanup(); +} + +CurlInputStream::~CurlInputStream() +{ + FreeEasyIndirect(); +} + +inline void +CurlInputStream::HeaderReceived(const char *name, std::string &&value) +{ + if (IsSeekPending()) + /* don't update metadata while seeking */ + return; + + if (StringEqualsCaseASCII(name, "accept-ranges")) { + /* a stream with icy-metadata is not seekable */ + if (!icy->IsEnabled()) + seekable = true; + } else if (StringEqualsCaseASCII(name, "content-length")) { + size = offset + ParseUint64(value.c_str()); + } else if (StringEqualsCaseASCII(name, "content-type")) { + SetMimeType(std::move(value)); + } else if (StringEqualsCaseASCII(name, "icy-name") || + StringEqualsCaseASCII(name, "ice-name") || + StringEqualsCaseASCII(name, "x-audiocast-name")) { + TagBuilder tag_builder; + tag_builder.AddItem(TAG_NAME, value.c_str()); + + SetTag(tag_builder.CommitNew()); + } else if (StringEqualsCaseASCII(name, "icy-metaint")) { + if (icy->IsEnabled()) + return; + + size_t icy_metaint = ParseUint64(value.c_str()); + FormatDebug(curl_domain, "icy-metaint=%zu", icy_metaint); + + if (icy_metaint > 0) { + icy->Enable(icy_metaint); + + /* a stream with icy-metadata is not + seekable */ + seekable = false; + } + } +} + +/** called by curl when new data is available */ +static size_t +input_curl_headerfunction(void *ptr, size_t size, size_t nmemb, void *stream) +{ + CurlInputStream &c = *(CurlInputStream *)stream; + + size *= nmemb; + + const char *header = (const char *)ptr; + const char *end = header + size; + + char name[64]; + + const char *value = (const char *)memchr(header, ':', size); + if (value == nullptr || (size_t)(value - header) >= sizeof(name)) + return size; + + memcpy(name, header, value - header); + name[value - header] = 0; + + /* skip the colon */ + + ++value; + + /* strip the value */ + + while (value < end && IsWhitespaceOrNull(*value)) + ++value; + + while (end > value && IsWhitespaceOrNull(end[-1])) + --end; + + c.HeaderReceived(name, std::string(value, end)); + return size; +} + +inline size_t +CurlInputStream::DataReceived(const void *ptr, size_t received_size) +{ + assert(received_size > 0); + + const ScopeLock protect(mutex); + + if (IsSeekPending()) + SeekDone(); + + if (received_size > GetBufferSpace()) { + AsyncInputStream::Pause(); + return CURL_WRITEFUNC_PAUSE; + } + + AppendToBuffer(ptr, received_size); + return received_size; +} + +/** called by curl when new data is available */ +static size_t +input_curl_writefunction(void *ptr, size_t size, size_t nmemb, void *stream) +{ + CurlInputStream &c = *(CurlInputStream *)stream; + + size *= nmemb; + if (size == 0) + return 0; + + return c.DataReceived(ptr, size); +} + +bool +CurlInputStream::InitEasy(Error &error) +{ + easy = curl_easy_init(); + if (easy == nullptr) { + error.Set(curl_domain, "curl_easy_init() failed"); + return false; + } + + curl_easy_setopt(easy, CURLOPT_PRIVATE, (void *)this); + curl_easy_setopt(easy, CURLOPT_USERAGENT, + "Music Player Daemon " VERSION); + curl_easy_setopt(easy, CURLOPT_HEADERFUNCTION, + input_curl_headerfunction); + curl_easy_setopt(easy, CURLOPT_WRITEHEADER, this); + curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, + input_curl_writefunction); + curl_easy_setopt(easy, CURLOPT_WRITEDATA, this); + curl_easy_setopt(easy, CURLOPT_HTTP200ALIASES, http_200_aliases); + curl_easy_setopt(easy, CURLOPT_FOLLOWLOCATION, 1); + curl_easy_setopt(easy, CURLOPT_NETRC, 1); + curl_easy_setopt(easy, CURLOPT_MAXREDIRS, 5); + curl_easy_setopt(easy, CURLOPT_FAILONERROR, true); + curl_easy_setopt(easy, CURLOPT_ERRORBUFFER, error_buffer); + curl_easy_setopt(easy, CURLOPT_NOPROGRESS, 1l); + curl_easy_setopt(easy, CURLOPT_NOSIGNAL, 1l); + curl_easy_setopt(easy, CURLOPT_CONNECTTIMEOUT, 10l); + + if (proxy != nullptr) + curl_easy_setopt(easy, CURLOPT_PROXY, proxy); + + if (proxy_port > 0) + curl_easy_setopt(easy, CURLOPT_PROXYPORT, (long)proxy_port); + + if (proxy_user != nullptr && proxy_password != nullptr) { + char proxy_auth_str[1024]; + snprintf(proxy_auth_str, sizeof(proxy_auth_str), + "%s:%s", + proxy_user, proxy_password); + curl_easy_setopt(easy, CURLOPT_PROXYUSERPWD, proxy_auth_str); + } + + curl_easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, verify_peer ? 1l : 0l); + curl_easy_setopt(easy, CURLOPT_SSL_VERIFYHOST, verify_host ? 2l : 0l); + + CURLcode code = curl_easy_setopt(easy, CURLOPT_URL, GetURI()); + if (code != CURLE_OK) { + error.Format(curl_domain, code, + "curl_easy_setopt() failed: %s", + curl_easy_strerror(code)); + return false; + } + + request_headers = nullptr; + request_headers = curl_slist_append(request_headers, + "Icy-Metadata: 1"); + curl_easy_setopt(easy, CURLOPT_HTTPHEADER, request_headers); + + return true; +} + +void +CurlInputStream::DoSeek(offset_type new_offset) +{ + assert(IsReady()); + + /* close the old connection and open a new one */ + + mutex.unlock(); + + FreeEasyIndirect(); + + offset = new_offset; + if (offset == size) { + /* seek to EOF: simulate empty result; avoid + triggering a "416 Requested Range Not Satisfiable" + response */ + mutex.lock(); + SeekDone(); + return; + } + + Error error; + if (!InitEasy(postponed_error)) { + mutex.lock(); + PostponeError(std::move(error)); + return; + } + + /* send the "Range" header */ + + if (offset > 0) { + sprintf(range, "%lld-", (long long)offset); + curl_easy_setopt(easy, CURLOPT_RANGE, range); + } + + if (!input_curl_easy_add_indirect(this, error)) { + mutex.lock(); + PostponeError(std::move(error)); + return; + } + + mutex.lock(); + offset = new_offset; +} + +inline InputStream * +CurlInputStream::Open(const char *url, Mutex &mutex, Cond &cond, + Error &error) +{ + void *buffer = HugeAllocate(CURL_MAX_BUFFERED); + if (buffer == nullptr) { + error.Set(curl_domain, "Out of memory"); + return nullptr; + } + + CurlInputStream *c = new CurlInputStream(url, mutex, cond, buffer); + + if (!c->InitEasy(error) || !input_curl_easy_add_indirect(c, error)) { + delete c; + return nullptr; + } + + return c->icy; +} + +static InputStream * +input_curl_open(const char *url, Mutex &mutex, Cond &cond, + Error &error) +{ + if (memcmp(url, "http://", 7) != 0 && + memcmp(url, "https://", 8) != 0) + return nullptr; + + return CurlInputStream::Open(url, mutex, cond, error); +} + +const struct InputPlugin input_plugin_curl = { + "curl", + input_curl_init, + input_curl_finish, + input_curl_open, +}; diff --git a/src/input/plugins/CurlInputPlugin.hxx b/src/input/plugins/CurlInputPlugin.hxx new file mode 100644 index 000000000..4acb18bfc --- /dev/null +++ b/src/input/plugins/CurlInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_INPUT_CURL_HXX +#define MPD_INPUT_CURL_HXX + +extern const struct InputPlugin input_plugin_curl; + +#endif diff --git a/src/input/plugins/DespotifyInputPlugin.cxx b/src/input/plugins/DespotifyInputPlugin.cxx new file mode 100644 index 000000000..29d9186d0 --- /dev/null +++ b/src/input/plugins/DespotifyInputPlugin.cxx @@ -0,0 +1,227 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "DespotifyInputPlugin.hxx" +#include "lib/despotify/DespotifyUtils.hxx" +#include "../InputStream.hxx" +#include "../InputPlugin.hxx" +#include "tag/Tag.hxx" +#include "util/StringUtil.hxx" +#include "Log.hxx" + +extern "C" { +#include <despotify.h> +} + +#include <unistd.h> +#include <string.h> +#include <errno.h> + +#include <stdio.h> + +class DespotifyInputStream final : public InputStream { + struct despotify_session *session; + struct ds_track *track; + Tag tag; + struct ds_pcm_data pcm; + size_t len_available; + bool eof; + + DespotifyInputStream(const char *_uri, + Mutex &_mutex, Cond &_cond, + despotify_session *_session, + ds_track *_track) + :InputStream(_uri, _mutex, _cond), + session(_session), track(_track), + tag(mpd_despotify_tag_from_track(*track)), + len_available(0), eof(false) { + + memset(&pcm, 0, sizeof(pcm)); + + /* Despotify outputs pcm data */ + SetMimeType("audio/x-mpd-cdda-pcm"); + SetReady(); + } + +public: + ~DespotifyInputStream(); + + static InputStream *Open(const char *url, Mutex &mutex, Cond &cond, + Error &error); + + void Callback(int sig); + + /* virtual methods from InputStream */ + + bool IsEOF() override { + return eof; + } + + Tag *ReadTag() override { + if (tag.IsEmpty()) + return nullptr; + + Tag *result = new Tag(std::move(tag)); + tag.Clear(); + return result; + } + + size_t Read(void *ptr, size_t size, Error &error) override; + +private: + void FillBuffer(); +}; + +inline void +DespotifyInputStream::FillBuffer() +{ + /* Wait until there is data */ + while (1) { + int rc = despotify_get_pcm(session, &pcm); + + if (rc == 0 && pcm.len) { + len_available = pcm.len; + break; + } + + if (eof == true) + break; + + if (rc < 0) { + LogDebug(despotify_domain, "despotify_get_pcm error"); + eof = true; + break; + } + + /* Wait a while until next iteration */ + usleep(50 * 1000); + } +} + +inline void +DespotifyInputStream::Callback(int sig) +{ + switch (sig) { + case DESPOTIFY_NEW_TRACK: + break; + + case DESPOTIFY_TIME_TELL: + break; + + case DESPOTIFY_TRACK_PLAY_ERROR: + LogWarning(despotify_domain, "Track play error"); + eof = true; + len_available = 0; + break; + + case DESPOTIFY_END_OF_PLAYLIST: + eof = true; + LogDebug(despotify_domain, "End of playlist"); + break; + } +} + +static void callback(gcc_unused struct despotify_session* ds, + int sig, gcc_unused void* data, void* callback_data) +{ + DespotifyInputStream *ctx = (DespotifyInputStream *)callback_data; + + ctx->Callback(sig); +} + +DespotifyInputStream::~DespotifyInputStream() +{ + mpd_despotify_unregister_callback(callback); + despotify_free_track(track); +} + +inline InputStream * +DespotifyInputStream::Open(const char *url, + Mutex &mutex, Cond &cond, + gcc_unused Error &error) +{ + if (!StringStartsWith(url, "spt://")) + return nullptr; + + despotify_session *session = mpd_despotify_get_session(); + if (session == nullptr) + return nullptr; + + ds_link *ds_link = despotify_link_from_uri(url + 6); + if (!ds_link) { + FormatDebug(despotify_domain, "Can't find %s", url); + return nullptr; + } + if (ds_link->type != LINK_TYPE_TRACK) { + despotify_free_link(ds_link); + return nullptr; + } + + ds_track *track = despotify_link_get_track(session, ds_link); + despotify_free_link(ds_link); + if (!track) + return nullptr; + + DespotifyInputStream *ctx = + new DespotifyInputStream(url, mutex, cond, + session, track); + + if (!mpd_despotify_register_callback(callback, ctx)) { + delete ctx; + return nullptr; + } + + if (despotify_play(ctx->session, ctx->track, false) == false) { + mpd_despotify_unregister_callback(callback); + delete ctx; + return nullptr; + } + + return ctx; +} + +static InputStream * +input_despotify_open(const char *url, Mutex &mutex, Cond &cond, Error &error) +{ + return DespotifyInputStream::Open(url, mutex, cond, error); +} + +size_t +DespotifyInputStream::Read(void *ptr, size_t read_size, + gcc_unused Error &error) +{ + if (len_available == 0) + FillBuffer(); + + size_t to_cpy = std::min(read_size, len_available); + memcpy(ptr, pcm.buf, to_cpy); + len_available -= to_cpy; + + offset += to_cpy; + + return to_cpy; +} + +const InputPlugin input_plugin_despotify = { + "despotify", + nullptr, + nullptr, + input_despotify_open, +}; diff --git a/src/input/plugins/DespotifyInputPlugin.hxx b/src/input/plugins/DespotifyInputPlugin.hxx new file mode 100644 index 000000000..83f963520 --- /dev/null +++ b/src/input/plugins/DespotifyInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef INPUT_DESPOTIFY_HXX +#define INPUT_DESPOTIFY_HXX + +extern const struct InputPlugin input_plugin_despotify; + +#endif diff --git a/src/input/plugins/FfmpegInputPlugin.cxx b/src/input/plugins/FfmpegInputPlugin.cxx new file mode 100644 index 000000000..6e0260aee --- /dev/null +++ b/src/input/plugins/FfmpegInputPlugin.cxx @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +/* necessary because libavutil/common.h uses UINT64_C */ +#define __STDC_CONSTANT_MACROS + +#include "config.h" +#include "FfmpegInputPlugin.hxx" +#include "../InputStream.hxx" +#include "../InputPlugin.hxx" +#include "util/StringUtil.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" + +extern "C" { +#include <libavformat/avio.h> +#include <libavformat/avformat.h> +} + +struct FfmpegInputStream final : public InputStream { + AVIOContext *h; + + bool eof; + + FfmpegInputStream(const char *_uri, Mutex &_mutex, Cond &_cond, + AVIOContext *_h) + :InputStream(_uri, _mutex, _cond), + h(_h), eof(false) { + seekable = (h->seekable & AVIO_SEEKABLE_NORMAL) != 0; + size = avio_size(h); + + /* hack to make MPD select the "ffmpeg" decoder plugin + - since avio.h doesn't tell us the MIME type of the + resource, we can't select a decoder plugin, but the + "ffmpeg" plugin is quite good at auto-detection */ + SetMimeType("audio/x-mpd-ffmpeg"); + SetReady(); + } + + ~FfmpegInputStream() { + avio_close(h); + } + + /* virtual methods from InputStream */ + bool IsEOF() override; + size_t Read(void *ptr, size_t size, Error &error) override; + bool Seek(offset_type offset, Error &error) override; +}; + +static constexpr Domain ffmpeg_domain("ffmpeg"); + +static inline bool +input_ffmpeg_supported(void) +{ + void *opaque = nullptr; + return avio_enum_protocols(&opaque, 0) != nullptr; +} + +static InputPlugin::InitResult +input_ffmpeg_init(gcc_unused const config_param ¶m, + Error &error) +{ + av_register_all(); + + /* disable this plugin if there's no registered protocol */ + if (!input_ffmpeg_supported()) { + error.Set(ffmpeg_domain, "No protocol"); + return InputPlugin::InitResult::UNAVAILABLE; + } + + return InputPlugin::InitResult::SUCCESS; +} + +static InputStream * +input_ffmpeg_open(const char *uri, + Mutex &mutex, Cond &cond, + Error &error) +{ + if (!StringStartsWith(uri, "gopher://") && + !StringStartsWith(uri, "rtp://") && + !StringStartsWith(uri, "rtsp://") && + !StringStartsWith(uri, "rtmp://") && + !StringStartsWith(uri, "rtmpt://") && + !StringStartsWith(uri, "rtmps://")) + return nullptr; + + AVIOContext *h; + int ret = avio_open(&h, uri, AVIO_FLAG_READ); + if (ret != 0) { + error.Set(ffmpeg_domain, ret, + "libavformat failed to open the URI"); + return nullptr; + } + + return new FfmpegInputStream(uri, mutex, cond, h); +} + +size_t +FfmpegInputStream::Read(void *ptr, size_t read_size, Error &error) +{ + int ret = avio_read(h, (unsigned char *)ptr, read_size); + if (ret <= 0) { + if (ret < 0) + error.Set(ffmpeg_domain, "avio_read() failed"); + + eof = true; + return false; + } + + offset += ret; + return (size_t)ret; +} + +bool +FfmpegInputStream::IsEOF() +{ + return eof; +} + +bool +FfmpegInputStream::Seek(offset_type new_offset, Error &error) +{ + int64_t ret = avio_seek(h, new_offset, SEEK_SET); + + if (ret >= 0) { + eof = false; + return true; + } else { + error.Set(ffmpeg_domain, "avio_seek() failed"); + return false; + } +} + +const InputPlugin input_plugin_ffmpeg = { + "ffmpeg", + input_ffmpeg_init, + nullptr, + input_ffmpeg_open, +}; diff --git a/src/input/plugins/FfmpegInputPlugin.hxx b/src/input/plugins/FfmpegInputPlugin.hxx new file mode 100644 index 000000000..43f829e89 --- /dev/null +++ b/src/input/plugins/FfmpegInputPlugin.hxx @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_FFMPEG_INPUT_PLUGIN_HXX +#define MPD_FFMPEG_INPUT_PLUGIN_HXX + +/** + * An input plugin based on libavformat's "avio" library. + */ +extern const struct InputPlugin input_plugin_ffmpeg; + +#endif diff --git a/src/input/plugins/FileInputPlugin.cxx b/src/input/plugins/FileInputPlugin.cxx new file mode 100644 index 000000000..60c316567 --- /dev/null +++ b/src/input/plugins/FileInputPlugin.cxx @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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" /* must be first for large file support */ +#include "FileInputPlugin.hxx" +#include "../InputStream.hxx" +#include "../InputPlugin.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" +#include "fs/Traits.hxx" +#include "system/fd_util.h" +#include "open.h" + +#include <sys/stat.h> +#include <unistd.h> +#include <errno.h> + +static constexpr Domain file_domain("file"); + +struct FileInputStream final : public InputStream { + int fd; + + FileInputStream(const char *path, int _fd, off_t _size, + Mutex &_mutex, Cond &_cond) + :InputStream(path, _mutex, _cond), + fd(_fd) { + size = _size; + seekable = true; + SetReady(); + } + + ~FileInputStream() { + close(fd); + } + + /* virtual methods from InputStream */ + + bool IsEOF() override { + return GetOffset() >= GetSize(); + } + + size_t Read(void *ptr, size_t size, Error &error) override; + bool Seek(offset_type offset, Error &error) override; +}; + +static InputStream * +input_file_open(const char *filename, + Mutex &mutex, Cond &cond, + Error &error) +{ + int fd, ret; + struct stat st; + + if (!PathTraitsFS::IsAbsolute(filename)) + return nullptr; + + fd = open_cloexec(filename, O_RDONLY|O_BINARY, 0); + if (fd < 0) { + if (errno != ENOENT && errno != ENOTDIR) + error.FormatErrno("Failed to open \"%s\"", + filename); + return nullptr; + } + + ret = fstat(fd, &st); + if (ret < 0) { + error.FormatErrno("Failed to stat \"%s\"", filename); + close(fd); + return nullptr; + } + + if (!S_ISREG(st.st_mode)) { + error.Format(file_domain, "Not a regular file: %s", filename); + close(fd); + return nullptr; + } + +#ifdef POSIX_FADV_SEQUENTIAL + posix_fadvise(fd, (off_t)0, st.st_size, POSIX_FADV_SEQUENTIAL); +#endif + + return new FileInputStream(filename, fd, st.st_size, mutex, cond); +} + +bool +FileInputStream::Seek(offset_type new_offset, Error &error) +{ + new_offset = (offset_type)lseek(fd, (off_t)new_offset, SEEK_SET); + if (new_offset < 0) { + error.SetErrno("Failed to seek"); + return false; + } + + offset = new_offset; + return true; +} + +size_t +FileInputStream::Read(void *ptr, size_t read_size, Error &error) +{ + ssize_t nbytes = read(fd, ptr, read_size); + if (nbytes < 0) { + error.SetErrno("Failed to read"); + return 0; + } + + offset += nbytes; + return (size_t)nbytes; +} + +const InputPlugin input_plugin_file = { + "file", + nullptr, + nullptr, + input_file_open, +}; diff --git a/src/input/plugins/FileInputPlugin.hxx b/src/input/plugins/FileInputPlugin.hxx new file mode 100644 index 000000000..4aef94637 --- /dev/null +++ b/src/input/plugins/FileInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_INPUT_FILE_HXX +#define MPD_INPUT_FILE_HXX + +extern const struct InputPlugin input_plugin_file; + +#endif diff --git a/src/input/plugins/MmsInputPlugin.cxx b/src/input/plugins/MmsInputPlugin.cxx new file mode 100644 index 000000000..1aed9c662 --- /dev/null +++ b/src/input/plugins/MmsInputPlugin.cxx @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "MmsInputPlugin.hxx" +#include "input/ThreadInputStream.hxx" +#include "input/InputPlugin.hxx" +#include "util/StringUtil.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" + +#include <libmms/mmsx.h> + +static constexpr size_t MMS_BUFFER_SIZE = 256 * 1024; + +class MmsInputStream final : public ThreadInputStream { + mmsx_t *mms; + +public: + MmsInputStream(const char *_uri, Mutex &_mutex, Cond &_cond) + :ThreadInputStream(input_plugin_mms.name, _uri, _mutex, _cond, + MMS_BUFFER_SIZE) { + } + +protected: + virtual bool Open(gcc_unused Error &error) override; + virtual size_t ThreadRead(void *ptr, size_t size, + Error &error) override; + + virtual void Close() { + mmsx_close(mms); + } +}; + +static constexpr Domain mms_domain("mms"); + +bool +MmsInputStream::Open(Error &error) +{ + Unlock(); + + mms = mmsx_connect(nullptr, nullptr, GetURI(), 128 * 1024); + if (mms == nullptr) { + Lock(); + error.Set(mms_domain, "mmsx_connect() failed"); + return false; + } + + Lock(); + + /* TODO: is this correct? at least this selects the ffmpeg + decoder, which seems to work fine */ + SetMimeType("audio/x-ms-wma"); + return true; +} + +static InputStream * +input_mms_open(const char *url, + Mutex &mutex, Cond &cond, + Error &error) +{ + if (!StringStartsWith(url, "mms://") && + !StringStartsWith(url, "mmsh://") && + !StringStartsWith(url, "mmst://") && + !StringStartsWith(url, "mmsu://")) + return nullptr; + + auto m = new MmsInputStream(url, mutex, cond); + auto is = m->Start(error); + if (is == nullptr) + delete m; + + return is; +} + +size_t +MmsInputStream::ThreadRead(void *ptr, size_t read_size, Error &error) +{ + int nbytes = mmsx_read(nullptr, mms, (char *)ptr, read_size); + if (nbytes <= 0) { + if (nbytes < 0) + error.SetErrno("mmsx_read() failed"); + return 0; + } + + return (size_t)nbytes; +} + +const InputPlugin input_plugin_mms = { + "mms", + nullptr, + nullptr, + input_mms_open, +}; diff --git a/src/input/plugins/MmsInputPlugin.hxx b/src/input/plugins/MmsInputPlugin.hxx new file mode 100644 index 000000000..b4017ffd6 --- /dev/null +++ b/src/input/plugins/MmsInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef INPUT_MMS_H +#define INPUT_MMS_H + +extern const struct InputPlugin input_plugin_mms; + +#endif diff --git a/src/input/plugins/NfsInputPlugin.cxx b/src/input/plugins/NfsInputPlugin.cxx new file mode 100644 index 000000000..baa707738 --- /dev/null +++ b/src/input/plugins/NfsInputPlugin.cxx @@ -0,0 +1,221 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "NfsInputPlugin.hxx" +#include "../AsyncInputStream.hxx" +#include "../InputPlugin.hxx" +#include "lib/nfs/Domain.hxx" +#include "lib/nfs/Glue.hxx" +#include "lib/nfs/FileReader.hxx" +#include "util/HugeAllocator.hxx" +#include "util/StringUtil.hxx" +#include "util/Error.hxx" + +extern "C" { +#include <nfsc/libnfs.h> +} + +#include <string.h> +#include <sys/stat.h> +#include <fcntl.h> + +/** + * Do not buffer more than this number of bytes. It should be a + * reasonable limit that doesn't make low-end machines suffer too + * much, but doesn't cause stuttering on high-latency lines. + */ +static const size_t NFS_MAX_BUFFERED = 512 * 1024; + +/** + * Resume the stream at this number of bytes after it has been paused. + */ +static const size_t NFS_RESUME_AT = 384 * 1024; + +class NfsInputStream final : public AsyncInputStream, NfsFileReader { + uint64_t next_offset; + +public: + NfsInputStream(const char *_uri, + Mutex &_mutex, Cond &_cond, + void *_buffer) + :AsyncInputStream(_uri, _mutex, _cond, + _buffer, NFS_MAX_BUFFERED, + NFS_RESUME_AT) {} + + virtual ~NfsInputStream() { + DeferClose(); + } + + bool Open(Error &error) { + assert(!IsReady()); + + return NfsFileReader::Open(GetURI(), error); + } + +private: + bool DoRead(); + +protected: + /* virtual methods from AsyncInputStream */ + virtual void DoResume() override; + virtual void DoSeek(offset_type new_offset) override; + +private: + /* virtual methods from NfsFileReader */ + void OnNfsFileOpen(uint64_t size) override; + void OnNfsFileRead(const void *data, size_t size) override; + void OnNfsFileError(Error &&error) override; +}; + +bool +NfsInputStream::DoRead() +{ + assert(NfsFileReader::IsIdle()); + + int64_t remaining = size - next_offset; + if (remaining <= 0) + return true; + + const size_t buffer_space = GetBufferSpace(); + if (buffer_space == 0) { + Pause(); + return true; + } + + size_t nbytes = std::min<size_t>(std::min<uint64_t>(remaining, 32768), + buffer_space); + + mutex.unlock(); + Error error; + bool success = NfsFileReader::Read(next_offset, nbytes, error); + mutex.lock(); + + if (!success) { + PostponeError(std::move(error)); + return false; + } + + return true; +} + +void +NfsInputStream::DoResume() +{ + assert(NfsFileReader::IsIdle()); + + DoRead(); +} + +void +NfsInputStream::DoSeek(offset_type new_offset) +{ + mutex.unlock(); + NfsFileReader::CancelRead(); + mutex.lock(); + + next_offset = offset = new_offset; + SeekDone(); + DoRead(); +} + +void +NfsInputStream::OnNfsFileOpen(uint64_t _size) +{ + const ScopeLock protect(mutex); + + size = _size; + seekable = true; + next_offset = 0; + SetReady(); + DoRead(); +} + +void +NfsInputStream::OnNfsFileRead(const void *data, size_t data_size) +{ + const ScopeLock protect(mutex); + assert(!IsBufferFull()); + assert(IsBufferFull() == (GetBufferSpace() == 0)); + AppendToBuffer(data, data_size); + + next_offset += data_size; + + DoRead(); +} + +void +NfsInputStream::OnNfsFileError(Error &&error) +{ + const ScopeLock protect(mutex); + postponed_error = std::move(error); + + if (IsSeekPending()) + SeekDone(); + else if (!IsReady()) + SetReady(); +} + +/* + * InputPlugin methods + * + */ + +static InputPlugin::InitResult +input_nfs_init(const config_param &, Error &) +{ + nfs_init(); + return InputPlugin::InitResult::SUCCESS; +} + +static void +input_nfs_finish() +{ + nfs_finish(); +} + +static InputStream * +input_nfs_open(const char *uri, + Mutex &mutex, Cond &cond, + Error &error) +{ + if (!StringStartsWith(uri, "nfs://")) + return nullptr; + + void *buffer = HugeAllocate(NFS_MAX_BUFFERED); + if (buffer == nullptr) { + error.Set(nfs_domain, "Out of memory"); + return nullptr; + } + + NfsInputStream *is = new NfsInputStream(uri, mutex, cond, buffer); + if (!is->Open(error)) { + delete is; + return nullptr; + } + + return is; +} + +const InputPlugin input_plugin_nfs = { + "nfs", + input_nfs_init, + input_nfs_finish, + input_nfs_open, +}; diff --git a/src/input/plugins/NfsInputPlugin.hxx b/src/input/plugins/NfsInputPlugin.hxx new file mode 100644 index 000000000..d2cc87549 --- /dev/null +++ b/src/input/plugins/NfsInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_INPUT_NFS_H +#define MPD_INPUT_NFS_H + +extern const struct InputPlugin input_plugin_nfs; + +#endif diff --git a/src/input/plugins/RewindInputPlugin.cxx b/src/input/plugins/RewindInputPlugin.cxx new file mode 100644 index 000000000..95f604044 --- /dev/null +++ b/src/input/plugins/RewindInputPlugin.cxx @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "RewindInputPlugin.hxx" +#include "../ProxyInputStream.hxx" + +#include <assert.h> +#include <string.h> + +class RewindInputStream final : public ProxyInputStream { + /** + * The read position within the buffer. Undefined as long as + * ReadingFromBuffer() returns false. + */ + size_t head; + + /** + * The write/append position within the buffer. + */ + size_t tail; + + /** + * The size of this buffer is the maximum number of bytes + * which can be rewinded cheaply without passing the "seek" + * call to CURL. + * + * The origin of this buffer is always the beginning of the + * stream (offset 0). + */ + char buffer[64 * 1024]; + +public: + RewindInputStream(InputStream *_input) + :ProxyInputStream(_input), + tail(0) { + } + + /* virtual methods from InputStream */ + + void Update() override { + if (!ReadingFromBuffer()) + ProxyInputStream::Update(); + } + + bool IsEOF() override { + return !ReadingFromBuffer() && ProxyInputStream::IsEOF(); + } + + size_t Read(void *ptr, size_t size, Error &error) override; + bool Seek(offset_type offset, Error &error) override; + +private: + /** + * Are we currently reading from the buffer, and does the + * buffer contain more data for the next read operation? + */ + bool ReadingFromBuffer() const { + return tail > 0 && offset < input.GetOffset(); + } +}; + +size_t +RewindInputStream::Read(void *ptr, size_t read_size, Error &error) +{ + if (ReadingFromBuffer()) { + /* buffered read */ + + assert(head == (size_t)offset); + assert(tail == (size_t)input.GetOffset()); + + if (read_size > tail - head) + read_size = tail - head; + + memcpy(ptr, buffer + head, read_size); + head += read_size; + offset += read_size; + + return read_size; + } else { + /* pass method call to underlying stream */ + + size_t nbytes = input.Read(ptr, read_size, error); + + if (input.GetOffset() > (offset_type)sizeof(buffer)) + /* disable buffering */ + tail = 0; + else if (tail == (size_t)offset) { + /* append to buffer */ + + memcpy(buffer + tail, ptr, nbytes); + tail += nbytes; + + assert(tail == (size_t)input.GetOffset()); + } + + CopyAttributes(); + + return nbytes; + } +} + +bool +RewindInputStream::Seek(offset_type new_offset, + Error &error) +{ + assert(IsReady()); + + if (tail > 0 && new_offset <= (offset_type)tail) { + /* buffered seek */ + + assert(!ReadingFromBuffer() || + head == (size_t)offset); + assert(tail == (size_t)input.GetOffset()); + + head = (size_t)new_offset; + offset = new_offset; + + return true; + } else { + /* disable the buffer, because input has left the + buffered range now */ + tail = 0; + + return ProxyInputStream::Seek(new_offset, error); + } +} + +InputStream * +input_rewind_open(InputStream *is) +{ + assert(is != nullptr); + assert(!is->IsReady() || is->GetOffset() == 0); + + if (is->IsReady() && is->IsSeekable()) + /* seekable resources don't need this plugin */ + return is; + + return new RewindInputStream(is); +} diff --git a/src/input/plugins/RewindInputPlugin.hxx b/src/input/plugins/RewindInputPlugin.hxx new file mode 100644 index 000000000..56b01b585 --- /dev/null +++ b/src/input/plugins/RewindInputPlugin.hxx @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +/** \file + * + * A wrapper for an input_stream object which allows cheap buffered + * rewinding. This is useful while detecting the stream codec (let + * each decoder plugin peek a portion from the stream). + */ + +#ifndef MPD_INPUT_REWIND_HXX +#define MPD_INPUT_REWIND_HXX + +#include "check.h" + +class InputStream; + +InputStream * +input_rewind_open(InputStream *is); + +#endif diff --git a/src/input/plugins/SmbclientInputPlugin.cxx b/src/input/plugins/SmbclientInputPlugin.cxx new file mode 100644 index 000000000..79987180f --- /dev/null +++ b/src/input/plugins/SmbclientInputPlugin.cxx @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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 "SmbclientInputPlugin.hxx" +#include "lib/smbclient/Init.hxx" +#include "lib/smbclient/Mutex.hxx" +#include "../InputStream.hxx" +#include "../InputPlugin.hxx" +#include "util/StringUtil.hxx" +#include "util/Error.hxx" + +#include <libsmbclient.h> + +class SmbclientInputStream final : public InputStream { + SMBCCTX *ctx; + int fd; + +public: + SmbclientInputStream(const char *_uri, + Mutex &_mutex, Cond &_cond, + SMBCCTX *_ctx, int _fd, const struct stat &st) + :InputStream(_uri, _mutex, _cond), + ctx(_ctx), fd(_fd) { + seekable = true; + size = st.st_size; + SetReady(); + } + + ~SmbclientInputStream() { + smbclient_mutex.lock(); + smbc_close(fd); + smbc_free_context(ctx, 1); + smbclient_mutex.unlock(); + } + + /* virtual methods from InputStream */ + + bool IsEOF() override { + return offset >= size; + } + + size_t Read(void *ptr, size_t size, Error &error) override; + bool Seek(offset_type offset, Error &error) override; +}; + +/* + * InputPlugin methods + * + */ + +static InputPlugin::InitResult +input_smbclient_init(gcc_unused const config_param ¶m, Error &error) +{ + if (!SmbclientInit(error)) + return InputPlugin::InitResult::UNAVAILABLE; + + // TODO: create one global SMBCCTX here? + + // TODO: evaluate config_param, call smbc_setOption*() + + return InputPlugin::InitResult::SUCCESS; +} + +static InputStream * +input_smbclient_open(const char *uri, + Mutex &mutex, Cond &cond, + Error &error) +{ + if (!StringStartsWith(uri, "smb://")) + return nullptr; + + const ScopeLock protect(smbclient_mutex); + + SMBCCTX *ctx = smbc_new_context(); + if (ctx == nullptr) { + error.SetErrno("smbc_new_context() failed"); + return nullptr; + } + + SMBCCTX *ctx2 = smbc_init_context(ctx); + if (ctx2 == nullptr) { + error.SetErrno("smbc_init_context() failed"); + smbc_free_context(ctx, 1); + return nullptr; + } + + ctx = ctx2; + + int fd = smbc_open(uri, O_RDONLY, 0); + if (fd < 0) { + error.SetErrno("smbc_open() failed"); + smbc_free_context(ctx, 1); + return nullptr; + } + + struct stat st; + if (smbc_fstat(fd, &st) < 0) { + error.SetErrno("smbc_fstat() failed"); + smbc_close(fd); + smbc_free_context(ctx, 1); + return nullptr; + } + + return new SmbclientInputStream(uri, mutex, cond, ctx, fd, st); +} + +size_t +SmbclientInputStream::Read(void *ptr, size_t read_size, Error &error) +{ + smbclient_mutex.lock(); + ssize_t nbytes = smbc_read(fd, ptr, read_size); + smbclient_mutex.unlock(); + if (nbytes < 0) { + error.SetErrno("smbc_read() failed"); + nbytes = 0; + } + + return nbytes; +} + +bool +SmbclientInputStream::Seek(offset_type new_offset, Error &error) +{ + smbclient_mutex.lock(); + off_t result = smbc_lseek(fd, new_offset, SEEK_SET); + smbclient_mutex.unlock(); + if (result < 0) { + error.SetErrno("smbc_lseek() failed"); + return false; + } + + offset = result; + return true; +} + +const InputPlugin input_plugin_smbclient = { + "smbclient", + input_smbclient_init, + nullptr, + input_smbclient_open, +}; diff --git a/src/input/plugins/SmbclientInputPlugin.hxx b/src/input/plugins/SmbclientInputPlugin.hxx new file mode 100644 index 000000000..a0539d020 --- /dev/null +++ b/src/input/plugins/SmbclientInputPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * 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. + */ + +#ifndef MPD_INPUT_SMBCLIENT_H +#define MPD_INPUT_SMBCLIENT_H + +extern const struct InputPlugin input_plugin_smbclient; + +#endif |