Compare commits

...

156 Commits

Author SHA1 Message Date
Max Kellermann
964804a4c2 release v0.21.15 2019-09-25 21:24:15 +02:00
Max Kellermann
92495d2b0b decoder/mpcdec: fix bogus ReplayGain values
Apparently, libmpcdec sets gain/peak variables to zero if they are not
present.  This clashes with our formula and results in bogus values
which cause noise during playback.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/640
2019-09-13 19:52:11 +02:00
Max Kellermann
9270829b5b ReplayGainInfo: move more code to a function 2019-09-13 19:50:49 +02:00
Max Kellermann
b6243a9945 decoder/mpcdec: merge duplicate code 2019-09-13 19:50:43 +02:00
Max Kellermann
496f88653d ReplayGainInfo: add static method Undefined() 2019-09-13 19:46:39 +02:00
Max Kellermann
5ef645df97 NEWS: add missing line for 818b7e0641 2019-09-08 12:54:16 +02:00
Max Kellermann
bf49c9e4e2 decoder/{dsf,dsdiff}: precalculate bit rate 2019-09-08 12:52:02 +02:00
Max Kellermann
0da9c91af2 decoder/{dsf,dsdiff}: fix displayed bit rate
The formula did not consider the channel count.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/639
2019-09-08 12:45:05 +02:00
Max Kellermann
193e637dd9 python/build/libs: update Boost to 1.71.0 2019-09-01 13:03:50 +02:00
Max Kellermann
928bee933d python/build/libs: update expat to 2.2.7 2019-09-01 13:02:56 +02:00
Max Kellermann
4d1720c886 python/build/libs: update CURL to 7.65.3 2019-09-01 13:02:04 +02:00
Max Kellermann
8f8ed87327 python/build/libs: update FFmpeg to 4.2 2019-09-01 13:00:26 +02:00
Max Kellermann
28a441c977 python/build/libs: update Opus to 1.3.1 2019-09-01 12:59:17 +02:00
Max Kellermann
8cf50b08f2 python/build/libs: update libogg to 1.3.4 2019-09-01 12:58:26 +02:00
Max Kellermann
818b7e0641 output/solaris: include sys/stropts.h only on Solaris
This header had been available for a long time on Linux, but was
removed in glibc 2.30.  This commit moves the `#include` line inside
the `#ifdef __sun` block and adds a fake declaration of `I_FLUSH` for
the Linux build.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/630
2019-08-22 11:41:12 +02:00
Max Kellermann
e70f40fac1 increment version number to 0.21.15 2019-08-22 11:40:17 +02:00
Max Kellermann
bc89ca92b4 release v0.21.14 2019-08-21 10:47:53 +02:00
Max Kellermann
b968e1b6de output/Thread: add missing return in exception handler 2019-08-21 10:20:17 +02:00
Max Kellermann
6c9f9c136b command/all: don't create new Response instance in exception handler
The new Response instance in the `catch` block didn't have the
`command` attribute set, so the error response didn't indicate which
command had failed, which however is required in the MPD protocol.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/628
2019-08-20 20:31:36 +02:00
Max Kellermann
9bff5f9e36 client/Process, command/all: add noexcept
Clarify that those can't throw, preparing for the next commit.
2019-08-20 20:28:15 +02:00
Max Kellermann
2bf26a2ff8 command/all: remove obsolete prototype 2019-08-20 20:28:10 +02:00
Max Kellermann
e33b50d9c5 command/all: simplify return from command_process() 2019-08-20 20:26:07 +02:00
Max Kellermann
21fa44c0d5 command/all: catch all exceptions 2019-08-20 20:23:54 +02:00
Max Kellermann
44444e1b89 decoder/Thread: on late SEEK, start decoder at seek position
Previously, a bogus value (whatever happened to be still in
`start_time`) was used.
2019-08-20 20:15:08 +02:00
Max Kellermann
ca450663d0 decoder/Control: work around crash after SEEK was too late
See code comment.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/629
2019-08-20 20:01:53 +02:00
Max Kellermann
f3d16f6d1b output/Thread: fix typo in comment 2019-08-13 13:08:40 +02:00
Max Kellermann
4464cdcc67 doc/protocol.rst: add missing newline to "albumart" example
This was missing in commit 0f488dcecf
2019-08-12 20:20:17 +02:00
Fredrik Noring
2d61e526de decoder/sidplay: Fix date field to have year but not company or author
Field 2 is called <released>, formerly used as <copyright>[1][2]. It is
formatted <year><space><company or author or group>, where <year> may be
<YYYY>, <YYY?>, <YY??> or <YYYY-YY>, for example "1987", "199?", "19??"
or "1985-87". The <company or author or group> may be for example Rob
Hubbard. A full field may be for example "1987 Rob Hubbard".

This change splits the <released> field at the first <space>, to retain
the <year> part.

The 51823 SID files in High Voltage SID Collection (HVSC) version 71
have the following distribution of dates:

    333 19??         11 1990-92       6 1995-99       2 2006-08
    827 198?         88 1990-93    2140 1996        530 2007
     32 1982         69 1990-94       9 1996-97      15 2007-08
      1 1982-83      49 1990-95       2 1996-98       2 2007-09
    255 1983       3467 1991          5 1996-99       1 2007-10
    677 1984         75 1991-92    1840 1997        430 2008
    775 1985         65 1991-93       4 1997-98      23 2008-09
      3 1985-86      10 1991-94    1276 1998          1 2008-12
     10 1985-87      35 1991-97       4 1998-99     631 2009
    943 1986       3320 1992        865 1999          1 2009-10
     12 1986-87      26 1992-93      24 200?        645 2010
      5 1986-89      59 1992-94     590 2000          1 2010-12
   2083 1987          1 1992-96       4 2000-01     538 2011
     31 1987-88    2996 1993        727 2001          1 2011-12
     44 1987-89      42 1993-94     875 2002        651 2012
   2510 1988         12 1993-95       2 2002-04     811 2013
    129 1988-89       2 1993-97     844 2003        790 2014
     91 1988-90    2737 1994          3 2003-05     740 2015
     58 1988-91      16 1994-95     842 2004        792 2016
   3466 1989         20 1994-96       2 2004-05     775 2017
     95 1989-90      17 1994-97     707 2005        638 2018
    150 1989-91    2271 1995          1 2005-06     284 2019
   1077 199?          2 1995-96       2 2005-07
   2834 1990          4 1995-97     785 2006
    119 1990-91       2 1995-98       6 2006-07

References:

[1] https://www.hvsc.c64.org/download/C64Music/DOCUMENTS/SID_file_format.txt
[2] https://hvsc.c64.org/info
2019-08-10 10:50:51 +02:00
Fredrik Noring
7723c481db decoder/sidplay: Fix windows-1252 to utf-8 string conversion
High Voltage SID Collection (HVSC) metadata fields are encoded in
windows-1252, as described in DOCUMENTS/SID_file_format.txt:

https://www.hvsc.c64.org/download/C64Music/DOCUMENTS/SID_file_format.txt

If utf-8 transcoding fails, or the ICU library is unavailable, fall
back to plain ASCII and replace other characters with '?'.
2019-08-10 10:45:02 +02:00
Fredrik Noring
0ed10542cc decoder/sidplay: Fix song length initialisation during container scan
The song length was previously undetermined.
2019-08-09 15:39:36 +02:00
Max Kellermann
ab830f9afd increment version number to 0.21.14 2019-08-09 15:38:01 +02:00
Max Kellermann
d4d2bc072e release v0.21.13 2019-08-06 11:35:42 +02:00
Max Kellermann
bcccc8f66c output/jack: use jack_free() for Windows compatibility 2019-08-06 11:34:56 +02:00
Max Kellermann
848c63e2d5 output/jack: use std::atomic_bool for "shutdown" and "pause"
Without this, the compiler may optimize accesses away.
2019-08-06 11:34:00 +02:00
Max Kellermann
f6d0310f9c output/jack: use SIZE_MAX instead of (size_t)-1 2019-08-06 11:33:52 +02:00
Max Kellermann
3ef043392c input/cdio_paranoia: drop support for libcdio-paranoia older than 10.2+0.93+1
Version 10.2+0.93+1 was released five years ago in 2014 and is the
first version to feature cdio_cddap_free_messages().  There is no way
to check the libcdio-paranoia version at compile time, so let's just
remove support for older versions instead of attempting to fix the
cdio_cddap_free_messages() check at build time.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/613
2019-08-06 11:09:36 +02:00
Max Kellermann
864d6f312d Revert "decoder/mad: use MAD_F_MIN and MAD_F_MAX"
This reverts commit f7ed7446ae.  It was
a bad idea, because MAD_F_MIN and MAD_F_MAX do not represent the
clamping limits, but the theoretical minimum and maximum values of the
mad_fixed_t data type.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/617
2019-08-05 13:07:41 +02:00
Max Kellermann
f44c67de09 increment version number to 0.21.13 2019-08-05 13:05:54 +02:00
Max Kellermann
ae19bda1f2 release v0.21.12 2019-08-03 12:48:20 +02:00
Max Kellermann
f2d8fd769d player/Thread: don't restart unseekable song after failed seek attempt
The check IsSeekableCurrentSong() was added by commit
44b200240f in version 0.20.19, but it
caused a regression: by doing the branch only if the current song is
seekable, the player would restart the current song if it was not
seekable, and later the initial seek would fail; but we already know
it's not seekable, and so we should fail early.
2019-08-03 12:30:10 +02:00
Max Kellermann
9661062ae2 decoder/mad: pass const reference to RecoverFrameError() 2019-08-03 11:59:41 +02:00
Max Kellermann
2a07354cad decoder/mad: change integers to size_t 2019-08-03 11:44:02 +02:00
Max Kellermann
fc18fd571c decoder/mad: return from SynthAndSubmit() early 2019-08-03 11:42:05 +02:00
Max Kellermann
51abed9732 decoder/mad: pass mad_pcm to mad_fixed_to_24_buffer() 2019-08-03 11:40:06 +02:00
Max Kellermann
d00afc912c decoder/mad: eliminate the loop in SubmitPCM()
libmad has a hard-coded maximum PCM buffer size; if we make our
output_buffer just as large, we can avoid the loop, because any
possible size will fit.
2019-08-03 11:36:05 +02:00
Max Kellermann
9d0fe725eb decoder/mad: rename a few misnamed methods 2019-08-03 11:32:42 +02:00
Max Kellermann
8a432c9b7f decoder/mad: move code to LoadNextFrame() 2019-08-03 11:32:06 +02:00
Max Kellermann
187204f03c decoder/mad: move code to HandleCurrentFrame() 2019-08-03 11:32:06 +02:00
Max Kellermann
5e5fadb5f2 decoder/mad: remove unnecessary initializers
These will not be used until they are initialized in SyncAndSend().
2019-08-03 08:49:26 +02:00
Max Kellermann
952c793235 decoder/mad: subtract libmad decoder delay from LAME encoder padding
Apparently, libmad not only inserts 529 samples of silence at the
beginning of the file, but also removes them at the end.

This solves the last piece of
https://github.com/MusicPlayerDaemon/MPD/issues/601

Closes https://github.com/MusicPlayerDaemon/MPD/issues/601
2019-08-03 08:35:00 +02:00
Max Kellermann
3e3d8c7f9d decoder/mad: pad the input buffer with zero bytes and end of file
libmad requires padding the input buffer with "MAD_BUFFER_GUARD" zero
bytes at the end of the file, or else it is unable to decode the last
frame.

This fixes yet another bug which prevented this plugin from decoding
the last frame, see
https://github.com/MusicPlayerDaemon/MPD/issues/601
2019-08-03 08:32:27 +02:00
Max Kellermann
9b99a9897a decoder/mad: don't count the Xing/LAME metadata frame
The Xing/LAME frame indicates how many frames there are, but that
excludes the initial Xing/LAME frame.  Therefore, it should not be
counted.

This fixes an off-by-one bug which caused the last frame to be
skipped, fixing one part of
https://github.com/MusicPlayerDaemon/MPD/issues/601
2019-08-03 08:25:48 +02:00
Max Kellermann
4f56fdc397 decoder/mad: make "current_frame" zero-based
Increment "current_frame" after processing the frame.
2019-08-03 08:24:25 +02:00
Max Kellermann
c87d6825ec decoder/mad: add API documentation 2019-08-03 08:07:30 +02:00
Max Kellermann
00830a20e3 decoder/mad: convert to class, make almost everything private 2019-08-03 07:52:51 +02:00
Max Kellermann
d39d2874b4 decoder/mad: move code to methods RunDecoder(), RunScan() 2019-08-03 07:49:41 +02:00
Max Kellermann
a0a74951b8 decoder/mad: eliminate attribute "bit_rate"
This also fixes a bug which caused the bit rate to not update after
seeking.
2019-08-03 00:38:45 +02:00
Max Kellermann
779a6855ff decoder/mad: add noexcept 2019-08-03 00:28:59 +02:00
Max Kellermann
f7ed7446ae decoder/mad: use MAD_F_MIN and MAD_F_MAX 2019-08-03 00:27:59 +02:00
Max Kellermann
9d44a6d2ae decoder/mad: use Clamp() 2019-08-03 00:26:57 +02:00
Max Kellermann
10da9ee7ba decoder/mad: refactor local variables in FillBuffer() 2019-08-02 23:19:11 +02:00
Max Kellermann
f9eff31205 decoder/mad: use sizeof(input_buffer) 2019-08-02 23:19:11 +02:00
Max Kellermann
1d74a029a2 decoder/mad: simplify variable initialization in FillBuffer() 2019-08-02 23:19:11 +02:00
Max Kellermann
6b8ca514bb decoder/mad: fix broken log message
Broken since commit f8bfea8bae
2019-08-02 22:58:16 +02:00
Max Kellermann
f51e555154 decoder/mad: change "mp3_" suffix to "mad_" 2019-08-02 22:49:55 +02:00
Max Kellermann
61a3c69a06 decoder/mad: make enums strictly-typed 2019-08-02 22:49:55 +02:00
Max Kellermann
089615a01e decoder/mad: include cleanup 2019-08-02 22:49:55 +02:00
Max Kellermann
52bee8f81f util/StaticFifoBuffer: add GetAvailable() 2019-08-02 22:49:55 +02:00
Max Kellermann
adc25e648f util/StaticFifoBuffer: add constexpr 2019-08-02 22:49:33 +02:00
Max Kellermann
31da8eac9b util/StaticFifoBuffer: add noexcept 2019-08-02 22:49:05 +02:00
Max Kellermann
e00464435b util/Compiler.h: move compiler version checks to meson.build 2019-08-02 15:53:16 +02:00
Diomendius
b81138bda1 Fix JACK plugin outputting only to left channel
The JACK output plugin would not correctly upmix mono input files when exactly 2 output ports were configured. This fixes that.
2019-08-02 15:52:20 +02:00
Max Kellermann
6de088140b lib/xiph/OggVisitor: invoke OnOggPacket() with the "E_O_S" packet
The "end of stream" packet is not special; it contains normal data,
and thus we should pass it to OnOggPacket().

This fixes one part of https://github.com/MusicPlayerDaemon/MPD/issues/601
2019-08-02 14:04:08 +02:00
Max Kellermann
86d0534638 lib/xiph/OggVisitor: more API documentation 2019-08-02 13:56:00 +02:00
Max Kellermann
1033dbca2b playlist/Song: add missing includes 2019-07-29 11:31:30 +02:00
Max Kellermann
b955334882 decoder/opus: ignore case in replay gain tag names
Closes https://github.com/MusicPlayerDaemon/MPD/issues/604
2019-07-29 10:40:37 +02:00
Max Kellermann
90ea3bf985 playlist/Song: support backslash in relative URIs
Closes https://github.com/MusicPlayerDaemon/MPD/issues/607
2019-07-29 09:58:53 +02:00
Max Kellermann
83b0871248 test/test_translate_song: remove unused variable "s1" 2019-07-29 09:52:57 +02:00
Max Kellermann
d8aec4b2dc test/run_decoder: catch StopDecoder
This exception is usually thrown by class DecoderBridge, but the Opus
plugin (ab)uses it as well, so we need to catch it.
2019-07-12 17:49:12 +02:00
Max Kellermann
39b302dcad increment version number to 0.21.12 2019-07-12 17:22:20 +02:00
Max Kellermann
f6125f0c35 release v0.21.11 2019-07-03 15:16:27 +02:00
Max Kellermann
f780ac418a output/alsa: log when generating silence due to slow decoder
MPD used to do that when this code lived in the player thread, but it
was removed by commit 98a7c62d7a4f716d90af6d78e18d1a3b10bc54b3; and
the replacement code in the ALSA output plugin didn't have it.
2019-06-28 18:15:30 +02:00
Max Kellermann
61a72a5d13 output/alsa: schedule a timer to generate silence
Without this timer, DispatchSockets() may disable the
MultiSocketMonitor and if Play() doesn't get called soon, it never
gets a chance to generate silence.  However if Play() gets called,
generating silence isn't necessary anymore...

Resulting from this misdesign (added by commit ccafe3f3cf in 0.21.3),
the silence generator didn't work reliably.
2019-06-28 18:04:49 +02:00
Max Kellermann
0c0a354753 output/alsa: add a new flag "waiting" for xrun management
In DispatchSockets(), when there was not enough data, but enough for
current playback, the method would disable the "active" flag so the
next Play() call would re-enable the MultiSocketMonitor.

This was an abuse of the flag which could result in a crash
in Cancel(), because that method asserts that the period_buffer is
empty, which it may be not.

The solution is to add anther flag called "waiting" which shares some
behavior with the old flag.
2019-06-28 18:04:49 +02:00
Max Kellermann
3c5f860fb8 output/alsa: Cancel() also affects "active" (documentation) 2019-06-28 18:04:49 +02:00
Max Kellermann
3da1fa88d0 output/alsa: fix comment typo 2019-06-28 18:04:49 +02:00
Max Kellermann
fac15aaffb output/alsa: fix comment typo 2019-06-28 14:39:54 +02:00
Max Kellermann
c926021599 output/alsa: always redo DrainInternal() after writing
Draining isn't finished just because the period_buffer has run empty.
It is only finished after snd_pcm_drain() has succeeded.
2019-06-28 09:10:16 +02:00
Max Kellermann
543776d9c9 output/alsa: check PCM state before calling snd_pcm_drain()
Apparently, if snd_pcm_drain() returns EAGAIN, it does not actually
want to be called again; the next call will snd_pcm_drain() will also
return EAGAIN, forever, even though the PCM state has meanwhile
switched to SND_PCM_STATE_SETUP.  This causes a busy loop; to fix
this, we should always check snd_pcm_state() to see if draining is
really required.
2019-06-28 08:55:25 +02:00
Max Kellermann
8bf3f9b874 input/tidal: deprecated because Tidal has changed the protocol
See https://github.com/MusicPlayerDaemon/MPD/issues/545
2019-06-26 23:14:07 +02:00
Max Kellermann
f07f8f7d88 decoder/wildmidi: add fallbacks for libwildmidi<0.4
Fix build breakage from commit ea639269d8
2019-06-26 23:13:23 +02:00
Max Kellermann
39b40ac1fd decoder/wildmidi: remove unused variable wildmidi_domain 2019-06-26 23:10:20 +02:00
Max Kellermann
ea639269d8 decoder/wildmidi: throw PluginUnavailable on WildMidi_Init() error
Closes https://github.com/MusicPlayerDaemon/MPD/issues/589
2019-06-26 22:40:27 +02:00
Max Kellermann
0abaa3ecc5 decoder/wildmidi: throw PluginUnavailable if config file does not exist
This makes the configuration error more visible, possibly addressing
one part of https://github.com/MusicPlayerDaemon/MPD/issues/589
2019-06-26 22:38:40 +02:00
Max Kellermann
c4d3efe71d decoder/List: handle exception PluginUnavailable 2019-06-26 22:02:54 +02:00
Max Kellermann
85e82e3d4d decoder/List: annotate exceptions thrown by DecoderPlugin::Init() 2019-06-26 22:01:45 +02:00
Max Kellermann
f44011519c meson.build: increase protocol version to 0.21.11
Commit 1eae9339f2 added support for
multiple "groups" in the "list" command, and this change allows
clients to detect that this behavior, which had been documented for
several years, is now implemented properly.
2019-06-18 15:35:38 +02:00
Max Kellermann
2c3eeb7194 MusicChunk: pad MusicChunkInfo to a multiple of 8 bytes
Workaround for a regression caused by commit
a06bf388d9, revealing a problem with
discarding odd numer of frames in the DSD_U32 and DoP converters,
causing distortions with DSD_U32 and DoP on 32 bit CPUs.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/469
2019-06-17 21:24:32 +02:00
Max Kellermann
79839db3a3 output/oss: return early if PcmExport::Export() returns empty array
This can happen if the DoP converter doesn't get enough source samples
for one destination quad.  This isn't a critical bug, because the OSS
plugin doesn't support DoP yet, but it's good to be prepared.
2019-06-17 21:07:30 +02:00
Max Kellermann
d478bdda8e pcm/Export: document that Export() may return an empty buffer 2019-06-17 21:07:29 +02:00
Max Kellermann
1eae9339f2 db/Interface: CollectUniqueTags() allows multiple "groups"
Instead of passing tag and group, pass an array of tags.  To support a
nested return value, return a nested std::map of std::maps.  Each key
specifies the tag value, and each value may be another nesting level.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/408
2019-06-16 10:39:29 +02:00
Max Kellermann
923c1b6220 doc/include: remove obsolete DocBook fragment 2019-06-11 09:29:20 +02:00
Max Kellermann
09884e608b increment version number to 0.21.11 2019-06-11 09:29:05 +02:00
Max Kellermann
e239009295 release v0.21.10 2019-06-05 22:32:32 +02:00
Max Kellermann
3fae2150f5 decoder/OpusReader: return StringView
Since we now don't duplicate all items, we can easily remove the 64kB
limit from OpusReader::ReadString() and instead silently ignore and
skip all strings which are longer than 4 kB.

This fixes a tag duplication bug with Opus file containing a very long
`METADATA_BLOCK_PICTURE` tag, which occurred because the Opus plugin
returned false after parsing all tags, and then the MPD core fell back
to FFmpeg which scanned the tags again.
2019-06-05 22:19:35 +02:00
cathugger
f9ca2f52c1 output/httpd: reject some well-known request paths
Return `404 not found` for some common well-known paths, as clients requesting them usually do that automatically and don't expect endless audio stram.

Closes 
2019-06-05 21:53:46 +02:00
cathugger
4b81cf0c2c output/httpd: use strncmp instead of memcmp
memcmp use may result in out of bounds access
2019-06-05 21:53:46 +02:00
Max Kellermann
e7acbf112c output/httpd: fix indent 2019-06-05 21:53:43 +02:00
Max Kellermann
304d45b551 Revert "player/Thread: remove unnecessary "pipe" check"
This reverts commit ff3e2c0514.  The
check was necessary, after all, because this is what checked whether
the decoder had finished the current or the next song.

> The "queued" flag can only possibly be set if the decoder is still
> decoding the current song or if the decoder is stopped.

That was wrong because ProcessCommand() sets `queued=true` and also
starts the decoder (if it was idle).

> This is also what the following assert() checks.

That was also wrong, because the assert() has two conditions.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/566
2019-05-31 17:23:12 +02:00
Max Kellermann
0f488dcecf doc/protocol.rst: binary responses do have a newline after all
Closes https://github.com/MusicPlayerDaemon/MPD/issues/568
2019-05-31 16:47:41 +02:00
Max Kellermann
17039aec70 doc/user.rst: more heading corrections
According to http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#sections
2019-05-31 16:30:06 +02:00
Max Kellermann
fb6cb07912 doc/developer.rst: remove outdated section about the clang static analyzer 2019-05-31 16:27:43 +02:00
Max Kellermann
e9e0e02db3 doc/user.rst: use ".. note:" 2019-05-31 16:26:52 +02:00
Max Kellermann
03507037e8 increment version number to 0.21.10 2019-05-31 16:16:56 +02:00
Max Kellermann
66a8fac25e release v0.21.9 2019-05-20 17:10:58 +02:00
Max Kellermann
1b902e00b4 doc/protocol.rst: several clarifications
Closes https://github.com/MusicPlayerDaemon/MPD/issues/340
2019-05-20 17:06:20 +02:00
Max Kellermann
923e66738c player/Thread: fix "single" mode race condition
If the decoder finishes decoding the current song between the two
IsIdle() checks, MPD stops playback instead of starting the decoder
for the next song.

This is usually not visible problem, because the main thread restarts
it via playlist::ResumePlayback(), but that way it, ignores "single"
mode.

As a workaround, this commit adds another "queued" check which
re-enters the player loop and checks again whether to start the
decoder.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/556
2019-05-20 16:22:01 +02:00
Max Kellermann
ff3e2c0514 player/Thread: remove unnecessary "pipe" check
The "queued" flag can only possibly be set if the decoder is still
decoding the current song or if the decoder is stopped.  This is also
what the following assert() checks.  This check was not necessary.
2019-05-20 16:20:59 +02:00
Max Kellermann
6922a2f55e input/buffered: check error in IsAvailable() 2019-05-17 12:43:45 +02:00
Max Kellermann
ca5a400dbe input/buffered: rethrow read_error in Check() 2019-05-16 22:08:33 +02:00
Max Kellermann
63fe4d1d17 input/buffered: wake up client thread on seek error 2019-05-16 22:05:25 +02:00
Max Kellermann
ca06d9d3bf input/buffered: fix deadlock bug 2019-05-16 21:11:03 +02:00
Max Kellermann
ed2db04f43 doc/mpd.conf.5: remove ALSA specific documentation
ALSA is just one out of many output plugins, and detailed plugin
documentation should only live in the user manual, without having
duplicates in the (brief) manpage.

Also move "mixer_type" to the "optional audio output parameters"
section; it is a generic option, not specific to ALSA.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/552
2019-05-13 22:51:48 +02:00
Max Kellermann
de0afa0e08 doc/mpd.conf.5: fix section indent 2019-05-13 22:51:45 +02:00
Max Kellermann
f0d3227d7b doc/protocol.rst: add references to audio_output_format 2019-05-13 22:46:23 +02:00
Max Kellermann
fb07a7cecc doc/user.rst: move audio format spec to section "Global Audio Format" 2019-05-13 22:39:49 +02:00
Max Kellermann
c6b08a4d48 doc/user.rst: add reference to audio_output_format 2019-05-13 22:39:44 +02:00
Max Kellermann
040e87ad8d doc/user.rst: more markup 2019-05-13 22:36:19 +02:00
Max Kellermann
d5521ead56 doc/user.rst: add missing space 2019-05-13 22:36:19 +02:00
Max Kellermann
f8468451c9 android/AndroidManifest.xml: increment versionCode after hotfix upload 2019-05-04 13:25:05 +02:00
Max Kellermann
65df6ca14e android/Settings: request READ_EXTERNAL_STORAGE permission
Using this API function requires SDK level 23.
2019-05-04 07:29:41 +02:00
Max Kellermann
36dec47bf7 android/build.py: link ARMv7 binary with libunwind
Fixes nullptr dereference when an exception gets thrown because there
is no ".eh_frame" section for unwinding.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/543
2019-05-03 20:15:50 +02:00
Max Kellermann
478cedcadf increment version number to 0.21.9 2019-05-03 20:15:33 +02:00
Max Kellermann
cabcbb059d release v0.21.8 2019-04-23 14:35:14 +02:00
Max Kellermann
5e21b2db3c doc/protocol.rst: "list file" is deprecated
Closes https://github.com/MusicPlayerDaemon/MPD/issues/526
2019-04-23 14:29:42 +02:00
Max Kellermann
3a0d6d96c1 input/smbclient: wrap in MaybeBufferedInputStream
This enables the input buffer for remote files and caches file
contents in MPD.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/376
2019-04-23 14:08:27 +02:00
Max Kellermann
f39d2d33c0 python/build/libs.py: upgrade Boost to 1.70.0 2019-04-23 14:08:27 +02:00
Max Kellermann
ead3dc6a92 LocateUri: pass URI plugin kind, optionally disables plugin verify
Commit b3a458338a added a LocateUri()
call to several playlist commands, which applied InputPlugin URI
scheme verification to playlist URIs.  This broke the SoundCloud
playlist plugin which uses "soundcloud://" URIs for which no input
plugin exists.

This commit allows the caller to specify the kind of plugin which
shall be used to verify the URI.  Right now, only "input" is
implemented; "storage" uses the "input" verification for now; and
"playlist" has no verification at all (for now).

Closes https://github.com/MusicPlayerDaemon/MPD/issues/528
2019-04-18 10:03:15 +02:00
Max Kellermann
7d814cc899 neighbor/smbclient: fix double smbc_closedir() call
There is already one call in ReadServers(), which is the correct place
to do it.
2019-04-18 09:40:56 +02:00
Max Kellermann
f5b4606c09 .travis.yml: switch to another PPA for a newer ninja version
Fixes Travis failure with Meson 0.50:

 ERROR: Could not detect Ninja v1.5 or newer
2019-04-18 09:40:30 +02:00
Max Kellermann
d6dbf64efb CommandLine: fix another build failure with -Ddatabase=false
Split several printf() calls to make it easier to deal with all those
#ifdefs.
2019-04-18 09:20:12 +02:00
Eugene Gorodinsky
8d18b4c24b Fix meson.build to work properly with '-Ddatabase=false' 2019-04-18 08:55:13 +02:00
Max Kellermann
fe8621906d systemd: add user socket unit
Copy the system socket unit to the "user" directory.

Closes https://github.com/MusicPlayerDaemon/MPD/issues/530
2019-04-10 16:37:13 +02:00
Max Kellermann
b4fcbdb235 systemd/socket: use %t instead of hard-coding /run
This allows using the file as a user unit, where "%t" maps to
"$XDG_RUNTIME_DIR".

Proposed in https://github.com/MusicPlayerDaemon/MPD/issues/530
2019-04-10 16:34:40 +02:00
Max Kellermann
f4b5a28596 doc/protocol: mention that stickers are only implemented for songs
Closes https://github.com/MusicPlayerDaemon/MPD/issues/524
2019-04-10 16:33:17 +02:00
Max Kellermann
6cbd77fc57 doc/protocol.rst: mention "in seconds" where it was missing
Closes https://github.com/MusicPlayerDaemon/MPD/issues/523
2019-04-10 16:30:26 +02:00
cotko
1bc78e9f2c Fid move doc args 2019-04-10 13:16:58 +02:00
Max Kellermann
cb6282e0a7 doc/developer.rst: remove mailing list, refer to GitHub instead 2019-04-10 11:36:03 +02:00
Max Kellermann
f6941f9a44 event/SocketMonitor: don't cancel if OnSocketReady() returns false
Expect OnSocketReady() to cancel events.  If it returns false, the
SocketMonitor may be destructed already.  This fixes a use-after-free
bug in the "httpd" output plugin.
2019-04-04 10:24:58 +02:00
Max Kellermann
d2eb4df8fc event/{Fully,}BufferedSocket: add more API documentation 2019-04-04 10:24:58 +02:00
Max Kellermann
df33a898d7 zeroconf/Bonjour: fix OnSocketReady() return value
Keep the SocketMonitor registered.  This wrong return value was added
6 years ago in commit 72cf8dd8a0, andd
apparently, nobody ever noticed.
2019-04-04 10:24:29 +02:00
Max Kellermann
325c7b8e8b output/httpd: close client connection on error
This missing piece probably never really hurt, because
HttpdClient::OnSocketClosed() would be called right after a socket
error, but it's better to be explicit about closing on error.
2019-04-04 09:39:22 +02:00
Max Kellermann
380656d8c9 output/httpd: add missing mutex lock 2019-04-03 22:53:03 +02:00
Max Kellermann
9111bc2c21 output/httpd: add more API documentation about locking 2019-04-03 22:49:25 +02:00
Max Kellermann
37b54179d8 net/IPv[46]Address: add cast to void* to fix GCC9 build failure
Fixes:

 src/net/IPv4Address.hxx: In member function 'constexpr IPv4Address::operator SocketAddress() const':
 src/net/IPv4Address.hxx:171:24: error: a reinterpret_cast is not a constant expression
   171 |   return SocketAddress((const struct sockaddr *)&address,
       |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 src/net/IPv6Address.hxx: In member function 'constexpr IPv6Address::operator SocketAddress() const':
 src/net/IPv6Address.hxx:138:24: error: a reinterpret_cast is not a constant expression
   138 |   return SocketAddress((const struct sockaddr *)&address,
       |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Closes https://github.com/MusicPlayerDaemon/MPD/issues/522
2019-04-03 16:59:53 +02:00
Max Kellermann
511826763a increment version number to 0.21.8 2019-04-03 12:27:18 +02:00
87 changed files with 1396 additions and 936 deletions
.travis.ymlNEWS
android
doc
meson.build
python/build
src
systemd
test

@@ -9,7 +9,7 @@ matrix:
sources:
- ubuntu-toolchain-r-test
- sourceline: 'ppa:mhier/libboost-latest'
- sourceline: 'ppa:saiarcot895/chromium-dev' # for ninja-build
- sourceline: 'ppa:mstipicevic/ninja-build-1-7-2'
- sourceline: 'ppa:deadsnakes/ppa' # for Python 3.7 (required by Meson)
packages:
- g++-6
@@ -34,7 +34,7 @@ matrix:
sources:
- ubuntu-toolchain-r-test
- sourceline: 'ppa:mhier/libboost-latest'
- sourceline: 'ppa:saiarcot895/chromium-dev' # for ninja-build
- sourceline: 'ppa:mstipicevic/ninja-build-1-7-2'
- sourceline: 'ppa:deadsnakes/ppa' # for Python 3.7 (required by Meson)
packages:
- g++-8

82
NEWS

@@ -1,3 +1,85 @@
ver 0.21.15 (2019/09/25)
* decoder
- dsdiff, dsf: fix displayed bit rate
- mpcdec: fix bogus ReplayGain values
* output
- solaris: fix build with glibc 2.30
ver 0.21.14 (2019/08/21)
* decoder
- sidplay: show track durations in database
- sidplay: convert tag values from Windows-1252 charset
- sidplay: strip text from "Date" tag
* player
- fix crash after song change
- fix seek position after restarting the decoder
* protocol
- include command name in error responses
ver 0.21.13 (2019/08/06)
* input
- cdio_paranoia: require libcdio-paranoia 10.2+0.93+1
* decoder
- mad: fix crackling sound (0.21.12 regression)
* output
- jack: improved Windows compatibility
ver 0.21.12 (2019/08/03)
* decoder
- mad: update bit rate after seeking
- mad: fix several bugs preventing the plugin from decoding the last frame
- opus: ignore case in replay gain tag names
- opus, vorbis: decode the "end of stream" packet
* output
- jack: fix mono-to-stereo conversion
* player
- don't restart unseekable song after failed seek attempt
* Windows
- support backslash in relative URIs loaded from playlists
ver 0.21.11 (2019/07/03)
* input
- tidal: deprecated because Tidal has changed the protocol
* decoder
- wildmidi: log error if library initialization fails
* output
- alsa: fix busy loop while draining
- alsa: fix missing drain call
- alsa: improve xrun-avoiding silence generator
- alsa: log when generating silence due to slow decoder
- alsa, osx: fix distortions with DSD_U32 and DoP on 32 bit CPUs
* protocol
- fix "list" with multiple "group" levels
ver 0.21.10 (2019/06/05)
* decoder
- opus: fix duplicate tags
* output
- httpd: reject some well-known URIs
* fix crash bug (0.21.9 regression)
ver 0.21.9 (2019/05/20)
* input
- buffer: fix deadlock bug
* Android
- fix crash on ARMv7
- request storage permission on Android 6+
* fix spurious "single" mode bug
ver 0.21.8 (2019/04/23)
* input
- smbclient: download to buffer instead of throttling transfer
* output
- httpd: add missing mutex lock
- httpd: fix use-after-free bug
* playlist
- soundcloud: fix "Unsupported URI scheme" (0.21.6 regression)
* fix Bonjour bug
* fix build failure with GCC 9
* fix build failure with -Ddatabase=false
* systemd: add user socket unit
* doc: "list file" is deprecated
ver 0.21.7 (2019/04/03)
* input
- qobuz/tidal: scan tags when loading a playlist

@@ -2,8 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.musicpd"
android:installLocation="auto"
android:versionCode="29"
android:versionName="0.21.7">
android:versionCode="38"
android:versionName="0.21.15">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="26"/>

@@ -138,6 +138,12 @@ class AndroidNdkToolchain:
libstdcxx_ldflags = libstdcxx_flags + ' -L' + libcxx_libs_path
libstdcxx_libs = '-lc++_static -lc++abi'
if self.is_armv7:
# On 32 bit ARM, clang generates no ".eh_frame" section;
# instead, the LLVM unwinder library is used for unwinding
# the stack after a C++ exception was thrown
libstdcxx_libs += ' -lunwind'
if use_cxx:
self.cxxflags += ' ' + libstdcxx_cxxflags
self.ldflags += ' ' + libstdcxx_ldflags

@@ -6,7 +6,7 @@ android_sdk = get_option('android_sdk')
android_abi = get_option('android_abi')
android_sdk_build_tools_version = '27.0.0'
android_sdk_platform = 'android-21'
android_sdk_platform = 'android-23'
android_build_tools_dir = join_paths(android_sdk, 'build-tools', android_sdk_build_tools_version)
android_sdk_platform_dir = join_paths(android_sdk, 'platforms', android_sdk_platform)

@@ -21,10 +21,12 @@ package org.musicpd;
import java.util.LinkedList;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@@ -178,6 +180,14 @@ public class Settings extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
/* TODO: this sure is the wrong place to request
permissions - it will cause MPD to quit
immediately; we should request permissions when we
need them, but implementing that is complicated, so
for now, we do it here to give users a quick
solution for the problem */
requestAllPermissions();
setContentView(R.layout.settings);
mRunButton = (ToggleButton) findViewById(R.id.run);
mRunButton.setOnCheckedChangeListener(mOnRunChangeListener);
@@ -203,6 +213,31 @@ public class Settings extends Activity {
super.onCreate(savedInstanceState);
}
private void checkRequestPermission(String permission) {
if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED)
return;
try {
this.requestPermissions(new String[]{permission}, 0);
} catch (Exception e) {
Log.e(TAG, "requestPermissions(" + permission + ") failed",
e);
}
}
private void requestAllPermissions() {
if (android.os.Build.VERSION.SDK_INT < 23)
/* we don't need to request permissions on
this old Android version */
return;
/* starting with Android 6.0, we need to explicitly
request all permissions before using them;
mentioning them in the manifest is not enough */
checkRequestPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
}
private void connectClient() {
mClient = new Main.Client(this, new Main.Client.Callback() {

@@ -38,7 +38,7 @@ author = 'Max Kellermann'
# built documents.
#
# The short X.Y version.
version = '0.21.7'
version = '0.21.15'
# The full version, including alpha/beta/rc tags.
release = version

@@ -2,12 +2,12 @@ Developer's Manual
##################
Introduction
============
************
This is a guide for those who wish to hack on the MPD source code. MPD is an open project, and we are always happy about contributions. So far, more than 150 people have contributed patches. This document is work in progress. Most of it may be incomplete yet. Please help!
Code Style
==========
**********
* indent with tabs (width 8)
* don't write CPP when you can write C++: use inline functions and constexpr instead of macros
@@ -18,7 +18,6 @@ Code Style
* classes and functions names use CamelCase; variables are lower-case with words separated by underscore
Some example code:
~~~~~~~~~~~~~~~~~~
.. code-block:: c
@@ -33,7 +32,7 @@ Some example code:
}
Hacking The Source
==================
******************
MPD sources are managed in a git repository on
`Github <https://github.com/MusicPlayerDaemon/>`_.
@@ -59,7 +58,7 @@ possible, to be sure that you don't break any disabled code.
Don't mix several changes in one single patch. Create a separate patch for every change. Tools like :program:`stgit` help you with that. This way, we can review your patches more easily, and we can pick the patches we like most first.
Basic stgit usage
-----------------
=================
stgit allows you to create a set of patches and refine all of them: you can go back to any patch at any time, and re-edit it (both the code and the commit message). You can reorder patches and insert new patches at any position. It encourages creating separate patches for tiny changes.
@@ -94,35 +93,7 @@ When the whole patch series is finished, convert stgit patches to git commits:
stg commit
Submitting Patches
==================
******************
Send your patches to the mailing list:
Email: `mpd-devel <mpd-devel@musicpd.org>`_
:program:`git pull` requests are preferred.
Development Tools
=================
Clang Static Analyzer
---------------------
The `static analyzer <http://clang-analyzer.llvm.org/>`_ is a tool that helps find bugs. To run it on the MPD code base, install LLVM and clang. configure MPD to use clang:
.. code-block:: sh
./configure --enable-debug CXX=clang++ CC=clang ...
It is recommended to use :code:`--enable-debug`, because the analyzer
takes advantage of :dfn:`assert()` calls, which are only enabled in
the debug build.
Now run the analyzer:
.. code-block:: sh
scan-build --use-c++=clang++ --use-cc=clang make
The options :code:`--use-c++` and :code:`--use-cc` are necessary
because it invokes :command:`cc` for actually compiling the sources by
default. That breaks, because MPD requires a C99 compiler.
Submit pull requests on GitHub:
https://github.com/MusicPlayerDaemon/MPD/pulls

@@ -1,165 +0,0 @@
<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE itemizedlist PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<itemizedlist>
<listitem>
<para>
<varname>artist</varname>: the artist name. Its meaning is not
well-defined; see <varname>composer</varname> and
<varname>performer</varname> for more specific tags.
</para>
</listitem>
<listitem>
<para>
<varname>artistsort</varname>: same as
<varname>artist</varname>, but for sorting. This usually omits
prefixes such as "The".
</para>
</listitem>
<listitem>
<para>
<varname>album</varname>: the album name.
</para>
</listitem>
<listitem>
<para>
<varname>albumsort</varname>: same as <varname>album</varname>,
but for sorting.
</para>
</listitem>
<listitem>
<para>
<varname>albumartist</varname>: on multi-artist albums, this is
the artist name which shall be used for the whole album. The
exact meaning of this tag is not well-defined.
</para>
</listitem>
<listitem>
<para>
<varname>albumartistsort</varname>: same as
<varname>albumartist</varname>, but for sorting.
</para>
</listitem>
<listitem>
<para>
<varname>title</varname>: the song title.
</para>
</listitem>
<listitem>
<para>
<varname>track</varname>: the decimal track number within the
album.
</para>
</listitem>
<listitem>
<para>
<varname>name</varname>: a name for this song. This is not the
song title. The exact meaning of this tag is not well-defined.
It is often used by badly configured internet radio stations
with broken tags to squeeze both the artist name and the song
title in one tag.
</para>
</listitem>
<listitem>
<para>
<varname>genre</varname>: the music genre.
</para>
</listitem>
<listitem>
<para>
<varname>date</varname>: the song's release date. This is
usually a 4-digit year.
</para>
</listitem>
<listitem>
<para>
<varname>composer</varname>: the artist who composed the song.
</para>
</listitem>
<listitem>
<para>
<varname>performer</varname>: the artist who performed the song.
</para>
</listitem>
<listitem>
<para>
<varname>comment</varname>: a human-readable comment about this
song. The exact meaning of this tag is not well-defined.
</para>
</listitem>
<listitem>
<para>
<varname>disc</varname>: the decimal disc number in a multi-disc
album.
</para>
</listitem>
<listitem>
<para>
<varname>musicbrainz_artistid</varname>: the artist id in the
<ulink
url="https://picard.musicbrainz.org/docs/mappings/">MusicBrainz</ulink>
database.
</para>
</listitem>
<listitem>
<para>
<varname>musicbrainz_albumid</varname>: the album id in the
<ulink
url="https://picard.musicbrainz.org/docs/mappings/">MusicBrainz</ulink>
database.
</para>
</listitem>
<listitem>
<para>
<varname>musicbrainz_albumartistid</varname>: the album artist
id in the <ulink
url="https://picard.musicbrainz.org/docs/mappings/">MusicBrainz</ulink>
database.
</para>
</listitem>
<listitem>
<para>
<varname>musicbrainz_trackid</varname>: the track id in the
<ulink
url="https://picard.musicbrainz.org/docs/mappings/">MusicBrainz</ulink>
database.
</para>
</listitem>
<listitem>
<para>
<varname>musicbrainz_releasetrackid</varname>: the release track
id in the <ulink
url="https://picard.musicbrainz.org/docs/mappings/">MusicBrainz</ulink>
database.
</para>
</listitem>
<listitem>
<para>
<varname>musicbrainz_workid</varname>: the work id in the
<ulink
url="https://picard.musicbrainz.org/docs/mappings/">MusicBrainz</ulink>
database.
</para>
</listitem>
</itemizedlist>

@@ -140,7 +140,6 @@ of database.
.B auto_update_depth <N>
Limit the depth of the directories being watched, 0 means only watch
the music directory itself. There is no limit by default.
.TP
.SH REQUIRED AUDIO OUTPUT PARAMETERS
.TP
.B type <type>
@@ -164,57 +163,12 @@ Specifies how replay gain is applied. The default is "software",
which uses an internal software volume control. "mixer" uses the
configured (hardware) mixer control. "none" disables replay gain on
this audio output.
.SH OPTIONAL ALSA OUTPUT PARAMETERS
.TP
.B device <dev>
This specifies the device to use for audio output. The default is "default".
.TP
.B mixer_type <hardware, software or none>
Specifies which mixer should be used for this audio output: the
hardware mixer (available for ALSA, OSS and PulseAudio), the software
mixer or no mixer ("none"). By default, the hardware mixer is used
for devices which support it, and none for the others.
.TP
.B mixer_device <mixer dev>
This specifies which mixer to use. The default is "default". To use
the second sound card in a system, use "hw:1".
.TP
.B mixer_control <mixer ctrl>
This specifies which mixer control to use (sometimes referred to as
the "device"). The default is "PCM". Use "amixer scontrols" to see
the list of possible controls.
.TP
.B mixer_index <mixer index>
A number identifying the index of the named mixer control. This is
probably only useful if your alsa device has more than one
identically\-named mixer control. The default is "0". Use "amixer
scontrols" to see the list of controls with their indexes.
.TP
.B auto_resample <yes or no>
Setting this to "no" disables ALSA's software resampling, if the
hardware does not support a specific sample rate. This lets MPD do
the resampling. "yes" is the default and allows ALSA to resample.
.TP
.B auto_channels <yes or no>
Setting this to "no" disables ALSA's channel conversion, if the
hardware does not support a specific number of channels. Default: "yes".
.TP
.B auto_format <yes or no>
Setting this to "no" disables ALSA's sample format conversion, if the
hardware does not support a specific sample format. Default: "yes".
.TP
.B buffer_time <time in microseconds>
This sets the length of the hardware sample buffer in microseconds. Increasing
it may help to reduce or eliminate skipping on certain setups. Most users do
not need to change this. The default is 500000 microseconds (0.5 seconds).
.TP
.B period_time <time in microseconds>
This sets the time between hardware sample transfers in microseconds.
Increasing this can reduce CPU usage while lowering it can reduce underrun
errors on bandwidth-limited devices. Some users have reported good results
with this set to 50000, but not all devices support values this high. Most
users do not need to change this. The default is 256000000 / sample_rate(kHz),
or 5804 microseconds for CD-quality audio.
.SH FILES
.TP
.BI ~/.mpdconf

@@ -4,10 +4,10 @@ Plugin reference
.. _database_plugins:
Database plugins
----------------
================
simple
~~~~~~
------
The default plugin. Stores a copy of the database in memory. A file is used for permanent storage.
@@ -25,7 +25,7 @@ The default plugin. Stores a copy of the database in memory. A file is used for
- Compress the database file using gzip? Enabled by default (if built with zlib).
proxy
~~~~~
-----
Provides access to the database of another :program:`MPD` instance using libmpdclient. This is useful when you run mount the music directory via NFS/SMB, and the file server already runs a :program:`MPD` instance. Only the file server needs to update the database.
@@ -45,30 +45,30 @@ Provides access to the database of another :program:`MPD` instance using libmpdc
- Send TCP keepalive packets to the "master" :program:`MPD` instance? This option can help avoid certain firewalls dropping inactive connections, at the expensive of a very small amount of additional network traffic. Disabled by default.
upnp
~~~~
----
Provides access to UPnP media servers.
Storage plugins
---------------
===============
local
~~~~~
-----
The default plugin which gives :program:`MPD` access to local files. It is used when music_directory refers to a local directory.
curl
~~~~
----
A WebDAV client using libcurl. It is used when :code:`music_directory` contains a http:// or https:// URI, for example :samp:`https://the.server/dav/`.
smbclient
~~~~~~~~~
---------
Load music files from a SMB/CIFS server. It is used when :code:`music_directory` contains a smb:// URI, for example :samp:`smb://myfileserver/Music`.
nfs
~~~
---
Load music files from a NFS server. It is used when :code:`music_directory` contains a nfs:// URI according to RFC2224, for example :samp:`nfs://servername/path`.
@@ -81,7 +81,7 @@ This plugin uses libnfs, which supports only NFS version 3. Since :program:`MPD`
Don't fear: "insecure" does not mean that your NFS server is insecure. A few decades ago, people thought the concept of "privileged ports" would make network services "secure", which was a fallacy. The absence of this obsolete "security" measure means little.
udisks
~~~~~~
------
Mount file systems (e.g. USB sticks or other removable media) using
the udisks2 daemon via D-Bus. To obtain a valid udisks2 URI, consult
@@ -106,29 +106,30 @@ MPD user.
.. _neighbor_plugin:
Neighbor plugins
----------------
================
smbclient
~~~~~~~~~
---------
Provides a list of SMB/CIFS servers on the local network.
udisks
~~~~~~
------
Queries the udisks2 daemon via D-Bus and obtain a list of file systems (e.g. USB sticks or other removable media).
upnp
~~~~
----
Provides a list of UPnP servers on the local network.
.. _input_plugins:
Input plugins
-------------
=============
alsa
~~~~
----
Allows :program:`MPD` on Linux to play audio directly from a soundcard using the scheme alsa://. Audio is formatted as 44.1 kHz 16-bit stereo (CD format). Examples:
@@ -141,7 +142,7 @@ Allows :program:`MPD` on Linux to play audio directly from a soundcard using the
mpc add alsa://hw:1,0 plays audio from device hw:1,0 cdio_paranoia
cdio_paranoia
~~~~~~~~~~~~~
-------------
Plays audio CDs using libcdio. The URI has the form: "cdda://[DEVICE][/TRACK]". The simplest form cdda:// plays the whole disc in the default drive.
@@ -157,7 +158,7 @@ Plays audio CDs using libcdio. The URI has the form: "cdda://[DEVICE][/TRACK]".
- Request CDParanoia cap the extraction speed to Nx normal CD audio rotation speed, keeping the drive quiet.
curl
~~~~
----
Opens remote files or streams over HTTP using libcurl.
@@ -179,22 +180,22 @@ Note that unless overridden by the below settings (e.g. by setting them to a bla
- Verify the certificate's name against host? `More information <http://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYHOST.html>`_.
ffmpeg
~~~~~~
------
Access to various network protocols implemented by the FFmpeg library: gopher://, rtp://, rtsp://, rtmp://, rtmpt://, rtmps://
file
~~~~
----
Opens local files
mms
~~~
---
Plays streams with the MMS protocol using `libmms <https://launchpad.net/libmms>`_.
nfs
~~~
---
Allows :program:`MPD` to access files on NFSv3 servers without actually mounting them (i.e. in userspace, without help from the kernel's VFS layer). All URIs with the nfs:// scheme are used according to RFC2224. Example:
@@ -205,7 +206,7 @@ Allows :program:`MPD` to access files on NFSv3 servers without actually mounting
Note that this usually requires enabling the "insecure" flag in the server's /etc/exports file, because :program:`MPD` cannot bind to so-called "privileged" ports. Don't fear: this will not make your file server insecure; the flag was named in a time long ago when privileged ports were thought to be meaningful for security. By today's standards, NFSv3 is not secure at all, and if you believe it is, you're already doomed.
smbclient
~~~~~~~~~
---------
Allows :program:`MPD` to access files on SMB/CIFS servers (e.g. Samba or Microsoft Windows). All URIs with the smb:// scheme are used. Example:
@@ -214,7 +215,7 @@ Allows :program:`MPD` to access files on SMB/CIFS servers (e.g. Samba or Microso
mpc add smb://servername/sharename/filename.ogg
qobuz
~~~~~
-----
Play songs from the commercial streaming service Qobuz. It plays URLs in the form qobuz://track/ID, e.g.:
@@ -240,10 +241,15 @@ Play songs from the commercial streaming service Qobuz. It plays URLs in the for
- The `Qobuz format identifier <https://github.com/Qobuz/api-documentation/blob/master/endpoints/track/getFileUrl.md#parameters>`_, i.e. a number which chooses the format and quality to be requested from Qobuz. The default is "5" (320 kbit/s MP3).
tidal
~~~~~
-----
Play songs from the commercial streaming service `Tidal <http://tidal.com/>`_. It plays URLs in the form tidal://track/ID, e.g.:
.. warning::
This plugin is currently defunct because Tidal has changed the
protocol and decided not to share documentation.
.. code-block:: none
mpc add tidal://track/59727857
@@ -266,10 +272,10 @@ Play songs from the commercial streaming service `Tidal <http://tidal.com/>`_. I
.. _decoder_plugins:
Decoder plugins
---------------
===============
adplug
~~~~~~
------
Decodes AdLib files using libadplug.
@@ -283,17 +289,17 @@ Decodes AdLib files using libadplug.
- The sample rate that shall be synthesized by the plugin. Defaults to 48000.
audiofile
~~~~~~~~~
---------
Decodes WAV and AIFF files using libaudiofile.
faad
~~~~
----
Decodes AAC files using libfaad.
ffmpeg
~~~~~~
------
Decodes various codecs using FFmpeg.
@@ -309,12 +315,12 @@ Decodes various codecs using FFmpeg.
- Sets the FFmpeg muxer option probesize, which specifies probing size in bytes, i.e. the size of the data to analyze to get stream information. The `FFmpeg formats documentation <https://ffmpeg.org/ffmpeg-formats.html>`_ has more information.
flac
~~~~
----
Decodes FLAC files using libFLAC.
dsdiff
~~~~~~
------
Decodes DFF files containing DSDIFF data (e.g. SACD rips).
@@ -328,12 +334,12 @@ Decodes DFF files containing DSDIFF data (e.g. SACD rips).
- Decode the least significant bit first. Default is no.
dsf
~~~
---
Decodes DSF files containing DSDIFF data (e.g. SACD rips).
fluidsynth
~~~~~~~~~~
----------
MIDI decoder based on `FluidSynth <http://www.fluidsynth.org/>`_.
@@ -349,7 +355,7 @@ MIDI decoder based on `FluidSynth <http://www.fluidsynth.org/>`_.
- The absolute path of the soundfont file. Defaults to :file:`/usr/share/sounds/sf2/FluidR3_GM.sf2`.
gme
~~~
---
Video game music file emulator based on `game-music-emu <https://bitbucket.org/mpyne/game-music-emu/wiki/Home>`_.
@@ -363,7 +369,7 @@ Video game music file emulator based on `game-music-emu <https://bitbucket.org/m
- Enable more accurate sound emulation.
hybrid_dsd
~~~~~~~~~~
----------
`Hybrid-DSD
<http://dsdmaster.blogspot.de/p/bitperfect-introduces-hybrid-dsd-file.html>`_
@@ -386,12 +392,12 @@ of the file is better.
- This specifies whether to support gapless playback of MP3s which have the necessary headers. Useful if your MP3s have headers with incorrect information. If you have such MP3s, it is highly recommended that you fix them using `vbrfix <http://www.willwap.co.uk/Programs/vbrfix.php>`_ instead of disabling gapless MP3 playback. The default is to support gapless MP3 playback.
mad
~~~
---
Decodes MP3 files using `libmad <http://www.underbit.com/products/mad/>`_.
mikmod
~~~~~~
------
Module player based on `MikMod <http://mikmod.sourceforge.net/>`_.
@@ -407,7 +413,7 @@ Module player based on `MikMod <http://mikmod.sourceforge.net/>`_.
- Sets the sample rate generated by libmikmod. Default is 44100.
modplug
~~~~~~~
-------
Module player based on MODPlug.
@@ -421,27 +427,27 @@ Module player based on MODPlug.
- Number of times to loop the module if it uses backward loops. Default is 0 which prevents looping. -1 loops forever.
mpcdec
~~~~~~
------
Decodes Musepack files using `libmpcdec <http://www.musepack.net/>`_.
mpg123
~~~~~~
------
Decodes MP3 files using `libmpg123 <http://www.mpg123.de/>`_.
opus
~~~~
----
Decodes Opus files using `libopus <http://www.opus-codec.org/>`_.
pcm
~~~
---
Read raw PCM samples. It understands the "audio/L16" MIME type with parameters "rate" and "channels" according to RFC 2586. It also understands the MPD-specific MIME type "audio/x-mpd-float".
sidplay
~~~~~~~
-------
C64 SID decoder based on `libsidplayfp <https://sourceforge.net/projects/sidplay-residfp/>`_ or `libsidplay2 <https://sourceforge.net/projects/sidplay2/>`_.
@@ -463,23 +469,23 @@ C64 SID decoder based on `libsidplayfp <https://sourceforge.net/projects/sidplay
- Only libsidplayfp. Absolute path to basic rom image file.
sndfile
~~~~~~~
-------
Decodes WAV and AIFF files using `libsndfile <http://www.mega-nerd.com/libsndfile/>`_.
vorbis
~~~~~~
------
Decodes Ogg-Vorbis files using `libvorbis <http://www.xiph.org/ogg/vorbis/>`_.
wavpack
~~~~~~~
-------
Decodes WavPack files using `libwavpack <http://www.wavpack.com/>`_.
wildmidi
~~~~~~~~
--------
MIDI decoder based on `libwildmidi <http://www.mindwerks.net/projects/wildmidi/>`_.
@@ -495,10 +501,11 @@ MIDI decoder based on `libwildmidi <http://www.mindwerks.net/projects/wildmidi/>
.. _encoder_plugins:
Encoder plugins
---------------
===============
flac
~~~~
----
Encodes into `FLAC <https://xiph.org/flac/>`_ (lossless).
.. list-table::
@@ -511,7 +518,7 @@ Encodes into `FLAC <https://xiph.org/flac/>`_ (lossless).
- Sets the libFLAC compression level. The levels range from 0 (fastest, least compression) to 8 (slowest, most compression).
lame
~~~~
----
Encodes into MP3 using the `LAME <http://lame.sourceforge.net/>`_ library.
@@ -527,12 +534,12 @@ Encodes into MP3 using the `LAME <http://lame.sourceforge.net/>`_ library.
- Sets the bit rate in kilobit per second. Cannot be used with quality.
null
~~~~
----
Does not encode anything, passes the input PCM data as-is.
shine
~~~~~
-----
Encodes into MP3 using the `Shine <https://github.com/savonet/shine>`_ library.
@@ -546,7 +553,7 @@ Encodes into MP3 using the `Shine <https://github.com/savonet/shine>`_ library.
- Sets the bit rate in kilobit per second.
twolame
~~~~~~~
-------
Encodes into MP2 using the `TwoLAME <http://www.twolame.org/>`_ library.
@@ -562,7 +569,7 @@ Encodes into MP2 using the `TwoLAME <http://www.twolame.org/>`_ library.
- Sets the bit rate in kilobit per second. Cannot be used with quality.
opus
~~~~
----
Encodes into `Ogg Opus <http://www.opus-codec.org/>`_.
@@ -584,7 +591,7 @@ Encodes into `Ogg Opus <http://www.opus-codec.org/>`_.
.. _vorbis_plugin:
vorbis
~~~~~~
------
Encodes into `Ogg Vorbis <http://www.vorbis.com/>`_.
@@ -600,13 +607,13 @@ Encodes into `Ogg Vorbis <http://www.vorbis.com/>`_.
- Sets the bit rate in kilobit per second. Cannot be used with quality.
wave
~~~~
----
Encodes into WAV (lossless).
.. _resampler_plugins:
Resampler plugins
-----------------
=================
The resampler can be configured in a block named resampler, for example:
@@ -629,12 +636,12 @@ The following table lists the resampler options valid for all plugins:
- The name of the plugin.
internal
~~~~~~~~
--------
A resampler built into :program:`MPD`. Its quality is very poor, but its CPU usage is low. This is the fallback if :program:`MPD` was compiled without an external resampler.
libsamplerate
~~~~~~~~~~~~~
-------------
A resampler using `libsamplerate <http://www.mega-nerd.com/SRC/>`_ a.k.a. Secret Rabbit Code (SRC).
@@ -667,7 +674,7 @@ The following converter types are provided by libsamplerate:
- Linear interpolator, very fast, poor quality.
soxr
~~~~
----
A resampler using `libsoxr <http://sourceforge.net/projects/soxr/>`_, the SoX Resampler library
@@ -693,12 +700,12 @@ Valid quality values for libsoxr:
.. _output_plugins:
Output plugins
--------------
==============
.. _alsa_plugin:
alsa
~~~~
----
The `Advanced Linux Sound Architecture (ALSA) <http://www.alsa-project.org/>`_ plugin uses libasound. It is recommended if you are using Linux.
@@ -757,7 +764,7 @@ The following attributes can be configured at runtime using the outputset comman
ao
~~
--
The ao plugin uses the portable `libao <https://www.xiph.org/ao/>`_ library. Use only if there is no native plugin for your operating system.
.. list-table::
@@ -774,7 +781,8 @@ The ao plugin uses the portable `libao <https://www.xiph.org/ao/>`_ library. Use
- This specifies how many bytes to write to the audio device at once. This parameter is to work around a bug in older versions of libao on sound cards with very small buffers. The default is 1024.
sndio
~~~~~
-----
The sndio plugin uses the `sndio <http://www.sndio.org/>`_ library. It should normally be used on OpenBSD.
.. list-table::
@@ -789,7 +797,7 @@ The sndio plugin uses the `sndio <http://www.sndio.org/>`_ library. It should no
- Set the application buffer time in milliseconds.
fifo
~~~~
----
The fifo plugin writes raw PCM data to a FIFO (First In, First Out) file. The data can be read by another program.
@@ -803,7 +811,7 @@ The fifo plugin writes raw PCM data to a FIFO (First In, First Out) file. The da
- This specifies the path of the FIFO to write to. Must be an absolute path. If the path does not exist, it will be created when MPD is started, and removed when MPD is stopped. The FIFO will be created with the same user and group as MPD is running as. Default permissions can be modified by using the builtin shell command umask. If a FIFO already exists at the specified path it will be reused, and will not be removed when MPD is stopped. You can use the "mkfifo" command to create this, and then you may modify the permissions to your liking.
haiku
~~~~~
-----
Use the SoundPlayer API on the Haiku operating system.
@@ -812,7 +820,8 @@ removed soon, unless there is a new maintainer.
jack
~~~~
----
The jack plugin connects to a `JACK server <http://jackaudio.org/>`_.
.. list-table::
@@ -835,7 +844,8 @@ The jack plugin connects to a `JACK server <http://jackaudio.org/>`_.
- Sets the size of the ring buffer for each channel. Do not configure this value unless you know what you're doing.
httpd
~~~~~
-----
The httpd plugin creates a HTTP server, similar to `ShoutCast <http://www.shoutcast.com/>`_ / `IceCast <http://icecast.org/>`_. HTTP streaming clients like mplayer, VLC, and mpv can connect to it.
It is highly recommended to configure a fixed format, because a stream cannot switch its audio format on-the-fly when the song changes.
@@ -856,7 +866,8 @@ It is highly recommended to configure a fixed format, because a stream cannot sw
- Sets a limit, number of concurrent clients. When set to 0 no limit will apply.
null
~~~~
----
The null plugin does nothing. It discards everything sent to it.
.. list-table::
@@ -871,7 +882,8 @@ The null plugin does nothing. It discards everything sent to it.
.. _oss_plugin:
oss
~~~
---
The "Open Sound System" plugin is supported on most Unix platforms.
On Linux, OSS has been superseded by ALSA. Use the ALSA output plugin :ref:`alsa_plugin` instead of this one on Linux.
@@ -899,7 +911,7 @@ The according hardware mixer plugin understands the following settings:
- Choose a mixer control, defaulting to PCM.
openal
~~~~~~
------
The "OpenAL" plugin uses `libopenal <http://kcat.strangesoft.net/openal.html>`_. It is supported on many platforms. Use only if there is no native plugin for your operating system.
.. list-table::
@@ -912,7 +924,7 @@ The "OpenAL" plugin uses `libopenal <http://kcat.strangesoft.net/openal.html>`_.
- Sets the device which should be used. This can be any valid OpenAL device name. If not specified, then libopenal will choose a default device.
osx
~~~
---
The "Mac OS X" plugin uses Apple's CoreAudio API.
.. list-table::
@@ -933,7 +945,7 @@ The "Mac OS X" plugin uses Apple's CoreAudio API.
The channel map may not refer to outputs that do not exist according to the format. If the format is "*:*:1" (mono) and you have a four-channel sound card then "-1,-1,0,0" (dual mono output on the second pair of sound card outputs) is a valid channel map but "-1,-1,0,1" is not because the second channel ('1') does not exist when the output is mono.
pipe
~~~~
----
The pipe plugin starts a program and writes raw PCM data into its standard input.
@@ -949,7 +961,7 @@ The pipe plugin starts a program and writes raw PCM data into its standard input
.. _pulse_plugin:
pulse
~~~~~
-----
The pulse plugin connects to a `PulseAudio <http://www.freedesktop.org/wiki/Software/PulseAudio/>`_ server. Requires libpulse.
.. list-table::
@@ -966,7 +978,7 @@ The pulse plugin connects to a `PulseAudio <http://www.freedesktop.org/wiki/Soft
- Specifies a linear scaling coefficient (ranging from 0.5 to 5.0) to apply when adjusting volume through :program:`MPD`. For example, chosing a factor equal to ``"0.7"`` means that setting the volume to 100 in :program:`MPD` will set the PulseAudio volume to 70%, and a factor equal to ``"3.5"`` means that volume 100 in :program:`MPD` corresponds to a 350% PulseAudio volume.
recorder
~~~~~~~~
--------
The recorder plugin writes the audio played by :program:`MPD` to a file. This may be useful for recording radio streams.
.. list-table::
@@ -978,13 +990,13 @@ The recorder plugin writes the audio played by :program:`MPD` to a file. This ma
* - **path P**
- Write to this file.
* - **format_path P**
- An alternative to path which provides a format string referring to tag values. The special tag iso8601 emits the current date and time in `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_ format (UTC). Every time a new song starts or a new tag gets received from a radio station, a new file is opened. If the format does not render a file name, nothing is recorded. A tag name enclosed in percent signs ('%') is replaced with the tag value. Example: :file:`~/.mpd/recorder/%artist% - %title%.ogg`. Square brackets can be used to group a substring. If none of the tags referred in the group can be found, the whole group is omitted. Example: [~/.mpd/recorder/[%artist% - ]%title%.ogg] (this omits the dash when no artist tag exists; if title also doesn't exist, no file is written). The operators "|" (logical "or") and "&" (logical "and") can be used to select portions of the format string depending on the existing tag values. Example: ~/.mpd/recorder/[%title%|%name%].ogg (use the "name" tag if no title exists)
- An alternative to path which provides a format string referring to tag values. The special tag iso8601 emits the current date and time in `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_ format (UTC). Every time a new song starts or a new tag gets received from a radio station, a new file is opened. If the format does not render a file name, nothing is recorded. A tag name enclosed in percent signs ('%') is replaced with the tag value. Example: :file:`-/.mpd/recorder/%artist% - %title%.ogg`. Square brackets can be used to group a substring. If none of the tags referred in the group can be found, the whole group is omitted. Example: [-/.mpd/recorder/[%artist% - ]%title%.ogg] (this omits the dash when no artist tag exists; if title also doesn't exist, no file is written). The operators "|" (logical "or") and "&" (logical "and") can be used to select portions of the format string depending on the existing tag values. Example: -/.mpd/recorder/[%title%|%name%].ogg (use the "name" tag if no title exists)
* - **encoder NAME**
- Chooses an encoder plugin. A list of encoder plugins can be found in the encoder plugin reference :ref:`encoder_plugins`.
shout
~~~~~
-----
The shout plugin connects to a ShoutCast or IceCast server using libshout. It forwards tags to this server.
You must set a format.
@@ -1028,7 +1040,7 @@ You must set a format.
.. _sles_output:
sles
~~~~
----
Plugin using the `OpenSL ES <https://www.khronos.org/opensles/>`__
audio API. Its primary use is local playback on Android, where
@@ -1036,7 +1048,7 @@ audio API. Its primary use is local playback on Android, where
solaris
~~~~~~~
-------
The "Solaris" plugin runs only on SUN Solaris, and plays via /dev/audio.
.. list-table::
@@ -1052,22 +1064,22 @@ The "Solaris" plugin runs only on SUN Solaris, and plays via /dev/audio.
.. _filter_plugins:
Filter plugins
--------------
==============
normalize
~~~~~~~~~
---------
Normalize the volume during playback (at the expensve of quality).
null
~~~~
----
A no-op filter. Audio data is returned as-is.
route
~~~~~
-----
Reroute channels.
@@ -1084,43 +1096,44 @@ Reroute channels.
.. _playlist_plugins:
Playlist plugins
----------------
================
asx
~~~
---
Reads .asx playlist files.
cue
~~~
---
Reads .cue files.
embcue
~~~~~~
------
Reads CUE sheets from the "CUESHEET" tag of song files.
m3u
~~~
---
Reads .m3u playlist files.
extm3u
~~~~~~
------
Reads extended .m3u playlist files.
flac
~~~~
----
Reads the cuesheet metablock from a FLAC file.
pls
~~~
---
Reads .pls playlist files.
rss
~~~
---
Reads music links from .rss files.
soundcloud
~~~~~~~~~~
----------
Download playlist from SoundCloud. It accepts URIs starting with soundcloud://.
.. list-table::
@@ -1133,5 +1146,5 @@ Download playlist from SoundCloud. It accepts URIs starting with soundcloud://.
- An API key to access the SoundCloud servers.
xspf
~~~~
----
Reads XSPF playlist files.

@@ -14,6 +14,9 @@ Once the client is connected to the server, they conduct a
conversation until the client closes the connection. The
conversation flow is always initiated by the client.
All data between the client and the server is encoded in
UTF-8.
The client transmits a command sequence, terminated by the
newline character ``\n``. The server will
respond with one or more lines, the last of which will be a
@@ -42,9 +45,6 @@ quotation marks.
Argument strings are separated from the command and any other
arguments by linear white-space (' ' or '\\t').
All data between the client and the server is encoded in
UTF-8.
Responses
=========
@@ -52,6 +52,28 @@ A command returns ``OK`` on completion or
``ACK some error`` on failure. These
denote the end of command execution.
Some commands return more data before the response ends with ``OK``.
Each line is usually in the form ``NAME: VALUE``. Example::
foo: bar
OK
.. _binary:
Binary Responses
----------------
Some commands can return binary data. This is initiated by a line
containing ``binary: 1234`` (followed as usual by a newline). After
that, the specified number of bytes of binary data follows, then a
newline, and finally the ``OK`` line. Example::
foo: bar
binary: 42
<42 bytes>
OK
Failure responses
-----------------
@@ -112,9 +134,9 @@ list begins with `command_list_begin` or
`command_list_ok_begin` and ends with
`command_list_end`.
It does not execute any commands until the list has ended.
The return value is whatever the return for a list of commands
is. On success for all commands,
It does not execute any commands until the list has ended. The
response is a concatentation of all individual responses.
On success for all commands,
``OK`` is returned. If a command
fails, no more commands are executed and the appropriate
``ACK`` error is returned. If
@@ -178,8 +200,9 @@ of:
file's time stamp with the given value (ISO 8601 or UNIX
time stamp).
- ``(AudioFormat == 'SAMPLERATE:BITS:CHANNELS')``:
compares the audio format with the given value.
- ``(AudioFormat == 'SAMPLERATE:BITS:CHANNELS')``: compares the audio
format with the given value. See :ref:`audio_output_format` for a
detailed explanation.
- ``(AudioFormat =~ 'SAMPLERATE:BITS:CHANNELS')``:
matches the audio format with the given mask (i.e. one
@@ -414,15 +437,18 @@ Querying :program:`MPD`'s status
- ``songid``: playlist songid of the current song stopped on or playing
- ``nextsong`` [#since_0_15]_: playlist song number of the next song to be played
- ``nextsongid`` [#since_0_15]_: playlist songid of the next song to be played
- ``time``: total time elapsed (of current playing/paused song)
- ``time``: total time elapsed (of current playing/paused song) in seconds
(deprecated, use ``elapsed`` instead)
- ``elapsed`` [#since_0_16]_: Total time elapsed within the current song, but with higher resolution.
- ``elapsed`` [#since_0_16]_: Total time elapsed within the
current song in seconds, but with higher resolution.
- ``duration`` [#since_0_20]_: Duration of the current song in seconds.
- ``bitrate``: instantaneous bitrate in kbps
- ``xfade``: ``crossfade`` in seconds
- ``mixrampdb``: ``mixramp`` threshold in dB
- ``mixrampdelay``: ``mixrampdelay`` in seconds
- ``audio``: The format emitted by the decoder plugin during playback, format: ``*samplerate:bits:channels*``. Check the user manual for a detailed explanation.
- ``audio``: The format emitted by the decoder plugin during
playback, format: ``samplerate:bits:channels``. See
:ref:`audio_output_format` for a detailed explanation.
- ``updating_db``: ``job id``
- ``error``: if there is an error, returns message here
@@ -437,7 +463,7 @@ Querying :program:`MPD`'s status
- ``albums``: number of albums
- ``songs``: number of songs
- ``uptime``: daemon uptime in seconds
- ``db_playtime``: sum of all song times in the db
- ``db_playtime``: sum of all song times in the database in seconds
- ``db_update``: last db update in UNIX time
- ``playtime``: time length of music played
@@ -599,7 +625,7 @@ Whenever possible, ids should be used.
Deletes the song ``SONGID`` from the
playlist
:command:`move {FROM} [{START:END} | {TO}]`
:command:`move [{FROM} | {START:END}] {TO}`
Moves the song at ``FROM`` or range of songs
at ``START:END`` [#since_0_15]_ to ``TO``
in the playlist.
@@ -790,7 +816,7 @@ The music database
Returns the file size and actual number
of bytes read at the requested offset, followed
by the chunk requested as raw bytes, then a
by the chunk requested as raw bytes (see :ref:`binary`), then a
newline and the completion code.
Example::
@@ -860,8 +886,7 @@ The music database
:command:`list {TYPE} {FILTER} [group {GROUPTYPE}]`
Lists unique tags values of the specified type.
``TYPE`` can be any tag supported by
:program:`MPD` or
*file*.
:program:`MPD`.
Additional arguments may specify a :ref:`filter <filter_syntax>`.
The *group* keyword may be used
@@ -872,6 +897,10 @@ The music database
list album group albumartist
``list file`` was implemented in an early :program:`MPD` version,
but does not appear to make a lot of sense. It still works (to
avoid breaking compatibility), but is deprecated.
.. _command_listall:
:command:`listall [URI]`
@@ -1053,7 +1082,8 @@ Stickers
"Stickers" [#since_0_15]_ are pieces of
information attached to existing
:program:`MPD` objects (e.g. song files,
directories, albums). Clients can create arbitrary name/value
directories, albums; but currently, they are only implemented for
song). Clients can create arbitrary name/value
pairs. :program:`MPD` itself does not assume
any special meaning in them.

@@ -402,14 +402,9 @@ The following table lists the audio_output options valid for all plugins:
- The name of the plugin
* - **name**
- The name of the audio output. It is visible to the client. Some plugins also use it internally, e.g. as a name registered in the PULSE server.
* - **format**
- Always open the audio output with the specified audio format samplerate:bits:channels), regardless of the format of the input file. This is optional for most plugins.
Any of the three attributes may be an asterisk to specify that this attribute should not be enforced, example: 48000:16:*. *:*:* is equal to not having a format specification.
The following values are valid for bits: 8 (signed 8 bit integer samples), 16, 24 (signed 24 bit integer samples padded to 32 bit), 32 (signed 32 bit integer samples), f (32 bit floating point, -1.0 to 1.0), "dsd" means DSD (Direct Stream Digital). For DSD, there are special cases such as "dsd64", which allows you to omit the sample rate (e.g. dsd512:2 for stereo DSD512, i.e. 22.5792 MHz).
The sample rate is special for DSD: :program:`MPD` counts the number of bytes, not bits. Thus, a DSD "bit" rate of 22.5792 MHz (DSD512) is 2822400 from :program:`MPD`'s point of view (44100*512/8).
* - **format samplerate:bits:channels**
- Always open the audio output with the specified audio format, regardless of the format of the input file. This is optional for most plugins.
See :ref:`audio_output_format` for a detailed description of the value.
* - **enabed yes|no**
- Specifies whether this audio output is enabled when :program:`MPD` is started. By default, all audio outputs are enabled. This is just the default setting when there is no state file; with a state file, the previous state is restored.
* - **tags yes|no**
@@ -504,13 +499,34 @@ reference.
Audio Format Settings
---------------------
Global Audio Format
~~~~~~~~~~~~~~~~~~~
.. _audio_output_format:
The setting audio_output_format forces :program:`MPD` to use one audio format for all outputs. Doing that is usually not a good idea. The values are the same as in format in the audio_output section.
Global Audio Format
^^^^^^^^^^^^^^^^^^^
The setting ``audio_output_format`` forces :program:`MPD` to use one
audio format for all outputs. Doing that is usually not a good idea.
The value is specified as ``samplerate:bits:channels``.
Any of the three attributes may be an asterisk to specify that this
attribute should not be enforced, example: ``48000:16:*``.
``*:*:*`` is equal to not having a format specification.
The following values are valid for bits: ``8`` (signed 8 bit integer
samples), ``16``, ``24`` (signed 24 bit integer samples padded to 32
bit), ``32`` (signed 32 bit integer samples), ``f`` (32 bit floating
point, -1.0 to 1.0), ``dsd`` means DSD (Direct Stream Digital). For
DSD, there are special cases such as ``dsd64``, which allows you to
omit the sample rate (e.g. ``dsd512:2`` for stereo DSD512,
i.e. 22.5792 MHz).
The sample rate is special for DSD: :program:`MPD` counts the number
of bytes, not bits. Thus, a DSD "bit" rate of 22.5792 MHz (DSD512) is
2822400 from :program:`MPD`'s point of view (44100*512/8).
Resampler
~~~~~~~~~
^^^^^^^^^
Sometimes, music needs to be resampled before it can be played; for example, CDs use a sample rate of 44,100 Hz while many cheap audio chips can only handle 48,000 Hz. Resampling reduces the quality and consumes a lot of CPU. There are different options, some of them optimized for high quality and others for low CPU usage, but you can't have both at the same time. Often, the resampler is the component that is responsible for most of :program:`MPD`'s CPU usage. Since :program:`MPD` comes with high quality defaults, it may appear that :program:`MPD` consumes more CPU than other software.
@@ -523,7 +539,7 @@ Client Connections
.. _listeners:
Listeners
~~~~~~~~~
^^^^^^^^^
The setting :code:`bind_to_address` specifies which addresses
:program:`MPD` listens on for connections from clients. It can be
@@ -566,7 +582,7 @@ used.
Permissions and Passwords
~~~~~~~~~~~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^^^^^^^^^^^
By default, all clients are unauthenticated and have a full set of permissions. This can be restricted with the settings :code:`default_permissions` and :code:`password`.
@@ -629,7 +645,7 @@ Other Settings
Section :ref:`tags` contains a list of supported tags.
The State File
~~~~~~~~~~~~~~
^^^^^^^^^^^^^^
The state file is a file where :program:`MPD` saves and restores its state (play queue, playback position etc.) to keep it persistent across restarts and reboots. It is an optional setting.
@@ -647,7 +663,7 @@ The State File
- Auto-save the state file this number of seconds after each state change. Defaults to 120 (2 minutes).
The Sticker Database
~~~~~~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^^^^^^
"Stickers" are pieces of information attached to songs. Some clients
use them to store ratings and other volatile data. This feature
@@ -664,7 +680,7 @@ requires :program:`SQLite`, compile-time configure option
- The location of the sticker database.
Resource Limitations
~~~~~~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^^^^^^
These settings are various limitations to prevent :program:`MPD` from using too many resources (denial of service).
@@ -686,7 +702,7 @@ These settings are various limitations to prevent :program:`MPD` from using too
- The maximum size of the output buffer to a client (maximum response size). Default is 8192 (8 MiB).
Buffer Settings
~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^
Do not change these unless you know what you are doing.
@@ -700,7 +716,7 @@ Do not change these unless you know what you are doing.
- Adjust the size of the internal audio buffer. Default is 4096 (4 MiB).
Zeroconf
~~~~~~~~
^^^^^^^^
If Zeroconf support (`Avahi <http://avahi.org/>`_ or Apple's Bonjour)
was enabled at compile time with :code:`-Dzeroconf=...`,
@@ -786,10 +802,12 @@ You can verify whether the real-time scheduler is active with the ps command:
The CLS column shows the CPU scheduler; TS is the normal scheduler; FF and RR are real-time schedulers. In this example, two threads use the real-time scheduler: the output thread and the rtio (real-time I/O) thread; these two are the important ones. The database update thread uses the idle scheduler ("IDL in ps), which only gets CPU when no other process needs it.
Note
~~~~
.. note::
There is a rumor that real-time scheduling improves audio quality. That is not true. All it does is reduce the probability of skipping (audio buffer xruns) when the computer is under heavy load.
There is a rumor that real-time scheduling improves audio
quality. That is not true. All it does is reduce the probability of
skipping (audio buffer xruns) when the computer is under heavy
load.
Using MPD
*********
@@ -817,7 +835,7 @@ Depending on the size of your music collection and the speed of the storage, thi
To exclude a file from the update, create a file called :file:`.mpdignore` in its parent directory. Each line of that file may contain a list of shell wildcards. Matching files in the current directory and all subdirectories are excluded.
Mounting other storages into the music directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:program:`MPD` has various storage plugins of which multiple instances can be "mounted" into the music directory. This way, you can use local music, file servers and USB sticks at the same time. Example:
@@ -885,7 +903,7 @@ To verify if :program:`MPD` converts the audio format, enable verbose logging, a
.. code-block:: none
decoder: audio_format=44100:24:2, seekable=true
output: opened plugin=alsa name="An ALSA output"audio_format=44100:16:2
output: opened plugin=alsa name="An ALSA output" audio_format=44100:16:2
output: converting from 44100:24:2
This example shows that a 24 bit file is being played, but the sound chip cannot play 24 bit. It falls back to 16 bit, discarding 8 bit.
@@ -912,7 +930,7 @@ Check list for bit-perfect playback:
device (:samp:`hw:0,0` or similar).
* Don't use software volume (setting :code:`mixer_type`).
* Don't force :program:`MPD` to use a specific audio format (settings
:code:`format`, :code:`audio_output_format`).
:code:`format`, :ref:`audio_output_format <audio_output_format>`).
* Verify that you are really doing bit-perfect playback using :program:`MPD`'s verbose log and :file:`/proc/asound/card*/pcm*p/sub*/hw_params`. Some DACs can also indicate the audio format.
Direct Stream Digital (DSD)
@@ -963,18 +981,18 @@ Support
-------
Getting Help
~~~~~~~~~~~~
^^^^^^^^^^^^
The :program:`MPD` project runs a `forum <https://forum.musicpd.org/>`_ and an IRC channel (#mpd on Freenode) for requesting help. Visit the MPD help page for details on how to get help.
Common Problems
~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^
1. Database
^^^^^^^^^^^
"""""""""""
Question: I can't see my music in the MPD database!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Check your :code:`music_directory` setting.
* Does the MPD user have read permission on all music files, and read+execute permission on all music directories (and all of their parent directories)?
@@ -982,22 +1000,22 @@ Question: I can't see my music in the MPD database!
* Did you enable all relevant decoder plugins at compile time? :command:`mpd --version` will tell you.
Question: MPD doesn't read ID3 tags!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* You probably compiled :program:`MPD` without libid3tag. :command:`mpd --version` will tell you.
2. Playback
^^^^^^^^^^^
"""""""""""
Question: I can't hear music on my client!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* That problem usually follows a misunderstanding of the nature of :program:`MPD`. :program:`MPD` is a remote-controlled music player, not a music distribution system. Usually, the speakers are connected to the box where :program:`MPD` runs, and the :program:`MPD` client only sends control commands, but the client does not actually play your music.
:program:`MPD` has output plugins which allow hearing music on a remote host (such as httpd), but that is not :program:`MPD`'s primary design goal.
Question: "Device or resource busy"
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* This ALSA error means that another program uses your sound hardware exclusively. You can stop that program to allow :program:`MPD` to use it.
@@ -1016,7 +1034,7 @@ Your bug report should contain:
* be clear about what you expect MPD to do, and what is actually happening
MPD crashes
~~~~~~~~~~~
^^^^^^^^^^^
All :program:`MPD` crashes are bugs which must be fixed by a developer, and you should write a bug report. (Many crash bugs are caused by codec libraries used by :program:`MPD`, and then that library must be fixed; but in any case, the :program:`MPD` `bug tracker <https://github.com/MusicPlayerDaemon/MPD/issues>`_ is a good place to report it first if you don't know.)

@@ -1,7 +1,7 @@
project(
'mpd',
['c', 'cpp'],
version: '0.21.7',
version: '0.21.15',
meson_version: '>= 0.49.0',
default_options: [
'c_std=c99',
@@ -15,12 +15,18 @@ version_cxx = vcs_tag(input: 'src/GitVersion.cxx', output: 'GitVersion.cxx')
compiler = meson.get_compiler('cpp')
c_compiler = meson.get_compiler('c')
if compiler.get_id() == 'gcc' and compiler.version().version_compare('<6')
warning('Your GCC version is too old. You need at least version 6.')
elif compiler.get_id() == 'clang' and compiler.version().version_compare('<3')
warning('Your clang version is too old. You need at least version 3.')
endif
conf = configuration_data()
conf.set_quoted('PACKAGE', meson.project_name())
conf.set_quoted('PACKAGE_NAME', meson.project_name())
conf.set_quoted('PACKAGE_VERSION', meson.project_version())
conf.set_quoted('VERSION', meson.project_version())
conf.set_quoted('PROTOCOL_VERSION', '0.21.6')
conf.set_quoted('PROTOCOL_VERSION', '0.21.11')
conf.set_quoted('SYSTEM_CONFIG_FILE_LOCATION', join_paths(get_option('prefix'), get_option('sysconfdir'), 'mpd.conf'))
common_cppflags = [
@@ -367,8 +373,10 @@ basic_dep = declare_dependency(
if enable_database
subdir('src/storage')
subdir('src/db')
else
storage_glue_dep = dependency('', required: false)
endif
subdir('src/db')
if neighbor_glue_dep.found()
sources += 'src/command/NeighborCommands.cxx'

@@ -15,8 +15,8 @@ libmpdclient = MesonProject(
)
libogg = AutotoolsProject(
'http://downloads.xiph.org/releases/ogg/libogg-1.3.3.tar.xz',
'4f3fc6178a533d392064f14776b23c397ed4b9f48f5de297aba73b643f955c08',
'http://downloads.xiph.org/releases/ogg/libogg-1.3.4.tar.xz',
'c163bc12bc300c401b6aa35907ac682671ea376f13ae0969a220f7ddf71893fe',
'lib/libogg.a',
[
'--disable-shared', '--enable-static',
@@ -38,8 +38,8 @@ libvorbis = AutotoolsProject(
)
opus = AutotoolsProject(
'https://archive.mozilla.org/pub/opus/opus-1.3.tar.gz',
'4f3d69aefdf2dbaf9825408e452a8a414ffc60494c70633560700398820dc550',
'https://archive.mozilla.org/pub/opus/opus-1.3.1.tar.gz',
'65b58e1e25b2a114157014736a3d9dfeaad8d41be1c8179866f144a2fb44ff9d',
'lib/libopus.a',
[
'--disable-shared', '--enable-static',
@@ -112,8 +112,8 @@ liblame = AutotoolsProject(
)
ffmpeg = FfmpegProject(
'http://ffmpeg.org/releases/ffmpeg-4.1.3.tar.xz',
'0c3020452880581a8face91595b239198078645e7d7184273b8bcc7758beb63d',
'http://ffmpeg.org/releases/ffmpeg-4.2.tar.xz',
'023f10831a97ad93d798f53a3640e55cd564abfeba807ecbe8524dac4fedecd5',
'lib/libavcodec.a',
[
'--disable-shared', '--enable-static',
@@ -341,8 +341,8 @@ ffmpeg = FfmpegProject(
)
curl = AutotoolsProject(
'http://curl.haxx.se/download/curl-7.64.1.tar.xz',
'9252332a7f871ce37bfa7f78bdd0a0e3924d8187cc27cb57c76c9474a7168fb3',
'http://curl.haxx.se/download/curl-7.65.3.tar.xz',
'f2d98854813948d157f6a91236ae34ca4a1b4cb302617cebad263d79b0235fea',
'lib/libcurl.a',
[
'--disable-shared', '--enable-static',
@@ -365,8 +365,8 @@ curl = AutotoolsProject(
)
libexpat = AutotoolsProject(
'https://github.com/libexpat/libexpat/releases/download/R_2_2_6/expat-2.2.6.tar.bz2',
'17b43c2716d521369f82fc2dc70f359860e90fa440bea65b3b85f0b246ea81f2',
'https://github.com/libexpat/libexpat/releases/download/R_2_2_7/expat-2.2.7.tar.bz2',
'cbc9102f4a31a8dafd42d642e9a3aa31e79a0aedaa1f6efd2795ebc83174ec18',
'lib/libexpat.a',
[
'--disable-shared', '--enable-static',
@@ -392,7 +392,7 @@ libnfs = AutotoolsProject(
)
boost = BoostProject(
'http://downloads.sourceforge.net/project/boost/boost/1.69.0/boost_1_69_0.tar.bz2',
'8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406',
'https://dl.bintray.com/boostorg/release/1.71.0/source/boost_1_71_0.tar.bz2',
'd73a8da01e8bf8c7eda40b4c84915071a8c8a0df4a6734537ddde4a8580524ee',
'include/boost/version.hpp',
)

@@ -108,17 +108,17 @@ static constexpr Domain cmdline_domain("cmdline");
gcc_noreturn
static void version(void)
{
printf("Music Player Daemon " VERSION " (%s)\n"
printf("Music Player Daemon " VERSION " (%s)"
"\n"
"Copyright 2003-2007 Warren Dukes <warren.dukes@gmail.com>\n"
"Copyright 2008-2018 Max Kellermann <max.kellermann@gmail.com>\n"
"This is free software; see the source for copying conditions. There is NO\n"
"warranty; not even MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
"warranty; not even MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
GIT_VERSION);
#ifdef ENABLE_DATABASE
"\n"
"Database plugins:\n",
GIT_VERSION);
printf("\n"
"Database plugins:\n");
for (auto i = database_plugins; *i != nullptr; ++i)
printf(" %s", (*i)->name);
@@ -129,18 +129,18 @@ static void version(void)
for (auto i = storage_plugins; *i != nullptr; ++i)
printf(" %s", (*i)->name);
printf("\n"
printf("\n");
#endif
#ifdef ENABLE_NEIGHBOR_PLUGINS
"\n"
printf("\n"
"Neighbor plugins:\n");
for (auto i = neighbor_plugins; *i != nullptr; ++i)
printf(" %s", (*i)->name);
printf("\n"
#endif
printf("\n"
"\n"
"Decoders plugins:\n");

@@ -55,14 +55,26 @@ LocateFileUri(const char *uri, const Client *client
}
static LocatedUri
LocateAbsoluteUri(const char *uri
LocateAbsoluteUri(UriPluginKind kind, const char *uri
#ifdef ENABLE_DATABASE
, const Storage *storage
#endif
)
{
if (!uri_supported_scheme(uri))
throw std::runtime_error("Unsupported URI scheme");
switch (kind) {
case UriPluginKind::INPUT:
case UriPluginKind::STORAGE: // TODO: separate check for storage plugins
if (!uri_supported_scheme(uri))
throw std::runtime_error("Unsupported URI scheme");
break;
case UriPluginKind::PLAYLIST:
/* for now, no validation for playlist URIs; this is
more complicated because there are three ways to
identify which plugin to use: URI scheme, filename
suffix and MIME type */
break;
}
#ifdef ENABLE_DATABASE
if (storage != nullptr) {
@@ -76,7 +88,8 @@ LocateAbsoluteUri(const char *uri
}
LocatedUri
LocateUri(const char *uri, const Client *client
LocateUri(UriPluginKind kind,
const char *uri, const Client *client
#ifdef ENABLE_DATABASE
, const Storage *storage
#endif
@@ -100,7 +113,7 @@ LocateUri(const char *uri, const Client *client
#endif
);
else if (uri_has_scheme(uri))
return LocateAbsoluteUri(uri
return LocateAbsoluteUri(kind, uri
#ifdef ENABLE_DATABASE
, storage
#endif

@@ -41,6 +41,12 @@ class Client;
class Storage;
#endif
enum class UriPluginKind {
INPUT,
STORAGE,
PLAYLIST,
};
struct LocatedUri {
enum class Type {
/**
@@ -84,7 +90,8 @@ struct LocatedUri {
* that feature is disabled if this parameter is nullptr
*/
LocatedUri
LocateUri(const char *uri, const Client *client
LocateUri(UriPluginKind kind,
const char *uri, const Client *client
#ifdef ENABLE_DATABASE
, const Storage *storage
#endif

@@ -43,7 +43,15 @@ struct MusicChunk;
/**
* Meta information for #MusicChunk.
*/
struct MusicChunkInfo {
struct alignas(8) MusicChunkInfo {
/* align to multiple of 8 bytes, which adds padding at the
end, so the size of MusicChunk::data is also a multiple of
8 bytes; this is a workaround for a bug in the DSD_U32 and
DoP converters which require processing 8 bytes at a time,
discarding the remainder */
/* TODO: once all converters have been fixed, we should remove
this workaround */
/** the next chunk in a linked list */
MusicChunkPtr next;
@@ -119,6 +127,10 @@ struct MusicChunk : MusicChunkInfo {
/** the data (probably PCM) */
uint8_t data[CHUNK_SIZE - sizeof(MusicChunkInfo)];
/* TODO: remove this check once all converters have been fixed
(see comment in struct MusicChunkInfo for details) */
static_assert(sizeof(data) % 8 == 0, "Wrong alignment");
/**
* Prepares appending to the music chunk. Returns a buffer
* where you may write into. After you are finished, call

@@ -38,6 +38,10 @@ struct ReplayGainTuple {
return gain > -100;
}
static constexpr ReplayGainTuple Undefined() noexcept {
return {-200.0f, 0.0f};
}
gcc_pure
float CalculateScale(const ReplayGainConfig &config) const noexcept;
};
@@ -49,6 +53,13 @@ struct ReplayGainInfo {
return track.IsDefined() || album.IsDefined();
}
static constexpr ReplayGainInfo Undefined() noexcept {
return {
ReplayGainTuple::Undefined(),
ReplayGainTuple::Undefined(),
};
}
const ReplayGainTuple &Get(ReplayGainMode mode) const noexcept {
return mode == ReplayGainMode::ALBUM
? (album.IsDefined() ? album : track)

@@ -94,7 +94,8 @@ SongLoader::LoadSong(const char *uri_utf8) const
assert(uri_utf8 != nullptr);
#endif
const auto located_uri = LocateUri(uri_utf8, client
const auto located_uri = LocateUri(UriPluginKind::INPUT,
uri_utf8, client
#ifdef ENABLE_DATABASE
, storage
#endif

@@ -35,6 +35,6 @@ extern size_t client_max_command_list_size;
extern size_t client_max_output_buffer_size;
CommandResult
client_process_line(Client &client, char *line);
client_process_line(Client &client, char *line) noexcept;
#endif

@@ -30,7 +30,7 @@
static CommandResult
client_process_command_list(Client &client, bool list_ok,
std::list<std::string> &&list)
std::list<std::string> &&list) noexcept
{
CommandResult ret = CommandResult::OK;
unsigned num = 0;
@@ -51,7 +51,7 @@ client_process_command_list(Client &client, bool list_ok,
}
CommandResult
client_process_line(Client &client, char *line)
client_process_line(Client &client, char *line) noexcept
{
CommandResult ret;

@@ -206,9 +206,10 @@ static constexpr struct command commands[] = {
static constexpr unsigned num_commands = ARRAY_SIZE(commands);
gcc_pure
static bool
command_available(gcc_unused const Partition &partition,
gcc_unused const struct command *cmd)
gcc_unused const struct command *cmd) noexcept
{
#ifdef ENABLE_SQLITE
if (StringIsEqual(cmd->cmd, "sticker"))
@@ -235,7 +236,7 @@ command_available(gcc_unused const Partition &partition,
static CommandResult
PrintAvailableCommands(Response &r, const Partition &partition,
unsigned permission)
unsigned permission) noexcept
{
for (unsigned i = 0; i < num_commands; ++i) {
const struct command *cmd = &commands[i];
@@ -249,7 +250,7 @@ PrintAvailableCommands(Response &r, const Partition &partition,
}
static CommandResult
PrintUnavailableCommands(Response &r, unsigned permission)
PrintUnavailableCommands(Response &r, unsigned permission) noexcept
{
for (unsigned i = 0; i < num_commands; ++i) {
const struct command *cmd = &commands[i];
@@ -276,7 +277,7 @@ handle_not_commands(Client &client, gcc_unused Request request, Response &r)
}
void
command_init()
command_init() noexcept
{
#ifndef NDEBUG
/* ensure that the command list is sorted */
@@ -285,8 +286,9 @@ command_init()
#endif
}
gcc_pure
static const struct command *
command_lookup(const char *name)
command_lookup(const char *name) noexcept
{
unsigned a = 0, b = num_commands, i;
@@ -308,7 +310,7 @@ command_lookup(const char *name)
static bool
command_check_request(const struct command *cmd, Response &r,
unsigned permission, Request args)
unsigned permission, Request args) noexcept
{
if (cmd->permission != (permission & cmd->permission)) {
r.FormatError(ACK_ERROR_PERMISSION,
@@ -342,7 +344,7 @@ command_check_request(const struct command *cmd, Response &r,
static const struct command *
command_checked_lookup(Response &r, unsigned permission,
const char *cmd_name, Request args)
const char *cmd_name, Request args) noexcept
{
const struct command *cmd = command_lookup(cmd_name);
if (cmd == nullptr) {
@@ -360,8 +362,8 @@ command_checked_lookup(Response &r, unsigned permission,
}
CommandResult
command_process(Client &client, unsigned num, char *line)
try {
command_process(Client &client, unsigned num, char *line) noexcept
{
Response r(client, num);
/* get the command name (first word on the line) */
@@ -389,34 +391,33 @@ try {
char *argv[COMMAND_ARGV_MAX];
Request args(argv, 0);
/* now parse the arguments (quoted or unquoted) */
try {
/* now parse the arguments (quoted or unquoted) */
while (true) {
if (args.size == COMMAND_ARGV_MAX) {
r.Error(ACK_ERROR_ARG, "Too many arguments");
return CommandResult::ERROR;
while (true) {
if (args.size == COMMAND_ARGV_MAX) {
r.Error(ACK_ERROR_ARG, "Too many arguments");
return CommandResult::ERROR;
}
char *a = tokenizer.NextParam();
if (a == nullptr)
break;
argv[args.size++] = a;
}
char *a = tokenizer.NextParam();
if (a == nullptr)
break;
/* look up and invoke the command handler */
argv[args.size++] = a;
const struct command *cmd =
command_checked_lookup(r, client.GetPermission(),
cmd_name, args);
if (cmd == nullptr)
return CommandResult::ERROR;
return cmd->handler(client, args, r);
} catch (...) {
PrintError(r, std::current_exception());
return CommandResult::ERROR;
}
/* look up and invoke the command handler */
const struct command *cmd =
command_checked_lookup(r, client.GetPermission(),
cmd_name, args);
CommandResult ret = cmd
? cmd->handler(client, args, r)
: CommandResult::ERROR;
return ret;
} catch (const std::exception &e) {
Response r(client, num);
PrintError(r, std::current_exception());
return CommandResult::ERROR;
}

@@ -25,12 +25,9 @@
class Client;
void
command_init();
void
command_finish();
command_init() noexcept;
CommandResult
command_process(Client &client, unsigned num, char *line);
command_process(Client &client, unsigned num, char *line) noexcept;
#endif

@@ -266,7 +266,7 @@ handle_list(Client &client, Request args, Response &r)
}
std::unique_ptr<SongFilter> filter;
TagType group = TAG_NUM_OF_ITEM_TYPES;
std::vector<TagType> tag_types;
if (args.size == 1 &&
/* parantheses are the syntax for filter expressions: no
@@ -284,20 +284,31 @@ handle_list(Client &client, Request args, Response &r)
args.shift()));
}
if (args.size >= 2 &&
StringIsEqual(args[args.size - 2], "group")) {
while (args.size >= 2 &&
StringIsEqual(args[args.size - 2], "group")) {
const char *s = args[args.size - 1];
group = tag_name_parse_i(s);
const auto group = tag_name_parse_i(s);
if (group == TAG_NUM_OF_ITEM_TYPES) {
r.FormatError(ACK_ERROR_ARG,
"Unknown tag type: %s", s);
return CommandResult::ERROR;
}
if (group == tagType ||
std::find(tag_types.begin(), tag_types.end(),
group) != tag_types.end()) {
r.Error(ACK_ERROR_ARG, "Conflicting group");
return CommandResult::ERROR;
}
tag_types.emplace_back(group);
args.pop_back();
args.pop_back();
}
tag_types.emplace_back(tagType);
if (!args.empty()) {
filter.reset(new SongFilter());
try {
@@ -310,13 +321,9 @@ handle_list(Client &client, Request args, Response &r)
filter->Optimize();
}
if (tagType < TAG_NUM_OF_ITEM_TYPES && tagType == group) {
r.Error(ACK_ERROR_ARG, "Conflicting group");
return CommandResult::ERROR;
}
PrintUniqueTags(r, client.GetPartition(),
tagType, group, filter.get());
{&tag_types.front(), tag_types.size()},
filter.get());
return CommandResult::OK;
}

@@ -218,7 +218,7 @@ handle_read_comments(Client &client, Request args, Response &r)
const char *const uri = args.front();
const auto located_uri = LocateUri(uri, &client
const auto located_uri = LocateUri(UriPluginKind::INPUT, uri, &client
#ifdef ENABLE_DATABASE
, nullptr
#endif
@@ -331,7 +331,7 @@ handle_album_art(Client &client, Request args, Response &r)
const char *uri = args.front();
size_t offset = args.ParseUnsigned(1);
const auto located_uri = LocateUri(uri, &client
const auto located_uri = LocateUri(UriPluginKind::INPUT, uri, &client
#ifdef ENABLE_DATABASE
, nullptr
#endif

@@ -99,7 +99,7 @@ handle_listfiles(Client &client, Request args, Response &r)
/* default is root directory */
const auto uri = args.GetOptional(0, "");
const auto located_uri = LocateUri(uri, &client
const auto located_uri = LocateUri(UriPluginKind::STORAGE, uri, &client
#ifdef ENABLE_DATABASE
, nullptr
#endif
@@ -219,7 +219,7 @@ handle_lsinfo(Client &client, Request args, Response &r)
compatibility, work around this here */
uri = "";
const auto located_uri = LocateUri(uri, &client
const auto located_uri = LocateUri(UriPluginKind::INPUT, uri, &client
#ifdef ENABLE_DATABASE
, nullptr
#endif

@@ -69,7 +69,8 @@ handle_save(Client &client, Request args, gcc_unused Response &r)
CommandResult
handle_load(Client &client, Request args, gcc_unused Response &r)
{
const auto uri = LocateUri(args.front(), &client
const auto uri = LocateUri(UriPluginKind::PLAYLIST, args.front(),
&client
#ifdef ENABLE_DATABASE
, nullptr
#endif
@@ -99,7 +100,8 @@ handle_load(Client &client, Request args, gcc_unused Response &r)
CommandResult
handle_listplaylist(Client &client, Request args, Response &r)
{
const auto name = LocateUri(args.front(), &client
const auto name = LocateUri(UriPluginKind::PLAYLIST, args.front(),
&client
#ifdef ENABLE_DATABASE
, nullptr
#endif
@@ -115,7 +117,8 @@ handle_listplaylist(Client &client, Request args, Response &r)
CommandResult
handle_listplaylistinfo(Client &client, Request args, Response &r)
{
const auto name = LocateUri(args.front(), &client
const auto name = LocateUri(UriPluginKind::PLAYLIST, args.front(),
&client
#ifdef ENABLE_DATABASE
, nullptr
#endif

@@ -83,7 +83,8 @@ handle_add(Client &client, Request args, Response &r)
here */
uri = "";
const auto located_uri = LocateUri(uri, &client
const auto located_uri = LocateUri(UriPluginKind::INPUT, uri,
&client
#ifdef ENABLE_DATABASE
, nullptr
#endif

@@ -1,5 +1,5 @@
/*
* Copyright 2003-2018 The Music Player Daemon Project
* Copyright 2003-2019 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
@@ -35,6 +35,7 @@
#include "Interface.hxx"
#include "fs/Traits.hxx"
#include "util/ChronoUtil.hxx"
#include "util/RecursiveMap.hxx"
#include <functional>
@@ -186,42 +187,29 @@ PrintSongUris(Response &r, Partition &partition,
}
static void
PrintUniqueTags(Response &r, TagType tag_type,
const std::set<std::string> &values)
PrintUniqueTags(Response &r, ConstBuffer<TagType> tag_types,
const RecursiveMap<std::string> &map) noexcept
{
const char *const name = tag_item_names[tag_type];
for (const auto &i : values)
r.Format("%s: %s\n", name, i.c_str());
}
const char *const name = tag_item_names[tag_types.front()];
tag_types.pop_front();
static void
PrintGroupedUniqueTags(Response &r, TagType tag_type, TagType group,
const std::map<std::string, std::set<std::string>> &groups)
{
if (group == TAG_NUM_OF_ITEM_TYPES) {
for (const auto &i : groups)
PrintUniqueTags(r, tag_type, i.second);
return;
}
for (const auto &i : map) {
r.Format("%s: %s\n", name, i.first.c_str());
const char *const group_name = tag_item_names[group];
for (const auto &i : groups) {
r.Format("%s: %s\n", group_name, i.first.c_str());
PrintUniqueTags(r, tag_type, i.second);
if (!tag_types.empty())
PrintUniqueTags(r, tag_types, i.second);
}
}
void
PrintUniqueTags(Response &r, Partition &partition,
TagType type, TagType group,
ConstBuffer<TagType> tag_types,
const SongFilter *filter)
{
assert(type < TAG_NUM_OF_ITEM_TYPES);
const Database &db = partition.GetDatabaseOrThrow();
const DatabaseSelection selection("", true, filter);
PrintGroupedUniqueTags(r, type, group,
db.CollectUniqueTags(selection, type, group));
PrintUniqueTags(r, tag_types,
db.CollectUniqueTags(selection, tag_types));
}

@@ -1,5 +1,5 @@
/*
* Copyright 2003-2018 The Music Player Daemon Project
* Copyright 2003-2019 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
@@ -22,6 +22,7 @@
#include <stdint.h>
template<typename T> struct ConstBuffer;
enum TagType : uint8_t;
class TagMask;
class SongFilter;
@@ -45,7 +46,7 @@ PrintSongUris(Response &r, Partition &partition,
void
PrintUniqueTags(Response &r, Partition &partition,
TagType type, TagType group,
ConstBuffer<TagType> tag_types,
const SongFilter *filter);
#endif

@@ -1,5 +1,5 @@
/*
* Copyright 2003-2018 The Music Player Daemon Project
* Copyright 2003-2019 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
@@ -25,15 +25,14 @@
#include "util/Compiler.h"
#include <chrono>
#include <map>
#include <set>
#include <string>
struct DatabasePlugin;
struct DatabaseStats;
struct DatabaseSelection;
struct LightSong;
class TagMask;
template<typename Key> class RecursiveMap;
template<typename T> struct ConstBuffer;
class Database {
const DatabasePlugin &plugin;
@@ -106,13 +105,14 @@ public:
}
/**
* Collect unique values of the given tag type.
* Collect unique values of the given tag types. Each item in
* the #tag_types parameter results in one nesting level in
* the return value.
*
* Throws on error.
*/
virtual std::map<std::string, std::set<std::string>> CollectUniqueTags(const DatabaseSelection &selection,
TagType tag_type,
TagType group=TAG_NUM_OF_ITEM_TYPES) const = 0;
virtual RecursiveMap<std::string> CollectUniqueTags(const DatabaseSelection &selection,
ConstBuffer<TagType> tag_types) const = 0;
/**
* Throws on error.

@@ -1,5 +1,5 @@
/*
* Copyright 2003-2018 The Music Player Daemon Project
* Copyright 2003-2019 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
@@ -21,36 +21,32 @@
#include "Interface.hxx"
#include "song/LightSong.hxx"
#include "tag/VisitFallback.hxx"
#include "util/ConstBuffer.hxx"
#include "util/RecursiveMap.hxx"
static void
CollectTags(std::set<std::string> &result,
const Tag &tag,
TagType tag_type) noexcept
CollectUniqueTags(RecursiveMap<std::string> &result,
const Tag &tag,
ConstBuffer<TagType> tag_types) noexcept
{
VisitTagWithFallbackOrEmpty(tag, tag_type, [&result](const char *value){
result.emplace(value);
if (tag_types.empty())
return;
const auto tag_type = tag_types.shift();
VisitTagWithFallbackOrEmpty(tag, tag_type, [&result, &tag, tag_types](const char *value){
CollectUniqueTags(result[value], tag, tag_types);
});
}
static void
CollectGroupTags(std::map<std::string, std::set<std::string>> &result,
const Tag &tag,
TagType tag_type,
TagType group) noexcept
{
VisitTagWithFallbackOrEmpty(tag, group, [&](const char *group_name){
CollectTags(result[group_name], tag, tag_type);
});
}
std::map<std::string, std::set<std::string>>
RecursiveMap<std::string>
CollectUniqueTags(const Database &db, const DatabaseSelection &selection,
TagType tag_type, TagType group)
ConstBuffer<TagType> tag_types)
{
std::map<std::string, std::set<std::string>> result;
RecursiveMap<std::string> result;
db.Visit(selection, [&result, tag_type, group](const LightSong &song){
CollectGroupTags(result, song.tag, tag_type, group);
db.Visit(selection, [&result, tag_types](const LightSong &song){
CollectUniqueTags(result, song.tag, tag_types);
});
return result;

@@ -1,5 +1,5 @@
/*
* Copyright 2003-2018 The Music Player Daemon Project
* Copyright 2003-2019 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
@@ -29,9 +29,11 @@
class TagMask;
class Database;
struct DatabaseSelection;
template<typename Key> class RecursiveMap;
template<typename T> struct ConstBuffer;
std::map<std::string, std::set<std::string>>
RecursiveMap<std::string>
CollectUniqueTags(const Database &db, const DatabaseSelection &selection,
TagType tag_type, TagType group);
ConstBuffer<TagType> tag_types);
#endif

@@ -9,6 +9,11 @@ db_api_dep = declare_dependency(
link_with: db_api,
)
if not enable_database
db_glue_dep = db_api_dep
subdir_done()
endif
subdir('plugins')
db_glue_sources = [

@@ -38,6 +38,8 @@
#include "tag/Tag.hxx"
#include "tag/Mask.hxx"
#include "tag/ParseName.hxx"
#include "util/ConstBuffer.hxx"
#include "util/RecursiveMap.hxx"
#include "util/ScopeExit.hxx"
#include "util/RuntimeError.hxx"
#include "protocol/Ack.hxx"
@@ -127,9 +129,8 @@ public:
VisitSong visit_song,
VisitPlaylist visit_playlist) const override;
std::map<std::string, std::set<std::string>> CollectUniqueTags(const DatabaseSelection &selection,
TagType tag_type,
TagType group) const override;
RecursiveMap<std::string> CollectUniqueTags(const DatabaseSelection &selection,
ConstBuffer<TagType> tag_types) const override;
DatabaseStats GetStats(const DatabaseSelection &selection) const override;
@@ -412,8 +413,7 @@ SendConstraints(mpd_connection *connection, const DatabaseSelection &selection)
static bool
SendGroup(mpd_connection *connection, TagType group)
{
if (group == TAG_NUM_OF_ITEM_TYPES)
return true;
assert(group != TAG_NUM_OF_ITEM_TYPES);
#if LIBMPDCLIENT_CHECK_VERSION(2,12,0)
const auto tag = Convert(group);
@@ -428,6 +428,19 @@ SendGroup(mpd_connection *connection, TagType group)
#endif
}
static bool
SendGroup(mpd_connection *connection, ConstBuffer<TagType> group)
{
while (!group.empty()) {
if (!SendGroup(connection, group.back()))
return false;
group.pop_back();
}
return true;
}
ProxyDatabase::ProxyDatabase(EventLoop &_loop, DatabaseListener &_listener,
const ConfigBlock &block)
:Database(proxy_db_plugin),
@@ -568,7 +581,8 @@ ProxyDatabase::OnSocketReady(gcc_unused unsigned flags) noexcept
if (!is_idle) {
// TODO: can this happen?
IdleMonitor::Schedule();
return false;
SocketMonitor::Cancel();
return true;
}
unsigned idle = (unsigned)mpd_recv_idle(connection, false);
@@ -586,7 +600,8 @@ ProxyDatabase::OnSocketReady(gcc_unused unsigned flags) noexcept
idle_received |= idle;
is_idle = false;
IdleMonitor::Schedule();
return false;
SocketMonitor::Cancel();
return true;
}
void
@@ -981,17 +996,20 @@ ProxyDatabase::Visit(const DatabaseSelection &selection,
helper.Commit();
}
std::map<std::string, std::set<std::string>>
RecursiveMap<std::string>
ProxyDatabase::CollectUniqueTags(const DatabaseSelection &selection,
TagType tag_type, TagType group) const
ConstBuffer<TagType> tag_types) const
try {
// TODO: eliminate the const_cast
const_cast<ProxyDatabase *>(this)->EnsureConnected();
enum mpd_tag_type tag_type2 = Convert(tag_type);
enum mpd_tag_type tag_type2 = Convert(tag_types.back());
if (tag_type2 == MPD_TAG_COUNT)
throw std::runtime_error("Unsupported tag");
auto group = tag_types;
group.pop_back();
if (!mpd_search_db_tags(connection, tag_type2) ||
!SendConstraints(connection, selection) ||
!SendGroup(connection, group))
@@ -1000,44 +1018,33 @@ try {
if (!mpd_search_commit(connection))
ThrowError(connection);
std::map<std::string, std::set<std::string>> result;
RecursiveMap<std::string> result;
std::vector<RecursiveMap<std::string> *> position;
position.emplace_back(&result);
if (group == TAG_NUM_OF_ITEM_TYPES) {
auto &values = result[std::string()];
while (auto *pair = mpd_recv_pair(connection)) {
AtScopeExit(this, pair) {
mpd_return_pair(connection, pair);
};
while (auto *pair = mpd_recv_pair(connection)) {
AtScopeExit(this, pair) {
mpd_return_pair(connection, pair);
};
const auto current_type = tag_name_parse_i(pair->name);
if (current_type == TAG_NUM_OF_ITEM_TYPES)
continue;
const auto current_type = tag_name_parse_i(pair->name);
if (current_type == TAG_NUM_OF_ITEM_TYPES)
continue;
auto it = std::find(tag_types.begin(), tag_types.end(),
current_type);
if (it == tag_types.end())
continue;
if (current_type == tag_type)
values.emplace(pair->value);
}
} else {
std::set<std::string> *current_group = nullptr;
size_t i = std::distance(tag_types.begin(), it);
if (i > position.size())
continue;
while (auto *pair = mpd_recv_pair(connection)) {
AtScopeExit(this, pair) {
mpd_return_pair(connection, pair);
};
if (i + 1 < position.size())
position.resize(i + 1);
const auto current_type = tag_name_parse_i(pair->name);
if (current_type == TAG_NUM_OF_ITEM_TYPES)
continue;
if (current_type == tag_type) {
if (current_group == nullptr)
current_group = &result[std::string()];
current_group->emplace(pair->value);
} else if (current_type == group) {
current_group = &result[pair->value];
}
}
auto &parent = *position[i];
position.emplace_back(&parent[pair->value]);
}
if (!mpd_response_finish(connection))

@@ -42,6 +42,8 @@
#include "fs/FileSystem.hxx"
#include "util/CharUtil.hxx"
#include "util/Domain.hxx"
#include "util/ConstBuffer.hxx"
#include "util/RecursiveMap.hxx"
#include "Log.hxx"
#ifdef ENABLE_ZLIB
@@ -329,11 +331,11 @@ SimpleDatabase::Visit(const DatabaseSelection &selection,
"No such directory");
}
std::map<std::string, std::set<std::string>>
RecursiveMap<std::string>
SimpleDatabase::CollectUniqueTags(const DatabaseSelection &selection,
TagType tag_type, TagType group) const
ConstBuffer<TagType> tag_types) const
{
return ::CollectUniqueTags(*this, selection, tag_type, group);
return ::CollectUniqueTags(*this, selection, tag_types);
}
DatabaseStats

@@ -122,9 +122,8 @@ public:
VisitSong visit_song,
VisitPlaylist visit_playlist) const override;
std::map<std::string, std::set<std::string>> CollectUniqueTags(const DatabaseSelection &selection,
TagType tag_type,
TagType group) const override;
RecursiveMap<std::string> CollectUniqueTags(const DatabaseSelection &selection,
ConstBuffer<TagType> tag_types) const override;
DatabaseStats GetStats(const DatabaseSelection &selection) const override;

@@ -40,10 +40,11 @@
#include "tag/Mask.hxx"
#include "fs/Traits.hxx"
#include "Log.hxx"
#include "util/ConstBuffer.hxx"
#include "util/RecursiveMap.hxx"
#include "util/SplitString.hxx"
#include <string>
#include <set>
#include <assert.h>
#include <string.h>
@@ -97,9 +98,8 @@ public:
VisitSong visit_song,
VisitPlaylist visit_playlist) const override;
std::map<std::string, std::set<std::string>> CollectUniqueTags(const DatabaseSelection &selection,
TagType tag_type,
TagType group) const override;
RecursiveMap<std::string> CollectUniqueTags(const DatabaseSelection &selection,
ConstBuffer<TagType> tag_types) const override;
DatabaseStats GetStats(const DatabaseSelection &selection) const override;
@@ -624,11 +624,11 @@ UpnpDatabase::Visit(const DatabaseSelection &selection,
helper.Commit();
}
std::map<std::string, std::set<std::string>>
RecursiveMap<std::string>
UpnpDatabase::CollectUniqueTags(const DatabaseSelection &selection,
TagType tag, TagType group) const
ConstBuffer<TagType> tag_types) const
{
return ::CollectUniqueTags(*this, selection, tag, group);
return ::CollectUniqueTags(*this, selection, tag_types);
}
DatabaseStats

@@ -147,6 +147,18 @@ DecoderControl::Seek(SongTime t)
seek_error = false;
SynchronousCommandLocked(DecoderCommand::SEEK);
while (state == DecoderState::START)
/* If the decoder falls back to DecoderState::START,
this means that our SEEK command arrived too late,
and the decoder had meanwhile finished decoding and
went idle. Our SEEK command is finished, but that
means only that the decoder thread has launched the
decoder. To work around illegal states, we wait
until the decoder plugin has become ready. This is
a kludge, built on top of the "late seek" kludge.
Not exactly elegant, sorry. */
WaitForDecoder();
if (seek_error)
throw std::runtime_error("Decoder failed to seek");
}

@@ -320,6 +320,11 @@ public:
gcc_pure
bool IsCurrentSong(const DetachedSong &_song) const noexcept;
gcc_pure
bool IsUnseekableCurrentSong(const DetachedSong &_song) const noexcept {
return !seekable && IsCurrentSong(_song);
}
gcc_pure
bool IsSeekableCurrentSong(const DetachedSong &_song) const noexcept {
return seekable && IsCurrentSong(_song);

@@ -20,6 +20,8 @@
#include "config.h"
#include "DecoderList.hxx"
#include "DecoderPlugin.hxx"
#include "PluginUnavailable.hxx"
#include "Log.hxx"
#include "config/Data.hxx"
#include "config/Block.hxx"
#include "plugins/AudiofileDecoderPlugin.hxx"
@@ -45,6 +47,7 @@
#include "plugins/FluidsynthDecoderPlugin.hxx"
#include "plugins/SidplayDecoderPlugin.hxx"
#include "util/Macros.hxx"
#include "util/RuntimeError.hxx"
#include <string.h>
@@ -147,8 +150,17 @@ decoder_plugin_init_all(const ConfigData &config)
if (param != nullptr)
param->SetUsed();
if (plugin.Init(*param))
decoder_plugins_enabled[i] = true;
try {
if (plugin.Init(*param))
decoder_plugins_enabled[i] = true;
} catch (const PluginUnavailable &e) {
FormatError(e,
"Decoder plugin '%s' is unavailable",
plugin.name);
} catch (...) {
std::throw_with_nested(FormatRuntimeError("Failed to initialize decoder plugin '%s'",
plugin.name));
}
}
}

@@ -455,6 +455,11 @@ static void
decoder_run_song(DecoderControl &dc,
const DetachedSong &song, const char *uri, Path path_fs)
{
if (dc.command == DecoderCommand::SEEK)
/* if the SEEK command arrived too late, start the
decoder at the seek position */
dc.start_time = dc.seek_time;
DecoderBridge bridge(dc, dc.start_time.IsPositive(),
/* pass the song tag only if it's
authoritative, i.e. if it's a local

@@ -362,6 +362,7 @@ dsdiff_decode_chunk(DecoderClient &client, InputStream &is,
unsigned channels, unsigned sample_rate,
const offset_type total_bytes)
{
const unsigned kbit_rate = channels * sample_rate / 1000;
const offset_type start_offset = is.GetOffset();
uint8_t buffer[8192];
@@ -408,7 +409,7 @@ dsdiff_decode_chunk(DecoderClient &client, InputStream &is,
bit_reverse_buffer(buffer, buffer + nbytes);
cmd = client.SubmitData(is, buffer, nbytes,
sample_rate / 1000);
kbit_rate);
}
return true;

@@ -256,6 +256,7 @@ dsf_decode_chunk(DecoderClient &client, InputStream &is,
offset_type n_blocks,
bool bitreverse)
{
const unsigned kbit_rate = channels * sample_rate / 1000;
const size_t block_size = channels * DSF_BLOCK_SIZE;
const offset_type start_offset = is.GetOffset();
@@ -291,7 +292,7 @@ dsf_decode_chunk(DecoderClient &client, InputStream &is,
cmd = client.SubmitData(is,
interleaved_buffer, block_size,
sample_rate / 1000);
kbit_rate);
++i;
}

@@ -21,14 +21,13 @@
#include "MadDecoderPlugin.hxx"
#include "../DecoderAPI.hxx"
#include "input/InputStream.hxx"
#include "config/Block.hxx"
#include "tag/Id3Scan.hxx"
#include "tag/Id3ReplayGain.hxx"
#include "tag/Rva2.hxx"
#include "tag/Handler.hxx"
#include "tag/ReplayGain.hxx"
#include "tag/MixRamp.hxx"
#include "CheckAudioFormat.hxx"
#include "util/Clamp.hxx"
#include "util/StringCompare.hxx"
#include "util/Domain.hxx"
#include "Log.hxx"
@@ -40,8 +39,6 @@
#include <id3tag.h>
#endif
#include <stdexcept>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
@@ -49,17 +46,17 @@
static constexpr unsigned long FRAMES_CUSHION = 2000;
enum mp3_action {
DECODE_SKIP = -3,
DECODE_BREAK = -2,
DECODE_CONT = -1,
DECODE_OK = 0
enum class MadDecoderAction {
SKIP,
BREAK,
CONT,
OK
};
enum muteframe {
MUTEFRAME_NONE,
MUTEFRAME_SKIP,
MUTEFRAME_SEEK
enum class MadDecoderMuteFrame {
NONE,
SKIP,
SEEK
};
/* the number of samples of silence the decoder inserts at start */
@@ -79,7 +76,7 @@ ToSongTime(mad_timer_t t) noexcept
}
static inline int32_t
mad_fixed_to_24_sample(mad_fixed_t sample)
mad_fixed_to_24_sample(mad_fixed_t sample) noexcept
{
static constexpr unsigned bits = 24;
static constexpr mad_fixed_t MIN = -MAD_F_ONE;
@@ -88,73 +85,79 @@ mad_fixed_to_24_sample(mad_fixed_t sample)
/* round */
sample = sample + (1L << (MAD_F_FRACBITS - bits));
/* clip */
if (gcc_unlikely(sample > MAX))
sample = MAX;
else if (gcc_unlikely(sample < MIN))
sample = MIN;
/* quantize */
return sample >> (MAD_F_FRACBITS + 1 - bits);
return Clamp(sample, MIN, MAX)
>> (MAD_F_FRACBITS + 1 - bits);
}
static void
mad_fixed_to_24_buffer(int32_t *dest, const struct mad_synth *synth,
unsigned int start, unsigned int end,
mad_fixed_to_24_buffer(int32_t *dest, const struct mad_pcm &src,
size_t start, size_t end,
unsigned int num_channels)
{
for (unsigned i = start; i < end; ++i)
for (size_t i = start; i < end; ++i)
for (unsigned c = 0; c < num_channels; ++c)
*dest++ = mad_fixed_to_24_sample(synth->pcm.samples[c][i]);
*dest++ = mad_fixed_to_24_sample(src.samples[c][i]);
}
static bool
mp3_plugin_init(const ConfigBlock &block)
mad_plugin_init(const ConfigBlock &block)
{
gapless_playback = block.GetBlockValue("gapless",
DEFAULT_GAPLESS_MP3_PLAYBACK);
return true;
}
struct MadDecoder {
class MadDecoder {
static constexpr size_t READ_BUFFER_SIZE = 40960;
static constexpr size_t MP3_DATA_OUTPUT_BUFFER_SIZE = 2048;
struct mad_stream stream;
struct mad_frame frame;
struct mad_synth synth;
mad_timer_t timer;
unsigned char input_buffer[READ_BUFFER_SIZE];
int32_t output_buffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
int32_t output_buffer[sizeof(mad_pcm::samples) / sizeof(mad_fixed_t)];
SignedSongTime total_time;
SongTime elapsed_time;
SongTime seek_time;
enum muteframe mute_frame = MUTEFRAME_NONE;
MadDecoderMuteFrame mute_frame = MadDecoderMuteFrame::NONE;
long *frame_offsets = nullptr;
mad_timer_t *times = nullptr;
unsigned long highest_frame = 0;
unsigned long max_frames = 0;
unsigned long current_frame = 0;
unsigned int drop_start_frames = 0;
unsigned int drop_end_frames = 0;
size_t highest_frame = 0;
size_t max_frames = 0;
size_t current_frame = 0;
unsigned int drop_start_frames;
unsigned int drop_end_frames;
unsigned int drop_start_samples = 0;
unsigned int drop_end_samples = 0;
bool found_replay_gain = false;
bool found_first_frame = false;
bool decoded_first_frame = false;
unsigned long bit_rate;
/**
* If this flag is true, then end-of-file was seen and a
* padding of 8 zero bytes were appended to #input_buffer, to
* allow libmad to decode the last frame.
*/
bool was_eof = false;
DecoderClient *const client;
InputStream &input_stream;
enum mad_layer layer = mad_layer(0);
MadDecoder(DecoderClient *client, InputStream &input_stream);
~MadDecoder();
public:
MadDecoder(DecoderClient *client, InputStream &input_stream) noexcept;
~MadDecoder() noexcept;
bool Seek(long offset);
bool FillBuffer();
void ParseId3(size_t tagsize, Tag *tag);
enum mp3_action DecodeNextFrameHeader(Tag *tag);
enum mp3_action DecodeNextFrame();
void RunDecoder() noexcept;
bool RunScan(TagHandler &handler) noexcept;
private:
bool Seek(long offset) noexcept;
bool FillBuffer() noexcept;
void ParseId3(size_t tagsize, Tag *tag) noexcept;
MadDecoderAction DecodeNextFrameHeader(Tag *tag) noexcept;
MadDecoderAction DecodeNextFrame() noexcept;
gcc_pure
offset_type ThisFrameOffset() const noexcept;
@@ -165,11 +168,11 @@ struct MadDecoder {
/**
* Attempt to calulcate the length of the song from filesize
*/
void FileSizeToSongLength();
void FileSizeToSongLength() noexcept;
bool DecodeFirstFrame(Tag *tag);
bool DecodeFirstFrame(Tag *tag) noexcept;
void AllocateBuffers() {
void AllocateBuffers() noexcept {
assert(max_frames > 0);
assert(frame_offsets == nullptr);
assert(times == nullptr);
@@ -179,27 +182,39 @@ struct MadDecoder {
}
gcc_pure
long TimeToFrame(SongTime t) const noexcept;
size_t TimeToFrame(SongTime t) const noexcept;
void UpdateTimerNextFrame();
/**
* Record the current frame's offset in the "frame_offsets"
* buffer and go forward to the next frame, updating the
* attributes "current_frame" and "timer".
*/
void UpdateTimerNextFrame() noexcept;
/**
* Sends the synthesized current frame via
* DecoderClient::SubmitData().
*/
DecoderCommand SendPCM(unsigned i, unsigned pcm_length);
DecoderCommand SubmitPCM(size_t start, size_t n) noexcept;
/**
* Synthesize the current frame and send it via
* DecoderClient::SubmitData().
*/
DecoderCommand SyncAndSend();
DecoderCommand SynthAndSubmit() noexcept;
bool Read();
/**
* @return false to stop decoding
*/
bool HandleCurrentFrame() noexcept;
bool LoadNextFrame() noexcept;
bool Read() noexcept;
};
MadDecoder::MadDecoder(DecoderClient *_client,
InputStream &_input_stream)
InputStream &_input_stream) noexcept
:client(_client), input_stream(_input_stream)
{
mad_stream_init(&stream);
@@ -210,7 +225,7 @@ MadDecoder::MadDecoder(DecoderClient *_client,
}
inline bool
MadDecoder::Seek(long offset)
MadDecoder::Seek(long offset) noexcept
{
try {
input_stream.LockSeek(offset);
@@ -225,32 +240,38 @@ MadDecoder::Seek(long offset)
}
inline bool
MadDecoder::FillBuffer()
MadDecoder::FillBuffer() noexcept
{
size_t remaining, length;
unsigned char *dest;
/* amount of rest data still residing in the buffer */
size_t rest_size = 0;
size_t max_read_size = sizeof(input_buffer);
unsigned char *dest = input_buffer;
if (stream.next_frame != nullptr) {
remaining = stream.bufend - stream.next_frame;
memmove(input_buffer, stream.next_frame, remaining);
dest = input_buffer + remaining;
length = READ_BUFFER_SIZE - remaining;
} else {
remaining = 0;
length = READ_BUFFER_SIZE;
dest = input_buffer;
rest_size = stream.bufend - stream.next_frame;
memmove(input_buffer, stream.next_frame, rest_size);
dest += rest_size;
max_read_size -= rest_size;
}
/* we've exhausted the read buffer, so give up!, these potential
* mp3 frames are way too big, and thus unlikely to be mp3 frames */
if (length == 0)
if (max_read_size == 0)
return false;
length = decoder_read(client, input_stream, dest, length);
if (length == 0)
return false;
size_t nbytes = decoder_read(client, input_stream,
dest, max_read_size);
if (nbytes == 0) {
if (was_eof || max_read_size < MAD_BUFFER_GUARD)
return false;
mad_stream_buffer(&stream, input_buffer, length + remaining);
was_eof = true;
nbytes = MAD_BUFFER_GUARD;
memset(dest, 0, nbytes);
}
mad_stream_buffer(&stream, input_buffer, rest_size + nbytes);
stream.error = MAD_ERROR_NONE;
return true;
@@ -286,7 +307,7 @@ parse_id3_mixramp(struct id3_tag *tag) noexcept
#endif
inline void
MadDecoder::ParseId3(size_t tagsize, Tag *mpd_tag)
MadDecoder::ParseId3(size_t tagsize, Tag *mpd_tag) noexcept
{
#ifdef ENABLE_ID3TAG
std::unique_ptr<id3_byte_t[]> allocated;
@@ -354,7 +375,7 @@ MadDecoder::ParseId3(size_t tagsize, Tag *mpd_tag)
* of the ID3 frame.
*/
static signed long
id3_tag_query(const void *p0, size_t length)
id3_tag_query(const void *p0, size_t length) noexcept
{
const char *p = (const char *)p0;
@@ -364,26 +385,26 @@ id3_tag_query(const void *p0, size_t length)
}
#endif /* !ENABLE_ID3TAG */
static enum mp3_action
RecoverFrameError(struct mad_stream &stream)
static MadDecoderAction
RecoverFrameError(const struct mad_stream &stream) noexcept
{
if (MAD_RECOVERABLE(stream.error))
return DECODE_SKIP;
return MadDecoderAction::SKIP;
else if (stream.error == MAD_ERROR_BUFLEN)
return DECODE_CONT;
return MadDecoderAction::CONT;
FormatWarning(mad_domain,
"unrecoverable frame level error: %s",
mad_stream_errorstr(&stream));
return DECODE_BREAK;
return MadDecoderAction::BREAK;
}
enum mp3_action
MadDecoder::DecodeNextFrameHeader(Tag *tag)
MadDecoderAction
MadDecoder::DecodeNextFrameHeader(Tag *tag) noexcept
{
if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
!FillBuffer())
return DECODE_BREAK;
return MadDecoderAction::BREAK;
if (mad_header_decode(&frame.header, &stream)) {
if (stream.error == MAD_ERROR_LOSTSYNC && stream.this_frame) {
@@ -393,7 +414,7 @@ MadDecoder::DecodeNextFrameHeader(Tag *tag)
if (tagsize > 0) {
ParseId3((size_t)tagsize, tag);
return DECODE_CONT;
return MadDecoderAction::CONT;
}
}
@@ -404,24 +425,24 @@ MadDecoder::DecodeNextFrameHeader(Tag *tag)
if (layer == (mad_layer)0) {
if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
/* Only layer 2 and 3 have been tested to work */
return DECODE_SKIP;
return MadDecoderAction::SKIP;
}
layer = new_layer;
} else if (new_layer != layer) {
/* Don't decode frames with a different layer than the first */
return DECODE_SKIP;
return MadDecoderAction::SKIP;
}
return DECODE_OK;
return MadDecoderAction::OK;
}
enum mp3_action
MadDecoder::DecodeNextFrame()
MadDecoderAction
MadDecoder::DecodeNextFrame() noexcept
{
if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
!FillBuffer())
return DECODE_BREAK;
return MadDecoderAction::BREAK;
if (mad_frame_decode(&frame, &stream)) {
if (stream.error == MAD_ERROR_LOSTSYNC) {
@@ -430,14 +451,14 @@ MadDecoder::DecodeNextFrame()
stream.this_frame);
if (tagsize > 0) {
mad_stream_skip(&stream, tagsize);
return DECODE_CONT;
return MadDecoderAction::CONT;
}
}
return RecoverFrameError(stream);
}
return DECODE_OK;
return MadDecoderAction::OK;
}
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
@@ -476,7 +497,7 @@ struct lame {
};
static bool
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen) noexcept
{
int bitlen = *oldbitlen;
@@ -556,7 +577,7 @@ parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
}
static bool
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen) noexcept
{
/* Unlike the xing header, the lame tag has a fixed length. Fail if
* not all 36 bytes (288 bits) are there. */
@@ -647,7 +668,7 @@ parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
}
static inline SongTime
mp3_frame_duration(const struct mad_frame *frame)
mad_frame_duration(const struct mad_frame *frame) noexcept
{
return ToSongTime(frame->header.duration);
}
@@ -672,12 +693,12 @@ MadDecoder::RestIncludingThisFrame() const noexcept
}
inline void
MadDecoder::FileSizeToSongLength()
MadDecoder::FileSizeToSongLength() noexcept
{
if (input_stream.KnownSize()) {
offset_type rest = RestIncludingThisFrame();
const SongTime frame_duration = mp3_frame_duration(&frame);
const SongTime frame_duration = mad_frame_duration(&frame);
const SongTime duration =
SongTime::FromScale<uint64_t>(rest,
frame.header.bitrate / 8);
@@ -694,25 +715,25 @@ MadDecoder::FileSizeToSongLength()
}
inline bool
MadDecoder::DecodeFirstFrame(Tag *tag)
MadDecoder::DecodeFirstFrame(Tag *tag) noexcept
{
struct xing xing;
while (true) {
enum mp3_action ret;
MadDecoderAction ret;
do {
ret = DecodeNextFrameHeader(tag);
} while (ret == DECODE_CONT);
if (ret == DECODE_BREAK)
} while (ret == MadDecoderAction::CONT);
if (ret == MadDecoderAction::BREAK)
return false;
if (ret == DECODE_SKIP) continue;
if (ret == MadDecoderAction::SKIP) continue;
do {
ret = DecodeNextFrame();
} while (ret == DECODE_CONT);
if (ret == DECODE_BREAK)
} while (ret == MadDecoderAction::CONT);
if (ret == MadDecoderAction::BREAK)
return false;
if (ret == DECODE_OK) break;
if (ret == MadDecoderAction::OK) break;
}
struct mad_bitptr ptr = stream.anc_ptr;
@@ -724,7 +745,7 @@ MadDecoder::DecodeFirstFrame(Tag *tag)
* if an xing tag exists, use that!
*/
if (parse_xing(&xing, &ptr, &bitlen)) {
mute_frame = MUTEFRAME_SKIP;
mute_frame = MadDecoderMuteFrame::SKIP;
if ((xing.flags & XING_FRAMES) && xing.frames) {
mad_timer_t duration = frame.header.duration;
@@ -736,9 +757,17 @@ MadDecoder::DecodeFirstFrame(Tag *tag)
struct lame lame;
if (parse_lame(&lame, &ptr, &bitlen)) {
if (gapless_playback && input_stream.IsSeekable()) {
/* libmad inserts 529 samples of
silence at the beginning and
removes those 529 samples at the
end */
drop_start_samples = lame.encoder_delay +
DECODERDELAY;
drop_end_samples = lame.encoder_padding;
if (drop_end_samples > DECODERDELAY)
drop_end_samples -= DECODERDELAY;
else
drop_end_samples = 0;
}
/* Album gain isn't currently used. See comment in
@@ -767,7 +796,7 @@ MadDecoder::DecodeFirstFrame(Tag *tag)
return true;
}
MadDecoder::~MadDecoder()
MadDecoder::~MadDecoder() noexcept
{
mad_synth_finish(&synth);
mad_frame_finish(&frame);
@@ -777,10 +806,10 @@ MadDecoder::~MadDecoder()
delete[] times;
}
long
size_t
MadDecoder::TimeToFrame(SongTime t) const noexcept
{
unsigned long i;
size_t i;
for (i = 0; i < highest_frame; ++i) {
auto frame_time = ToSongTime(times[i]);
@@ -792,12 +821,11 @@ MadDecoder::TimeToFrame(SongTime t) const noexcept
}
void
MadDecoder::UpdateTimerNextFrame()
MadDecoder::UpdateTimerNextFrame() noexcept
{
if (current_frame >= highest_frame) {
/* record this frame's properties in frame_offsets
(for seeking) and times */
bit_rate = frame.header.bitrate;
if (current_frame >= max_frames)
/* cap current_frame */
@@ -818,36 +846,22 @@ MadDecoder::UpdateTimerNextFrame()
}
DecoderCommand
MadDecoder::SendPCM(unsigned i, unsigned pcm_length)
MadDecoder::SubmitPCM(size_t i, size_t pcm_length) noexcept
{
unsigned max_samples = sizeof(output_buffer) /
sizeof(output_buffer[0]) /
MAD_NCHANNELS(&frame.header);
size_t num_samples = pcm_length - i;
while (i < pcm_length) {
unsigned int num_samples = pcm_length - i;
if (num_samples > max_samples)
num_samples = max_samples;
mad_fixed_to_24_buffer(output_buffer, synth.pcm,
i, i + num_samples,
MAD_NCHANNELS(&frame.header));
num_samples *= MAD_NCHANNELS(&frame.header);
i += num_samples;
mad_fixed_to_24_buffer(output_buffer, &synth,
i - num_samples, i,
MAD_NCHANNELS(&frame.header));
num_samples *= MAD_NCHANNELS(&frame.header);
auto cmd = client->SubmitData(input_stream, output_buffer,
sizeof(output_buffer[0]) * num_samples,
bit_rate / 1000);
if (cmd != DecoderCommand::NONE)
return cmd;
}
return DecoderCommand::NONE;
return client->SubmitData(input_stream, output_buffer,
sizeof(output_buffer[0]) * num_samples,
frame.header.bitrate / 1000);
}
inline DecoderCommand
MadDecoder::SyncAndSend()
MadDecoder::SynthAndSubmit() noexcept
{
mad_synth_frame(&synth, &frame);
@@ -864,33 +878,33 @@ MadDecoder::SyncAndSend()
drop_start_frames--;
return DecoderCommand::NONE;
} else if ((drop_end_frames > 0) &&
(current_frame == (max_frames + 1 - drop_end_frames))) {
current_frame == max_frames - drop_end_frames) {
/* stop decoding, effectively dropping all remaining
frames */
return DecoderCommand::STOP;
}
unsigned i = 0;
size_t i = 0;
if (!decoded_first_frame) {
i = drop_start_samples;
decoded_first_frame = true;
}
unsigned pcm_length = synth.pcm.length;
size_t pcm_length = synth.pcm.length;
if (drop_end_samples &&
(current_frame == max_frames - drop_end_frames)) {
current_frame == max_frames - drop_end_frames - 1) {
if (drop_end_samples >= pcm_length)
pcm_length = 0;
else
pcm_length -= drop_end_samples;
return DecoderCommand::STOP;
pcm_length -= drop_end_samples;
}
auto cmd = SendPCM(i, pcm_length);
auto cmd = SubmitPCM(i, pcm_length);
if (cmd != DecoderCommand::NONE)
return cmd;
if (drop_end_samples &&
(current_frame == max_frames - drop_end_frames))
current_frame == max_frames - drop_end_frames - 1)
/* stop decoding, effectively dropping
* all remaining samples */
return DecoderCommand::STOP;
@@ -899,44 +913,51 @@ MadDecoder::SyncAndSend()
}
inline bool
MadDecoder::Read()
MadDecoder::HandleCurrentFrame() noexcept
{
UpdateTimerNextFrame();
switch (mute_frame) {
DecoderCommand cmd;
case MUTEFRAME_SKIP:
mute_frame = MUTEFRAME_NONE;
case MadDecoderMuteFrame::SKIP:
mute_frame = MadDecoderMuteFrame::NONE;
break;
case MUTEFRAME_SEEK:
case MadDecoderMuteFrame::SEEK:
if (elapsed_time >= seek_time)
mute_frame = MUTEFRAME_NONE;
mute_frame = MadDecoderMuteFrame::NONE;
UpdateTimerNextFrame();
break;
case MUTEFRAME_NONE:
cmd = SyncAndSend();
case MadDecoderMuteFrame::NONE:
cmd = SynthAndSubmit();
UpdateTimerNextFrame();
if (cmd == DecoderCommand::SEEK) {
assert(input_stream.IsSeekable());
const auto t = client->GetSeekTime();
unsigned long j = TimeToFrame(t);
size_t j = TimeToFrame(t);
if (j < highest_frame) {
if (Seek(frame_offsets[j])) {
current_frame = j;
was_eof = false;
client->CommandFinished();
} else
client->SeekError();
} else {
seek_time = t;
mute_frame = MUTEFRAME_SEEK;
mute_frame = MadDecoderMuteFrame::SEEK;
client->CommandFinished();
}
} else if (cmd != DecoderCommand::NONE)
return false;
}
return true;
}
inline bool
MadDecoder::LoadNextFrame() noexcept
{
while (true) {
enum mp3_action ret;
MadDecoderAction ret;
do {
Tag tag;
@@ -945,84 +966,104 @@ MadDecoder::Read()
if (!tag.IsEmpty())
client->SubmitTag(input_stream,
std::move(tag));
} while (ret == DECODE_CONT);
if (ret == DECODE_BREAK)
} while (ret == MadDecoderAction::CONT);
if (ret == MadDecoderAction::BREAK)
return false;
const bool skip = ret == DECODE_SKIP;
const bool skip = ret == MadDecoderAction::SKIP;
if (mute_frame == MUTEFRAME_NONE) {
if (mute_frame == MadDecoderMuteFrame::NONE) {
do {
ret = DecodeNextFrame();
} while (ret == DECODE_CONT);
if (ret == DECODE_BREAK)
} while (ret == MadDecoderAction::CONT);
if (ret == MadDecoderAction::BREAK)
return false;
}
if (!skip && ret == DECODE_OK)
if (!skip && ret == MadDecoderAction::OK)
return true;
}
}
static void
mp3_decode(DecoderClient &client, InputStream &input_stream)
inline bool
MadDecoder::Read() noexcept
{
MadDecoder data(&client, input_stream);
return HandleCurrentFrame() &&
LoadNextFrame();
}
inline void
MadDecoder::RunDecoder() noexcept
{
assert(client != nullptr);
Tag tag;
if (!data.DecodeFirstFrame(&tag)) {
if (client.GetCommand() == DecoderCommand::NONE)
if (!DecodeFirstFrame(&tag)) {
if (client->GetCommand() == DecoderCommand::NONE)
LogError(mad_domain,
"input/Input does not appear to be a mp3 bit stream");
"input does not appear to be a mp3 bit stream");
return;
}
data.AllocateBuffers();
AllocateBuffers();
client.Ready(CheckAudioFormat(data.frame.header.samplerate,
SampleFormat::S24_P32,
MAD_NCHANNELS(&data.frame.header)),
input_stream.IsSeekable(),
data.total_time);
client->Ready(CheckAudioFormat(frame.header.samplerate,
SampleFormat::S24_P32,
MAD_NCHANNELS(&frame.header)),
input_stream.IsSeekable(),
total_time);
if (!tag.IsEmpty())
client.SubmitTag(input_stream, std::move(tag));
client->SubmitTag(input_stream, std::move(tag));
while (data.Read()) {}
while (Read()) {}
}
static bool
mad_decoder_scan_stream(InputStream &is, TagHandler &handler) noexcept
static void
mad_decode(DecoderClient &client, InputStream &input_stream)
{
MadDecoder data(nullptr, is);
if (!data.DecodeFirstFrame(nullptr))
MadDecoder data(&client, input_stream);
data.RunDecoder();
}
inline bool
MadDecoder::RunScan(TagHandler &handler) noexcept
{
if (!DecodeFirstFrame(nullptr))
return false;
if (!data.total_time.IsNegative())
handler.OnDuration(SongTime(data.total_time));
if (!total_time.IsNegative())
handler.OnDuration(SongTime(total_time));
try {
handler.OnAudioFormat(CheckAudioFormat(data.frame.header.samplerate,
handler.OnAudioFormat(CheckAudioFormat(frame.header.samplerate,
SampleFormat::S24_P32,
MAD_NCHANNELS(&data.frame.header)));
MAD_NCHANNELS(&frame.header)));
} catch (...) {
}
return true;
}
static const char *const mp3_suffixes[] = { "mp3", "mp2", nullptr };
static const char *const mp3_mime_types[] = { "audio/mpeg", nullptr };
static bool
mad_decoder_scan_stream(InputStream &is, TagHandler &handler) noexcept
{
MadDecoder data(nullptr, is);
return data.RunScan(handler);
}
static const char *const mad_suffixes[] = { "mp3", "mp2", nullptr };
static const char *const mad_mime_types[] = { "audio/mpeg", nullptr };
const struct DecoderPlugin mad_decoder_plugin = {
"mad",
mp3_plugin_init,
mad_plugin_init,
nullptr,
mp3_decode,
mad_decode,
nullptr,
nullptr,
mad_decoder_scan_stream,
nullptr,
mp3_suffixes,
mp3_mime_types,
mad_suffixes,
mad_mime_types,
};

@@ -137,6 +137,28 @@ mpc_to_mpd_buffer(MpcdecSampleTraits::pointer_type dest,
*dest++ = mpc_to_mpd_sample(*src++);
}
static constexpr ReplayGainTuple
ImportMpcdecReplayGain(mpc_uint16_t gain, mpc_uint16_t peak) noexcept
{
auto t = ReplayGainTuple::Undefined();
if (gain != 0 && peak != 0) {
t.gain = MPC_OLD_GAIN_REF - (gain / 256.);
t.peak = pow(10, peak / 256. / 20) / 32767;
}
return t;
}
static constexpr ReplayGainInfo
ImportMpcdecReplayGain(const mpc_streaminfo &info) noexcept
{
auto rgi = ReplayGainInfo::Undefined();
rgi.album = ImportMpcdecReplayGain(info.gain_album, info.peak_album);
rgi.track = ImportMpcdecReplayGain(info.gain_title, info.peak_title);
return rgi;
}
static void
mpcdec_decode(DecoderClient &client, InputStream &is)
{
@@ -167,14 +189,11 @@ mpcdec_decode(DecoderClient &client, InputStream &is)
mpcdec_sample_format,
info.channels);
ReplayGainInfo rgi;
rgi.Clear();
rgi.album.gain = MPC_OLD_GAIN_REF - (info.gain_album / 256.);
rgi.album.peak = pow(10, info.peak_album / 256. / 20) / 32767;
rgi.track.gain = MPC_OLD_GAIN_REF - (info.gain_title / 256.);
rgi.track.peak = pow(10, info.peak_title / 256. / 20) / 32767;
client.SubmitReplayGain(&rgi);
{
const auto rgi = ImportMpcdecReplayGain(info);
if (rgi.IsDefined())
client.SubmitReplayGain(&rgi);
}
client.Ready(audio_format, is.IsSeekable(),
SongTime::FromS(mpc_streaminfo_get_length(&info)));

@@ -1,5 +1,5 @@
/*
* Copyright 2003-2018 The Music Player Daemon Project
* Copyright 2003-2019 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
@@ -20,6 +20,8 @@
#ifndef MPD_OPUS_READER_HXX
#define MPD_OPUS_READER_HXX
#include "util/StringView.hxx"
#include <algorithm>
#include <stdint.h>
@@ -81,18 +83,16 @@ public:
return ReadWord(length) && Skip(length);
}
char *ReadString() {
StringView ReadString() {
uint32_t length;
if (!ReadWord(length) || length >= 65536)
if (!ReadWord(length))
return nullptr;
const char *src = (const char *)Read(length);
if (src == nullptr)
return nullptr;
char *dest = new char[length + 1];
*std::copy_n(src, length, dest) = 0;
return dest;
return {src, length};
}
};

@@ -22,10 +22,12 @@
#include "lib/xiph/XiphTags.hxx"
#include "tag/Handler.hxx"
#include "tag/ParseName.hxx"
#include "util/ASCII.hxx"
#include "ReplayGainInfo.hxx"
#include <string>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
gcc_pure
@@ -44,7 +46,7 @@ ScanOneOpusTag(const char *name, const char *value,
ReplayGainInfo *rgi,
TagHandler &handler) noexcept
{
if (rgi != nullptr && strcmp(name, "R128_TRACK_GAIN") == 0) {
if (rgi != nullptr && StringEqualsCaseASCII(name, "R128_TRACK_GAIN")) {
/* R128_TRACK_GAIN is a Q7.8 fixed point number in
dB */
@@ -52,7 +54,8 @@ ScanOneOpusTag(const char *name, const char *value,
long l = strtol(value, &endptr, 10);
if (endptr > value && *endptr == 0)
rgi->track.gain = double(l) / 256.;
} else if (rgi != nullptr && strcmp(name, "R128_ALBUM_GAIN") == 0) {
} else if (rgi != nullptr &&
StringEqualsCaseASCII(name, "R128_ALBUM_GAIN")) {
/* R128_ALBUM_GAIN is a Q7.8 fixed point number in
dB */
@@ -91,18 +94,25 @@ ScanOpusTags(const void *data, size_t size,
return false;
while (n-- > 0) {
char *p = r.ReadString();
if (p == nullptr)
const auto s = r.ReadString();
if (s == nullptr)
return false;
char *eq = strchr(p, '=');
if (eq != nullptr && eq > p) {
*eq = 0;
if (s.size >= 4096)
continue;
ScanOneOpusTag(p, eq + 1, rgi, handler);
}
const auto eq = s.Find('=');
if (eq == nullptr || eq == s.data)
continue;
delete[] p;
auto name = s, value = s;
name.SetEnd(eq);
value.MoveFront(eq + 1);
const std::string name2(name.data, name.size);
const std::string value2(value.data, value.size);
ScanOneOpusTag(name2.c_str(), value2.c_str(), rgi, handler);
}
return true;

@@ -25,6 +25,7 @@
#include "song/DetachedSong.hxx"
#include "fs/Path.hxx"
#include "fs/AllocatedPath.hxx"
#include "lib/icu/Converter.hxx"
#ifdef HAVE_SIDPLAYFP
#include "fs/io/FileReader.hxx"
#include "util/RuntimeError.hxx"
@@ -32,6 +33,8 @@
#include "util/Macros.hxx"
#include "util/StringFormat.hxx"
#include "util/Domain.hxx"
#include "util/AllocatedString.hxx"
#include "util/CharUtil.hxx"
#include "system/ByteOrder.hxx"
#include "Log.hxx"
@@ -432,19 +435,70 @@ sidplay_file_decode(DecoderClient &client, Path path_fs)
} while (cmd != DecoderCommand::STOP);
}
static AllocatedString<char>
Windows1252ToUTF8(const char *s) noexcept
{
#ifdef HAVE_ICU_CONVERTER
try {
std::unique_ptr<IcuConverter>
converter(IcuConverter::Create("windows-1252"));
return converter->ToUTF8(s);
} catch (...) { }
#endif
/*
* Fallback to not transcoding windows-1252 to utf-8, that may result
* in invalid utf-8 unless nonprintable characters are replaced.
*/
auto t = AllocatedString<char>::Duplicate(s);
for (size_t i = 0; t[i] != AllocatedString<char>::SENTINEL; i++)
if (!IsPrintableASCII(t[i]))
t[i] = '?';
return t;
}
gcc_pure
static const char *
static AllocatedString<char>
GetInfoString(const SidTuneInfo &info, unsigned i) noexcept
{
#ifdef HAVE_SIDPLAYFP
return info.numberOfInfoStrings() > i
const char *s = info.numberOfInfoStrings() > i
? info.infoString(i)
: nullptr;
: "";
#else
return info.numberOfInfoStrings > i
const char *s = info.numberOfInfoStrings > i
? info.infoString[i]
: nullptr;
: "";
#endif
return Windows1252ToUTF8(s);
}
gcc_pure
static AllocatedString<char>
GetDateString(const SidTuneInfo &info) noexcept
{
/*
* Field 2 is called <released>, previously used as <copyright>.
* It is formatted <year><space><company or author or group>,
* where <year> may be <YYYY>, <YYY?>, <YY??> or <YYYY-YY>, for
* example "1987", "199?", "19??" or "1985-87". The <company or
* author or group> may be for example Rob Hubbard. A full field
* may be for example "1987 Rob Hubbard".
*/
AllocatedString<char> release = GetInfoString(info, 2);
/* Keep the <year> part only for the date. */
for (size_t i = 0; release[i] != AllocatedString<char>::SENTINEL; i++)
if (std::isspace(release[i])) {
release[i] = AllocatedString<char>::SENTINEL;
break;
}
return release;
}
static void
@@ -452,27 +506,25 @@ ScanSidTuneInfo(const SidTuneInfo &info, unsigned track, unsigned n_tracks,
TagHandler &handler) noexcept
{
/* title */
const char *title = GetInfoString(info, 0);
if (title == nullptr)
title = "";
const auto title = GetInfoString(info, 0);
if (n_tracks > 1) {
const auto tag_title =
StringFormat<1024>("%s (%u/%u)",
title, track, n_tracks);
handler.OnTag(TAG_TITLE, tag_title);
title.c_str(), track, n_tracks);
handler.OnTag(TAG_TITLE, tag_title.c_str());
} else
handler.OnTag(TAG_TITLE, title);
handler.OnTag(TAG_TITLE, title.c_str());
/* artist */
const char *artist = GetInfoString(info, 1);
if (artist != nullptr)
handler.OnTag(TAG_ARTIST, artist);
const auto artist = GetInfoString(info, 1);
if (!artist.empty())
handler.OnTag(TAG_ARTIST, artist.c_str());
/* date */
const char *date = GetInfoString(info, 2);
if (date != nullptr)
handler.OnTag(TAG_DATE, date);
const auto date = GetDateString(info);
if (!date.empty())
handler.OnTag(TAG_DATE, date.c_str());
/* track */
handler.OnTag(TAG_TRACK, StringFormat<16>("%u", track));
@@ -547,6 +599,10 @@ sidplay_container_scan(Path path_fs)
AddTagHandler h(tag_builder);
ScanSidTuneInfo(info, i, n_tracks, h);
const SignedSongTime duration = get_song_length(tune);
if (!duration.IsNegative())
h.OnDuration(SongTime(duration));
char track_name[32];
/* Construct container/tune path names, eg.
Delta.sid/tune_001.sid */

@@ -20,18 +20,18 @@
#include "WildmidiDecoderPlugin.hxx"
#include "../DecoderAPI.hxx"
#include "tag/Handler.hxx"
#include "util/Domain.hxx"
#include "util/ScopeExit.hxx"
#include "util/StringFormat.hxx"
#include "fs/AllocatedPath.hxx"
#include "fs/FileSystem.hxx"
#include "fs/Path.hxx"
#include "Log.hxx"
#include "PluginUnavailable.hxx"
extern "C" {
#include <wildmidi_lib.h>
}
static constexpr Domain wildmidi_domain("wildmidi");
static constexpr AudioFormat wildmidi_audio_format{48000, SampleFormat::S16, 2};
static bool
@@ -43,14 +43,27 @@ wildmidi_init(const ConfigBlock &block)
if (!FileExists(path)) {
const auto utf8 = path.ToUTF8();
FormatDebug(wildmidi_domain,
"configuration file does not exist: %s",
utf8.c_str());
return false;
throw PluginUnavailable(StringFormat<1024>("configuration file does not exist: %s",
utf8.c_str()));
}
return WildMidi_Init(path.c_str(), wildmidi_audio_format.sample_rate,
0) == 0;
#ifdef LIBWILDMIDI_VERSION
/* WildMidi_ClearError() requires libwildmidi 0.4 */
WildMidi_ClearError();
AtScopeExit() { WildMidi_ClearError(); };
#endif
if (WildMidi_Init(path.c_str(), wildmidi_audio_format.sample_rate,
0) != 0) {
#ifdef LIBWILDMIDI_VERSION
/* WildMidi_GetError() requires libwildmidi 0.4 */
throw PluginUnavailable(WildMidi_GetError());
#else
throw PluginUnavailable("WildMidi_Init() failed");
#endif
}
return true;
}
static void

@@ -110,15 +110,9 @@ BufferedSocket::OnSocketReady(unsigned flags) noexcept
if (flags & READ) {
assert(!input.IsFull());
if (!ReadToBuffer())
if (!ReadToBuffer() || !ResumeInput())
return false;
if (!ResumeInput())
/* we must return "true" here or
SocketMonitor::Dispatch() will call
Cancel() on a freed object */
return true;
if (!input.IsFull())
ScheduleRead();
}

@@ -46,6 +46,11 @@ public:
using SocketMonitor::Close;
private:
/**
* @return the number of bytes read from the socket, 0 if the
* socket isn't ready for reading, -1 on error (the socket has
* been closed and probably destructed)
*/
ssize_t DirectRead(void *data, size_t length) noexcept;
/**

@@ -45,6 +45,11 @@ public:
}
private:
/**
* @return the number of bytes written to the socket, 0 if the
* socket isn't ready for writing, -1 on error (the socket has
* been closed and probably destructed)
*/
ssize_t DirectWrite(const void *data, size_t length) noexcept;
protected:

@@ -33,8 +33,8 @@ SocketMonitor::Dispatch(unsigned flags) noexcept
{
flags &= GetScheduledFlags();
if (flags != 0 && !OnSocketReady(flags) && IsDefined())
Cancel();
if (flags != 0)
OnSocketReady(flags);
}
SocketMonitor::~SocketMonitor() noexcept

@@ -59,6 +59,9 @@ BufferedInputStream::~BufferedInputStream() noexcept
void
BufferedInputStream::Check()
{
if (read_error)
std::rethrow_exception(read_error);
if (input)
input->Check();
}
@@ -101,7 +104,7 @@ BufferedInputStream::IsEOF() noexcept
bool
BufferedInputStream::IsAvailable() noexcept
{
return IsEOF() || buffer.Read(offset).HasData();
return IsEOF() || buffer.Read(offset).HasData() || read_error;
}
size_t
@@ -164,6 +167,32 @@ BufferedInputStream::RunThread() noexcept
idle = false;
seek = false;
client_cond.signal();
} else if (!idle && !read_error &&
offset != input->GetOffset() &&
!IsAvailable()) {
/* a past Seek() call was a no-op because data
was already available at that position, but
now we've reached a new position where
there is no more data in the buffer, and
our input is reading somewhere else (maybe
stuck at the end of the file); to find a
way out, we now seek our input to our
reading position to be able to fill our
buffer */
try {
input->Seek(offset);
} catch (...) {
/* this is really a seek error, but we
register it as a read_error,
because seek_error is only checked
by Seek(), and at our frontend (our
own InputStream interface) is in
"read" mode */
read_error = std::current_exception();
client_cond.signal();
InvokeOnAvailable();
}
} else if (!idle && !read_error &&
input->IsAvailable() && !input->IsEOF()) {
const auto read_offset = input->GetOffset();

@@ -298,11 +298,7 @@ CdioParanoiaInputStream::Read(void *ptr, size_t length)
if (s_err) {
FormatError(cdio_domain,
"paranoia_read: %s", s_err);
#if LIBCDIO_VERSION_NUM >= 90
cdio_cddap_free_messages(s_err);
#else
free(s_err);
#endif
}
throw;

@@ -22,6 +22,7 @@
#include "lib/smbclient/Mutex.hxx"
#include "../InputStream.hxx"
#include "../InputPlugin.hxx"
#include "../MaybeBufferedInputStream.hxx"
#include "PluginUnavailable.hxx"
#include "system/Error.hxx"
#include "util/ASCII.hxx"
@@ -112,8 +113,9 @@ input_smbclient_open(const char *uri,
throw MakeErrno(e, "smbc_fstat() failed");
}
return std::make_unique<SmbclientInputStream>(uri, mutex,
ctx, fd, st);
return std::make_unique<MaybeBufferedInputStream>
(std::make_unique<SmbclientInputStream>(uri, mutex,
ctx, fd, st));
}
size_t

@@ -180,6 +180,8 @@ InitTidalInput(EventLoop &event_loop, const ConfigBlock &block)
if (password == nullptr)
throw PluginUnavailable("No Tidal password configured");
FormatWarning(tidal_domain, "The Tidal input plugin is deprecated because Tidal has changed the protocol and doesn't share documentation");
tidal_audioquality = block.GetBlockValue("audioquality", "HIGH");
tidal_session = new TidalSessionManager(event_loop, base_url, token,

@@ -6,7 +6,7 @@ if alsa_dep.found()
input_plugins_sources += 'AlsaInputPlugin.cxx'
endif
libcdio_paranoia_dep = dependency('libcdio_paranoia', version: '>= 0.4', required: get_option('cdio_paranoia'))
libcdio_paranoia_dep = dependency('libcdio_paranoia', version: '>= 10.2+0.93+1', required: get_option('cdio_paranoia'))
conf.set('ENABLE_CDIO_PARANOIA', libcdio_paranoia_dep.found())
if libcdio_paranoia_dep.found()
input_plugins_sources += 'CdioParanoiaInputPlugin.cxx'

@@ -34,11 +34,7 @@
#include "util/Compiler.h"
#include <cdio/version.h>
#if LIBCDIO_VERSION_NUM >= 90
#include <cdio/paranoia/paranoia.h>
#else
#include <cdio/paranoia.h>
#endif
#include <stdexcept>
#include <utility>

@@ -69,12 +69,12 @@ OggVisitor::HandlePacket(const ogg_packet &packet)
/* fail if BOS is missing */
throw std::runtime_error("BOS packet expected");
OnOggPacket(packet);
if (packet.e_o_s) {
EndStream();
return;
}
OnOggPacket(packet);
}
inline void

@@ -69,8 +69,21 @@ private:
void HandlePackets();
protected:
/**
* Called when the "beginning of stream" packet has been seen.
*
* @param packet the "beginning of stream" packet
*/
virtual void OnOggBeginning(const ogg_packet &packet) = 0;
/**
* Called for each follow-up packet.
*/
virtual void OnOggPacket(const ogg_packet &packet) = 0;
/**
* Called after the "end of stream" packet has been processed.
*/
virtual void OnOggEnd() = 0;
};

@@ -150,8 +150,6 @@ ReadServers(NeighborExplorer::List &list, int fd)
smbc_dirent *e;
while ((e = smbc_readdir(fd)) != nullptr)
ReadEntry(list, *e);
smbc_closedir(fd);
}
static void

@@ -168,7 +168,7 @@ public:
}
constexpr operator SocketAddress() const noexcept {
return SocketAddress((const struct sockaddr *)&address,
return SocketAddress((const struct sockaddr *)(const void *)&address,
sizeof(address));
}

@@ -135,7 +135,7 @@ public:
}
constexpr operator SocketAddress() const noexcept {
return SocketAddress((const struct sockaddr *)&address,
return SocketAddress((const struct sockaddr *)(const void *)&address,
sizeof(address));
}

@@ -159,6 +159,7 @@ AudioOutputControl::InternalOpen(const AudioFormat in_audio_format,
} catch (...) {
LogError(std::current_exception());
Failure(std::current_exception());
return;
}
if (f != in_audio_format || f != output->out_audio_format)
@@ -458,7 +459,7 @@ AudioOutputControl::Task() noexcept
case Command::RELEASE:
if (!open) {
/* the output has failed after
the PAUSE command was submitted; bail
the RELEASE command was submitted; bail
out */
CommandFinished();
break;

@@ -27,6 +27,7 @@
#include "../OutputAPI.hxx"
#include "mixer/MixerList.hxx"
#include "pcm/PcmExport.hxx"
#include "system/PeriodClock.hxx"
#include "thread/Mutex.hxx"
#include "thread/Cond.hxx"
#include "util/Manual.hxx"
@@ -56,6 +57,17 @@ class AlsaOutput final
DeferEvent defer_invalidate_sockets;
/**
* This timer is used to re-schedule the #MultiSocketMonitor
* after it had been disabled to wait for the next Play() call
* to deliver more data. This timer is necessary to start
* generating silence if Play() doesn't get called soon enough
* to avoid the xrun.
*/
TimerEvent silence_timer;
PeriodClock throttle_silence_log;
Manual<PcmExport> pcm_export;
/**
@@ -109,6 +121,8 @@ class AlsaOutput final
*/
snd_pcm_uframes_t period_frames;
std::chrono::steady_clock::duration effective_period_duration;
/**
* If snd_pcm_avail() goes above this value and no more data
* is available in the #ring_buffer, we need to play some
@@ -128,13 +142,20 @@ class AlsaOutput final
bool work_around_drain_bug;
/**
* After Open(), has this output been activated by a Play()
* command?
* After Open() or Cancel(), has this output been activated by
* a Play() command?
*
* Protected by #mutex.
*/
bool active;
/**
* Is this output waiting for more data?
*
* Protected by #mutex.
*/
bool waiting;
/**
* Do we need to call snd_pcm_prepare() before the next write?
* It means that we put the device to SND_PCM_STATE_SETUP by
@@ -176,7 +197,7 @@ class AlsaOutput final
Alsa::PeriodBuffer period_buffer;
/**
* Protects #cond, #error, #active, #drain.
* Protects #cond, #error, #active, #waiting, #drain.
*/
mutable Mutex mutex;
@@ -248,6 +269,12 @@ private:
return active;
}
gcc_pure
bool LockIsActiveAndNotWaiting() const noexcept {
const std::lock_guard<Mutex> lock(mutex);
return active && !waiting;
}
/**
* Activate the output by registering the sockets in the
* #EventLoop. Before calling this, filling the ring buffer
@@ -260,10 +287,11 @@ private:
* was never unlocked
*/
bool Activate() noexcept {
if (active)
if (active && !waiting)
return false;
active = true;
waiting = false;
const ScopeUnlock unlock(mutex);
defer_invalidate_sockets.Schedule();
@@ -330,9 +358,23 @@ private:
const std::lock_guard<Mutex> lock(mutex);
error = std::current_exception();
active = false;
waiting = false;
cond.signal();
}
/**
* Callback for @silence_timer
*/
void OnSilenceTimer() noexcept {
{
const std::lock_guard<Mutex> lock(mutex);
assert(active);
waiting = false;
}
MultiSocketMonitor::InvalidateSockets();
}
/* virtual methods from class MultiSocketMonitor */
std::chrono::steady_clock::duration PrepareSockets() noexcept override;
void DispatchSockets() noexcept override;
@@ -344,6 +386,7 @@ AlsaOutput::AlsaOutput(EventLoop &_loop, const ConfigBlock &block)
:AudioOutput(FLAG_ENABLE_DISABLE),
MultiSocketMonitor(_loop),
defer_invalidate_sockets(_loop, BIND_THIS_METHOD(InvalidateSockets)),
silence_timer(_loop, BIND_THIS_METHOD(OnSilenceTimer)),
device(block.GetBlockValue("device", "")),
#ifdef ENABLE_DSD
dop_setting(block.GetBlockValue("dop", false) ||
@@ -500,8 +543,9 @@ AlsaOutput::Setup(AudioFormat &audio_format,
alsa_period_size = 1;
period_frames = alsa_period_size;
effective_period_duration = audio_format.FramesToTime<decltype(effective_period_duration)>(period_frames);
/* generate silence if there's less than once period of data
/* generate silence if there's less than one period of data
in the ALSA-PCM buffer */
max_avail_frames = hw_result.buffer_size - hw_result.period_size;
@@ -684,6 +728,7 @@ AlsaOutput::Open(AudioFormat &audio_format)
period_buffer.Allocate(period_frames, out_frame_size);
active = false;
waiting = false;
must_prepare = false;
written = false;
error = {};
@@ -766,7 +811,7 @@ AlsaOutput::DrainInternal()
/* need to call CopyRingToPeriodBuffer() and
WriteFromPeriodBuffer() again in the next
iteration, so don't finish the drain just yet */
return period_buffer.IsEmpty();
return false;
}
if (!written)
@@ -774,6 +819,24 @@ AlsaOutput::DrainInternal()
don't need to drain it */
return true;
switch (snd_pcm_state(pcm)) {
case SND_PCM_STATE_PREPARED:
case SND_PCM_STATE_RUNNING:
/* these states require a call to snd_pcm_drain() */
break;
case SND_PCM_STATE_DRAINING:
/* already draining, but not yet finished; this is
probably a spurious epoll event, and we should wait
for the next one */
return false;
default:
/* all other states cannot be drained, and we're
done */
return true;
}
/* .. and finally drain the ALSA hardware buffer */
int result;
@@ -827,9 +890,11 @@ AlsaOutput::CancelInternal() noexcept
ring_buffer->reset();
active = false;
waiting = false;
MultiSocketMonitor::Reset();
defer_invalidate_sockets.Cancel();
silence_timer.Cancel();
}
void
@@ -858,6 +923,7 @@ AlsaOutput::Close() noexcept
BlockingCall(GetEventLoop(), [this](){
MultiSocketMonitor::Reset();
defer_invalidate_sockets.Cancel();
silence_timer.Cancel();
});
period_buffer.Free();
@@ -912,7 +978,7 @@ AlsaOutput::Play(const void *chunk, size_t size)
std::chrono::steady_clock::duration
AlsaOutput::PrepareSockets() noexcept
{
if (!LockIsActive()) {
if (!LockIsActiveAndNotWaiting()) {
ClearSocketList();
return std::chrono::steady_clock::duration(-1);
}
@@ -977,28 +1043,42 @@ try {
whenever more data arrives */
/* the same applies when there is still enough
data in the ALSA-PCM buffer (determined by
snd_pcm_avail()); this can happend at the
snd_pcm_avail()); this can happen at the
start of playback, when our ring_buffer is
smaller than the ALSA-PCM buffer */
{
const std::lock_guard<Mutex> lock(mutex);
active = false;
waiting = true;
cond.signal();
}
/* avoid race condition: see if data has
arrived meanwhile before disabling the
event (but after clearing the "active"
event (but after setting the "waiting"
flag) */
if (!CopyRingToPeriodBuffer()) {
MultiSocketMonitor::Reset();
defer_invalidate_sockets.Cancel();
/* just in case Play() doesn't get
called soon enough, schedule a
timer which generates silence
before the xrun occurs */
/* the timer fires in half of a
period; this short duration may
produce a few more wakeups than
necessary, but should be small
enough to avoid the xrun */
silence_timer.Schedule(effective_period_duration / 2);
}
return;
}
if (throttle_silence_log.CheckUpdate(std::chrono::seconds(5)))
FormatWarning(alsa_output_domain, "Decoder is too slow; playing silence to avoid xrun");
/* insert some silence if the buffer has not enough
data yet, to avoid ALSA xrun */
period_buffer.FillWithSilence(silence, out_frame_size);

@@ -28,6 +28,8 @@
#include "util/Domain.hxx"
#include "Log.hxx"
#include <atomic>
#include <assert.h>
#include <jack/jack.h>
@@ -69,13 +71,13 @@ struct JackOutput final : AudioOutput {
jack_client_t *client;
jack_ringbuffer_t *ringbuffer[MAX_PORTS];
bool shutdown;
std::atomic_bool shutdown;
/**
* While this flag is set, the "process" callback generates
* silence.
*/
bool pause;
std::atomic_bool pause;
explicit JackOutput(const ConfigBlock &block);
@@ -529,7 +531,10 @@ JackOutput::Start()
jports = nullptr;
}
AtScopeExit(jports) { free(jports); };
AtScopeExit(jports) {
if (jports != nullptr)
jack_free(jports);
};
assert(num_dports > 0);
@@ -540,7 +545,7 @@ JackOutput::Start()
std::fill(dports + num_dports, dports + audio_format.channels,
dports[0]);
} else if (num_dports > audio_format.channels) {
if (audio_format.channels == 1 && num_dports > 2) {
if (audio_format.channels == 1 && num_dports >= 2) {
/* mono input file: connect the one source
channel to the both destination channels */
duplicate_port = dports[1];
@@ -602,7 +607,7 @@ JackOutput::WriteSamples(const float *src, size_t n_frames)
const unsigned n_channels = audio_format.channels;
float *dest[MAX_CHANNELS];
size_t space = -1;
size_t space = SIZE_MAX;
for (unsigned i = 0; i < n_channels; ++i) {
jack_ringbuffer_data_t d[2];
jack_ringbuffer_get_write_vector(ringbuffer[i], d);

@@ -670,12 +670,13 @@ OssOutput::Play(const void *chunk, size_t size)
#ifdef AFMT_S24_PACKED
const auto e = pcm_export->Export({chunk, size});
if (e.empty())
return size;
chunk = e.data;
size = e.size;
#endif
assert(size > 0);
while (true) {
ret = fd.Write(chunk, size);
if (ret > 0) {

@@ -22,7 +22,6 @@
#include "system/FileDescriptor.hxx"
#include "system/Error.hxx"
#include <sys/stropts.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -31,11 +30,18 @@
#ifdef __sun
#include <sys/audio.h>
#include <sys/stropts.h>
#else
/* some fake declarations that allow build this plugin on systems
other than Solaris, just to see if it compiles */
#include <sys/ioctl.h>
#ifndef I_FLUSH
#define I_FLUSH 0
#endif
#define AUDIO_GETINFO 0
#define AUDIO_SETINFO 0
#define AUDIO_ENCODING_LINEAR 0

@@ -71,10 +71,10 @@ HttpdClient::HandleLine(const char *line) noexcept
assert(state != State::RESPONSE);
if (state == State::REQUEST) {
if (memcmp(line, "HEAD /", 6) == 0) {
if (strncmp(line, "HEAD /", 6) == 0) {
line += 6;
head_method = true;
} else if (memcmp(line, "GET /", 5) == 0) {
} else if (strncmp(line, "GET /", 5) == 0) {
line += 5;
} else {
/* only GET is supported */
@@ -83,8 +83,19 @@ HttpdClient::HandleLine(const char *line) noexcept
return false;
}
/* blacklist some well-known request paths */
if ((strncmp(line, "favicon.ico", 11) == 0 &&
(line[11] == '\0' || line[11] == ' ')) ||
(strncmp(line, "robots.txt", 10) == 0 &&
(line[10] == '\0' || line[10] == ' ')) ||
(strncmp(line, "sitemap.xml", 11) == 0 &&
(line[11] == '\0' || line[11] == ' ')) ||
(strncmp(line, ".well-known/", 12) == 0)) {
should_reject = true;
}
line = strchr(line, ' ');
if (line == nullptr || memcmp(line + 1, "HTTP/", 5) != 0) {
if (line == nullptr || strncmp(line + 1, "HTTP/", 5) != 0) {
/* HTTP/0.9 without request headers */
if (head_method)
@@ -129,14 +140,21 @@ HttpdClient::SendResponse() noexcept
assert(state == State::RESPONSE);
if (metadata_requested) {
if (should_reject) {
response =
"HTTP/1.1 404 not found\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n"
"\r\n"
"404 not found";
} else if (metadata_requested) {
allocated =
icy_server_metadata_header(httpd.name, httpd.genre,
httpd.website,
httpd.content_type,
metaint);
response = allocated.c_str();
} else { /* revert to a normal HTTP request */
} else { /* revert to a normal HTTP request */
snprintf(buffer, sizeof(buffer),
"HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\n"
@@ -154,7 +172,7 @@ HttpdClient::SendResponse() noexcept
FormatWarning(httpd_output_domain,
"failed to write to client: %s",
(const char *)msg);
Close();
LockClose();
return false;
}
@@ -415,7 +433,7 @@ HttpdClient::OnSocketInput(void *data, size_t length) noexcept
if (!SendResponse())
return InputResult::CLOSED;
if (head_method) {
if (head_method || should_reject) {
LockClose();
return InputResult::CLOSED;
}
@@ -428,6 +446,7 @@ void
HttpdClient::OnSocketError(std::exception_ptr ep) noexcept
{
LogError(ep);
LockClose();
}
void

@@ -83,6 +83,11 @@ class HttpdClient final
*/
bool head_method = false;
/**
* Should we reject this request?
*/
bool should_reject = false;
/* ICY */
/**
@@ -142,6 +147,8 @@ public:
/**
* Frees the client and removes it from the server's client list.
*
* Caller must lock the mutex.
*/
void Close() noexcept;

@@ -208,10 +208,15 @@ public:
return HasClients();
}
/**
* Caller must lock the mutex.
*/
void AddClient(UniqueSocketDescriptor fd) noexcept;
/**
* Removes a client from the httpd_output.clients linked list.
*
* Caller must lock the mutex.
*/
void RemoveClient(HttpdClient &client) noexcept;
@@ -239,10 +244,14 @@ public:
/**
* Broadcasts data from the encoder to all clients.
*
* Mutext must not be locked.
*/
void BroadcastFromEncoder();
/**
* Mutext must not be locked.
*
* Throws #std::runtime_error on error.
*/
void EncodeAndPlay(const void *chunk, size_t size);
@@ -251,6 +260,9 @@ public:
size_t Play(const void *chunk, size_t size) override;
/**
* Mutext must not be locked.
*/
void CancelAllClients() noexcept;
void Cancel() noexcept override;

@@ -173,7 +173,8 @@ public:
* Export a PCM buffer.
*
* @param src the source PCM buffer
* @return the destination buffer (may be a pointer to the source buffer)
* @return the destination buffer; may be empty (and may be a
* pointer to the source buffer)
*/
ConstBuffer<void> Export(ConstBuffer<void> src) noexcept;

@@ -599,6 +599,19 @@ Player::SeekDecoder() noexcept
{
assert(pc.next_song != nullptr);
if (pc.seek_time > SongTime::zero() && // TODO: allow this only if the song duration is known
dc.IsUnseekableCurrentSong(*pc.next_song)) {
/* seeking into the current song; but we already know
it's not seekable, so let's fail early */
/* note the seek_time>0 check: if seeking to the
beginning, we can simply restart the decoder */
pc.next_song.reset();
pc.SetError(PlayerError::DECODER,
std::make_exception_ptr(std::runtime_error("Not seekable")));
pc.CommandFinished();
return true;
}
CancelPendingSeek();
{
@@ -996,7 +1009,7 @@ Player::Run() noexcept
}
}
if (dc.IsIdle() && queued && dc.pipe == pipe) {
if (dc.IsIdle() && queued && IsDecoderAtCurrentSong()) {
/* the decoder has finished the current song;
make it decode the next song */
@@ -1058,6 +1071,16 @@ Player::Run() noexcept
SongBorder();
} else if (dc.IsIdle()) {
if (queued)
/* the decoder has just stopped,
between the two IsIdle() checks,
probably while UnlockCheckOutputs()
left the mutex unlocked; to restart
the decoder instead of stopping
playback completely, let's re-enter
this loop */
continue;
/* check the size of the pipe again, because
the decoder thread may have added something
since we last checked */

@@ -25,6 +25,9 @@
#include "util/UriUtil.hxx"
#include "song/DetachedSong.hxx"
#include <algorithm>
#include <string>
#include <string.h>
static void
@@ -66,6 +69,22 @@ playlist_check_translate_song(DetachedSong &song, const char *base_uri,
base_uri = nullptr;
const char *uri = song.GetURI();
#ifdef _WIN32
if (!PathTraitsUTF8::IsAbsolute(uri) && strchr(uri, '\\') != nullptr) {
/* Windows uses the backslash as path separator, but
the MPD protocol uses the (forward) slash by
definition; to allow backslashes in relative URIs
loaded from playlist files, this step converts all
backslashes to (forward) slashes */
std::string new_uri(uri);
std::replace(new_uri.begin(), new_uri.end(), '\\', '/');
song.SetURI(std::move(new_uri));
uri = song.GetURI();
}
#endif
if (base_uri != nullptr && !uri_has_scheme(uri) &&
!PathTraitsUTF8::IsAbsolute(uri))
song.SetURI(PathTraitsUTF8::Build(base_uri, uri));

@@ -57,18 +57,6 @@
(GCC_VERSION > 0 && CLANG_VERSION == 0 && \
GCC_VERSION < GCC_MAKE_VERSION(major, minor, 0))
#ifdef __clang__
# if __clang_major__ < 3
# error Sorry, your clang version is too old. You need at least version 3.1.
# endif
#elif defined(__GNUC__)
# if GCC_OLDER_THAN(6,0)
# error Sorry, your gcc version is too old. You need at least version 6.0.
# endif
#else
# warning Untested compiler. Use at your own risk!
#endif
/**
* Are we building with the specified version of clang or newer?
*/

41
src/util/RecursiveMap.hxx Normal file

@@ -0,0 +1,41 @@
/*
* Copyright 2019 Max Kellermann <max.kellermann@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RECURSIVE_MAP_HXX
#define RECURSIVE_MAP_HXX
#include <map>
/**
* A #std::map which contains instances of itself.
*/
template<typename Key>
class RecursiveMap : public std::map<Key, RecursiveMap<Key>> {};
#endif

@@ -56,11 +56,11 @@ protected:
T data[size];
public:
constexpr size_type GetCapacity() const {
constexpr size_type GetCapacity() const noexcept {
return size;
}
void Shift() {
void Shift() noexcept {
if (head == 0)
return;
@@ -74,15 +74,15 @@ public:
head = 0;
}
void Clear() {
void Clear() noexcept {
head = tail = 0;
}
bool empty() const {
constexpr bool empty() const noexcept {
return head == tail;
}
bool IsFull() const {
constexpr bool IsFull() const noexcept {
return head == 0 && tail == size;
}
@@ -90,7 +90,7 @@ public:
* Prepares writing. Returns a buffer range which may be written.
* When you are finished, call Append().
*/
Range Write() {
Range Write() noexcept {
if (empty())
Clear();
else if (tail == size)
@@ -103,7 +103,7 @@ public:
* Expands the tail of the buffer, after data has been written to
* the buffer returned by Write().
*/
void Append(size_type n) {
void Append(size_type n) noexcept {
assert(tail <= size);
assert(n <= size);
assert(tail + n <= size);
@@ -111,18 +111,22 @@ public:
tail += n;
}
constexpr size_type GetAvailable() const noexcept {
return tail - head;
}
/**
* Return a buffer range which may be read. The buffer pointer is
* writable, to allow modifications while parsing.
*/
Range Read() {
constexpr Range Read() noexcept {
return Range(data + head, tail - head);
}
/**
* Marks a chunk as consumed.
*/
void Consume(size_type n) {
void Consume(size_type n) noexcept {
assert(tail <= size);
assert(head <= tail);
assert(n <= tail);

@@ -50,7 +50,7 @@ protected:
/* virtual methods from class SocketMonitor */
bool OnSocketReady(gcc_unused unsigned flags) noexcept override {
DNSServiceProcessResult(service_ref);
return false;
return true;
}
};

@@ -1,5 +1,5 @@
[Socket]
ListenStream=/run/mpd/socket
ListenStream=%t/mpd/socket
ListenStream=6600
Backlog=5
KeepAlive=true

@@ -3,6 +3,12 @@ if systemd_user_unit_dir == ''
systemd_user_unit_dir = join_paths(get_option('prefix'), 'lib', 'systemd', 'user')
endif
# copy the system socket unit to the "user" directory
install_data(
join_paths('..', 'system', 'mpd.socket'),
install_dir: systemd_user_unit_dir,
)
configure_file(
input: 'mpd.service.in',
output: 'mpd.service',

@@ -23,7 +23,7 @@
#include "event/Thread.hxx"
#include "decoder/DecoderList.hxx"
#include "decoder/DecoderPlugin.hxx"
#include "decoder/Client.hxx"
#include "decoder/DecoderAPI.hxx" /* for class StopDecoder */
#include "input/Init.hxx"
#include "input/InputStream.hxx"
#include "fs/Path.hxx"
@@ -244,10 +244,16 @@ try {
ChromaprintDecoderClient client;
if (plugin->file_decode != nullptr) {
plugin->FileDecode(client, Path::FromFS(c.uri));
try {
plugin->FileDecode(client, Path::FromFS(c.uri));
} catch (StopDecoder) {
}
} else if (plugin->stream_decode != nullptr) {
auto is = InputStream::OpenReady(c.uri, client.mutex);
plugin->StreamDecode(client, *is);
try {
plugin->StreamDecode(client, *is);
} catch (StopDecoder) {
}
} else {
fprintf(stderr, "Decoder plugin is not usable\n");
return EXIT_FAILURE;

@@ -21,6 +21,7 @@
#include "event/Thread.hxx"
#include "decoder/DecoderList.hxx"
#include "decoder/DecoderPlugin.hxx"
#include "decoder/DecoderAPI.hxx" /* for class StopDecoder */
#include "DumpDecoderClient.hxx"
#include "input/Init.hxx"
#include "input/InputStream.hxx"
@@ -116,10 +117,16 @@ try {
DumpDecoderClient client;
if (plugin->file_decode != nullptr) {
plugin->FileDecode(client, Path::FromFS(c.uri));
try {
plugin->FileDecode(client, Path::FromFS(c.uri));
} catch (StopDecoder) {
}
} else if (plugin->stream_decode != nullptr) {
auto is = InputStream::OpenReady(c.uri, client.mutex);
plugin->StreamDecode(client, *is);
try {
plugin->StreamDecode(client, *is);
} catch (StopDecoder) {
}
} else {
fprintf(stderr, "Decoder plugin is not usable\n");
return EXIT_FAILURE;

@@ -207,7 +207,6 @@ TEST_F(TranslateSongTest, Insecure)
TEST_F(TranslateSongTest, Secure)
{
DetachedSong song1(uri1, MakeTag1b());
auto s1 = ToString(song1);
auto se = ToString(DetachedSong(uri1, MakeTag1c()));
const SongLoader loader(nullptr, nullptr);
@@ -226,14 +225,12 @@ TEST_F(TranslateSongTest, InDatabase)
loader));
DetachedSong song2(uri2, MakeTag2b());
auto s1 = ToString(song2);
auto se = ToString(DetachedSong(uri2, MakeTag2c()));
EXPECT_TRUE(playlist_check_translate_song(song2, nullptr,
loader));
EXPECT_EQ(se, ToString(song2));
DetachedSong song3("/music/foo/bar.ogg", MakeTag2b());
s1 = ToString(song3);
se = ToString(DetachedSong(uri2, MakeTag2c()));
EXPECT_TRUE(playlist_check_translate_song(song3, nullptr,
loader));
@@ -249,7 +246,6 @@ TEST_F(TranslateSongTest, Relative)
/* map to music_directory */
DetachedSong song1("bar.ogg", MakeTag2b());
auto s1 = ToString(song1);
auto se = ToString(DetachedSong(uri2, MakeTag2c()));
EXPECT_TRUE(playlist_check_translate_song(song1, "/music/foo",
insecure_loader));
@@ -262,7 +258,6 @@ TEST_F(TranslateSongTest, Relative)
/* legal because secure=true */
DetachedSong song3("bar.ogg", MakeTag1b());
s1 = ToString(song3);
se = ToString(DetachedSong(uri1, MakeTag1c()));
EXPECT_TRUE(playlist_check_translate_song(song3, "/foo",
secure_loader));
@@ -270,9 +265,28 @@ TEST_F(TranslateSongTest, Relative)
/* relative to http:// */
DetachedSong song4("bar.ogg", MakeTag2a());
s1 = ToString(song4);
se = ToString(DetachedSong("http://example.com/foo/bar.ogg", MakeTag2a()));
EXPECT_TRUE(playlist_check_translate_song(song4, "http://example.com/foo",
insecure_loader));
EXPECT_EQ(se, ToString(song4));
}
TEST_F(TranslateSongTest, Backslash)
{
const SongLoader loader(reinterpret_cast<const Database *>(1),
storage);
DetachedSong song1("foo\\bar.ogg", MakeTag2b());
#ifdef _WIN32
/* on Windows, all backslashes are converted to slashes in
relative paths from playlists */
auto se = ToString(DetachedSong(uri2, MakeTag2c()));
EXPECT_TRUE(playlist_check_translate_song(song1, nullptr,
loader));
EXPECT_EQ(se, ToString(song1));
#else
/* backslash only supported on Windows */
EXPECT_FALSE(playlist_check_translate_song(song1, nullptr,
loader));
#endif
}